如何在Go中获取所有请求标头

How can I obtain all available http headers from a request as array in Go? I see only the following two methods:

  • Header(name string, value string)
  • GetHeader(name string)

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.

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)
    }
}

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
}

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))
}