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

huangapple go评论124阅读模式
英文:

How to set headers in http get request?

问题

我在Go中进行了一个简单的HTTP GET请求:

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

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

英文:

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

答案1

得分: 373

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

req.Header.Set("name", "value")
英文:

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

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

答案2

得分: 83

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

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)

答案3

得分: 47

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

client := http.Client{}
req , err := http.NewRequest("GET", url, nil)
if err != nil {
    //处理错误
}

req.Header = http.Header{
    "Host": {"www.host.com"},
    "Content-Type": {"application/json"},
    "Authorization": {"Bearer Token"},
}

res , err := client.Do(req)
if err != nil {
    //处理错误
}
英文:

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
}

答案4

得分: 0

Go的net/http包有许多处理头部的函数。其中包括Add、Del、Get和Set方法。使用Set方法的方式如下:

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

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")
}

huangapple
  • 本文由 发表于 2012年10月13日 01:33:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/12864302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定