How to set headers in http get request?

2019-01-31 21:52发布

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 go
3条回答
Viruses.
2楼-- · 2019-01-31 22:16

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"

resp, err := http.Client.Do(req)
查看更多
forever°为你锁心
3楼-- · 2019-01-31 22:32

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")
}
查看更多
不美不萌又怎样
4楼-- · 2019-01-31 22:35

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

req.Header.Set("name", "value")
查看更多
登录 后发表回答