英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论