Reputation: 881
How can I obtain all available http headers from a request as array in Go? I see only the following two methods:
But in this case I need to know the name of the Header and can't return all existing headers. I'd like to copy the http headers from one request to anther one.
Upvotes: 33
Views: 45159
Reputation: 561
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))
}
Upvotes: 11
Reputation: 120941
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)
}
}
Upvotes: 67
Reputation: 46433
As you can see from the documentation, Header
is just a map[string][]string
with some extra helper methods, so you can still use it like any map
to access its keys:
for key,val := range req.Header {
// Logic using key
// And val if you need it
}
Upvotes: 7