Menu Close

Go – HTTP ParseHTTPVersion Function in Go

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

The ParseHTTPVersion function parse an HTTP version string and return the major and minor version numbers.

syntax

func ParseHTTPVersion(vers string) (major, minor int, ok bool)

The ParseHTTPVersion function takes a single argument:

  1. vers: A string representing the HTTP version (e.g., “HTTP/1.1”).

The function returns three values:

  1. major: An integer representing the major version number of the HTTP protocol (e.g., 1 for HTTP/1.1).
  2. minor: An integer representing the minor version number of the HTTP protocol (e.g., 1 for HTTP/1.1).
  3. ok: A boolean value that indicates whether the parsing was successful. It returns true if the parsing was successful, and false otherwise.

Example:

package main


import (

	"fmt"

	"net/http"

)


func main() {

	httpVersion := "HTTP/1.1"


	major, minor, ok := http.ParseHTTPVersion(httpVersion)


	if ok {

		fmt.Printf("Major Version: %d\n", major)

		fmt.Printf("Minor Version: %d\n", minor)

	} else {

		fmt.Println("Invalid HTTP version string")

	}

}

In this example, we define an HTTP version string “HTTP/1.1” and use the ParseHTTPVersion function to parse it. If the parsing is successful, the major and minor version numbers are printed; otherwise, an error message is displayed.

Output:

Major Version: 1
Minor Version: 1

Handling Invalid HTTP Version Strings

If the provided version string is not a valid HTTP version, then function returns ok as false. Let’s look at an example to see how this works.

package main


import (

	"fmt"

	"net/http"

)


func main() {

	httpVersion := "InvalidVersion"


	major, minor, ok := http.ParseHTTPVersion(httpVersion)


	if ok {

		fmt.Printf("Major Version: %d\n", major)

		fmt.Printf("Minor Version: %d\n", minor)

	} else {

		fmt.Println("Invalid HTTP version string")

	}

}

In this case, since the provided string “InvalidVersion” is not a valid HTTP version, the function returns ok as false, and the “Invalid HTTP version string” error message is displayed.

Output:

Invalid HTTP version string

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

https://www.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 *