How can I read a header from an http request in golang?

Go

Go Problem Overview


If I receive a request of type http.Request, how can I read the value of a specific header? In this case I want to pull the value of a jwt token out of the request header.

Go Solutions


Solution 1 - Go

You can use the r.Header.Get:

func yourHandler(w http.ResponseWriter, r *http.Request) {
	ua := r.Header.Get("User-Agent")
    ...
}

Solution 2 - Go

package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s %s %s \n", r.Method, r.URL, r.Proto)
	//Iterate over all header fields
	for k, v := range r.Header {
		fmt.Fprintf(w, "Header field %q, Value %q\n", k, v)
	}

	fmt.Fprintf(w, "Host = %q\n", r.Host)
	fmt.Fprintf(w, "RemoteAddr= %q\n", r.RemoteAddr)
	//Get value for a specified token
	fmt.Fprintf(w, "\n\nFinding value of \"Accept\" %q", r.Header["Accept"])
}

Connecting to http://localhost:8000/ from a browser will print the output in the browser.

Solution 3 - Go

Note: The accepted answer is missing some information.

A Header represents the key-value pairs in an HTTP header. It's defined as a map where key is of string type and value is an array of string type.

type Header map[string][]string

Actually, r.Header.Get gets the first value associated with the given key i.e. it just gets the first string from index 0.

This is okay if your header just have one value but if it has multiple values, you may miss out on some information.

Eg. User-Agent header has multiple values against the same key.

user-agent: ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)",  "AppleWebKit/537.36 (KHTML, like Gecko)", "Chrome/80.0.3987.106 Safari/537.36",]

So if you use r.Header.get("User-Agent") , it'll return Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) only and not the rest of the values.

If you want to get all the values you can use this:

req.Header["User-Agent"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyman ElmubarkView Question on Stackoverflow
Solution 1 - GonbariView Answer on Stackoverflow
Solution 2 - GoRavi RView Answer on Stackoverflow
Solution 3 - GoFaaduBaalakView Answer on Stackoverflow