golang net/http包设置host

1. 通过req.Header.Set或者req.Header.Add设置host不生效

1
2
3
4
5
6
7
8
9
10
11
12
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("HOST", "www.baidu.com")
res, err := client.Do(req)
if err != nil {
panic(err)
}
_, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
panic(err)
}

2. 解决

1
2
3
4
5
6
7
8
9
10
11
12
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.Host = "www.baidu.com"
res, err := client.Do(req)
if err != nil {
panic(err)
}
_, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
panic(err)
}