How to obtain all request headers in Go

You can use above approaches if you want to loop one by one through all headers. If you want to print all headers in one line you can,

if reqHeadersBytes, err := json.Marshal(req.Header); err != nil {
    log.Println("Could not Marshal Req Headers")
} else {
    log.Println(string(reqHeadersBytes))
}

Use Request.Header to access all headers. Because Header is a map[string][]string, two loops are required to access all headers.

// Loop over header names
for name, values := range r.Header {
    // Loop over all values for the name.
    for _, value := range values {
        fmt.Println(name, value)
    }
}

Tags:

Go