Menu Close

Go – HTTP ParseTime Function in Go

In this article, we will explore the http ParseTime function in Go net/http package in detail, along with examples.

The http ParseTime function parses a time string in the HTTP/1.1 format and returns a time.Time value.

syntax

func ParseTime(text string) (t time.Time, err error)

The ParseTime function takes a single argument:

  1. text: A string representing a date-time value in the HTTP/1.1 format (e.g., “Sun, 06 Nov 1994 08:49:37 GMT”).

The function returns two values:

  1. t: A time.Time value representing the parsed date-time value.
  2. err: An error value indicating whether the parsing was successful. It returns nil if the parsing was successful, and an error otherwise.

The http.ParseTime function supports parsing date-time strings in three standard formats specified by the HTTP/1.1 protocol:

  1. RFC 1123: “Mon, 02 Jan 2006 15:04:05 GMT”
  2. RFC 850: “Monday, 02-Jan-06 15:04:05 GMT”
  3. ANSI C’s asctime(): “Mon Jan _2 15:04:05 2006”

Example Usage

Let’s demonstrate with a simple example.

package main


import (

	"fmt"

	"net/http"

)


func main() {

	httpTimeString := "Sun, 06 Nov 1994 08:49:37 GMT"


	t, err := http.ParseTime(httpTimeString)


	if err == nil {

		fmt.Printf("Parsed time: %s\n", t)

	} else {

		fmt.Println("Error parsing HTTP time:", err)

	}

}

In this example, we define an HTTP date-time string “Sun, 06 Nov 1994 08:49:37 GMT” and use the ParseTime function to parse it. If the parsing is successful, the parsed time is printed; otherwise, an error message is displayed.

Output:

Parsed time: 1994-11-06 08:49:37 +0000 UTC

Handling Invalid HTTP Time Strings

If the provided time string is not in a valid HTTP/1.1 format, then it returns an error. Let’s look at an example to see how this works.

package main


import (

	"fmt"

	"net/http"

)


func main() {

	httpTimeString := "InvalidTime"


	t, err := http.ParseTime(httpTimeString)


	if err == nil {

		fmt.Printf("Parsed time: %s\n", t)

	} else {

		fmt.Println("Error parsing HTTP time:", err)

	}

}

In this case, since the provided string “InvalidTime” is not a valid HTTP time format, the function returns an error, and the “Error parsing HTTP time” message is displayed.

Output:

Error parsing HTTP time: parsing time "InvalidTime" as "Mon Jan _2 15:04:05 2006": cannot parse "InvalidTime" as "Mon"

To check more Go related articles. Pls click given below link:

https://techieindoor.com/go-net-http-package-in-go-golang/

https://pkg.go.dev/net/http

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *