273

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

Forge
  • 6,538
  • 6
  • 44
  • 64
wong2
  • 34,358
  • 48
  • 134
  • 179

4 Answers4

376

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

req.Header.Set("name", "value")
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
84

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)
jk2K
  • 4,279
  • 3
  • 37
  • 40
Oleg Neumyvakin
  • 9,706
  • 3
  • 58
  • 62
48

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": {"www.host.com"},
    "Content-Type": {"application/json"},
    "Authorization": {"Bearer Token"},
}

res , err := client.Do(req)
if err != nil {
    //Handle Error
}
Sandeep
  • 545
  • 6
  • 9
0

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")
}
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 7
    what type is w ? – Eswar Yaganti Aug 15 '17 at 18:21
  • @EswarYaganti how are you sending the headers? You get a `r *http.Request` and returns back something in `w http.ResponseWriter`. So probably because you are returning headers, you need to write them in a response writer. And `w` is a response writer. Does this look logical to you? – Salvador Dali Dec 05 '17 at 06:05
  • 19
    The original poster said he wants to "customize the *request* header". Your example customizes the *response* header. – Martin Del Vecchio Jan 24 '19 at 17:54