Go:设置HTTP请求头域Header的Host无效

43 篇文章 3 订阅
30 篇文章 1 订阅

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
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值