How to set headers in http get request?

HttpGo

Http Problem Overview


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

Http Solutions


Solution 1 - Http

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

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

Solution 2 - Http

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 - Http

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
}

Solution 4 - Http

Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

func yourHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("header_name", "header_value")
}

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
Questionwong2View Question on Stackoverflow
Solution 1 - HttpDenys SéguretView Answer on Stackoverflow
Solution 2 - HttpOleg NeumyvakinView Answer on Stackoverflow
Solution 3 - HttpWhite2001View Answer on Stackoverflow
Solution 4 - HttpSalvador DaliView Answer on Stackoverflow