如何在http get请求中设置标头?

won*_*ng2 122 http go

我在Go中做了一个简单的http GET:

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

但我找不到在doc中自定义请求标头的方法,谢谢

Den*_*ret 197

Header请求的字段是公开的.你可以这样做:

req.Header.Set("name", "value")
Run Code Online (Sandbox Code Playgroud)


San*_*eep 52

如果您想设置多个标头,这比编写 set 语句更方便。

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
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*kin 28

注意在http.Request标题中"Host"不能通过Set方法设置

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

但可以直接设置:

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)
Run Code Online (Sandbox Code Playgroud)

  • 救命的答案!! (3认同)