在http请求中设置UserAgent
问题描述:
我正在尝试使我的Go应用程序将其自身指定为特定的 UserAgent
,但是找不到有关如何使用 net/http
进行此操作的任何信息.我正在创建一个 http.Client
,并使用它通过 client.Get()
发出 Get
请求.
I'm trying to make my Go application specify itself as a specific UserAgent
, but can't find anything on how to go about doing this with net/http
. I'm creating an http.Client
, and using it to make Get
requests, via client.Get()
.
是否可以在客户端中设置 UserAgent
或完全设置?
Is there a way to set the UserAgent
in the Client, or at all?
答
在创建请求时,请使用 request.Header.Set("key","value")
:
When creating your request use request.Header.Set("key", "value")
:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://httpbin.org/user-agent", nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("User-Agent", "Golang_Spider_Bot/3.0")
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println(string(body))
}
结果:
2012/11/07 15:05:47 {
"user-agent": "Golang_Spider_Bot/3.0"
}
P.S. http://httpbin.org 对于测试这种东西真是太神奇了!
P.S. http://httpbin.org is amazing for testing this kind of thing!