Menu Close

Go – Convert header key to its canonical form in go

In this article, we are going to learn how to convert header key to its canonical form in go lang.

The CanonicalHeaderKey function in Go is a built-in function that is used to convert a given header key to its canonical form. The canonical form of a header key is the title-cased version of the header key, with the first letter of each word capitalized. For example, “content-type” becomes “Content-Type”, “etag” becomes “Etag”, and so on.

Syntax:

func CanonicalHeaderKey(s string) string

The CanonicalHeaderKey function takes a string argument representing the header key and returns the canonical version of the key. If the input string is an empty string, the function returns an empty string.

Here is an example usage of the CanonicalHeaderKey function:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	header := http.Header{}
	
	header.Add("content-type", "application/json")
	header.Add("x-custom-header", "custom-value")

	for key, value := range header {
		fmt.Printf("Key: %s, Value: %s\n", http.CanonicalHeaderKey(key), value)
	}
}

In this example, we create an http.Header object and add two headers to it. We then iterate over the headers and use the CanonicalHeaderKey function to convert the header key to its canonical form before printing it along with the header value.

Output:

Key: Content-Type, Value: [application/json]
Key: X-Custom-Header, Value: [custom-value]

As you can see, the CanonicalHeaderKey function has converted the header keys to their canonical form, making them more readable and easier to work with.

In summary, the CanonicalHeaderKey function in Go is a useful function that can help you convert header keys to their canonical form. By using this function, you can ensure that your header keys are consistent and easy to work with, which can be particularly useful when working with HTTP requests and responses.

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in golang, net, packages

Leave a Reply

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