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

新手上路,请多包涵

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

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

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

原文由 wong2 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

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

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

原文由 Denys Séguret 发布,翻译遵循 CC BY-SA 3.0 许可协议

请注意,在 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)

原文由 Oleg Neumyvakin 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题