Go:设置HTTP请求头域Header的Host无效
通常,设置HTTP请求头域Header键值对是通过http.Header.Set接口设置,例如:
req.Header.Set("KEY", "VALUE")
 
但是,在设置Host字段时,却发现设置无效。
测试样例
服务端代码:
package main
import (
	"encoding/json"
	"log"
	"net/http"
)
func main() {
	http.HandleFunc("/", handle)
	log.Fatal(http.ListenAndServe(":1280", nil))
}
func handle(w http.ResponseWriter, r *http.Request) {
	respBody, err := json.Marshal(struct {
		Host string
	}{
		Host: r.Host,
	})
	if err != nil {
		panic(err)
	}
	w.Write(respBody)
}
 
客户端代码:
package main
import (
	"fmt"
	"io/ioutil"
	"net/http"
)
func main() {
	req, err := http.NewRequest("GET", "http://127.0.0.1:1280/", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Host", "www.test1280.cn")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(respBody))
}
 
运行服务端:
>go run http_server.go 
^Csignal: interrupt
 
运行客户端:
>go run http_client.go 
{"Host":"127.0.0.1:1280"}
 
我在客户端代码中通过http.Header.Set的方式设置Host,但是设置无效,使用了URL中的IP:PORT作为Host值。
net/http/request.go
	// For client requests, Host optionally overrides the Host
	// header to send. If empty, the Request.Write method uses
	// the value of URL.Host. Host may contain an international
	// domain name.
	Host string
 
正确方式:Go中设置Host,是通过http.Request.Host="$HOST"设置的。
通过http.Request方式设置Host样例:
package main
import (
	"fmt"
	"io/ioutil"
	"net/http"
)
func main() {
	req, err := http.NewRequest("GET", "http://127.0.0.1:1280/", nil)
	if err != nil {
		panic(err)
	}
	req.Host = "www.test1280.com"
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(respBody))
}
 
重点在于:
原先代码:
req.Header.Set("Host", "www.test1280.cn")
 
正确代码:
req.Host = "www.test1280.com"
 
参考:
- https://github.com/golang/go/issues/7682
 - https://www.cnblogs.com/jinsdu/p/5161962.html
 - https://segmentfault.com/a/1190000021244633?utm_source=tag-newest
 - https://wuguiyunwei.com/index.php/2014/02/28/1465.html
 - https://blog.csdn.net/yuanlaidewo000/article/details/93750653
 - https://stackoverflow.com/questions/12864302/how-to-set-headers-in-http-get-request