How to set headers in http get request?

I'm doing a simple http GET in Go:

client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
res, _ := client.Do(req)

But I can't found a way to customize the request header in the doc, thanks


Solution 1:

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

Solution 2:

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

Solution 3:

If you want to set more than one header, this can be handy rather than writing set statements.

client := http.Client{}
req , err := http.NewRequest("GET", url, nil)
if err != nil {
    //Handle Error
}

req.Header = http.Header{
    "Host": []string{"www.host.com"},
    "Content-Type": []string{"application/json"},
    "Authorization": []string{"Bearer Token"},
}

res , err := client.Do(req)
if err != nil {
    //Handle Error
}