go中发送http请求header修改host不生效

271 阅读1分钟

背景

因为公司的业务原因,我需要在A机器上通过http调用C机器上的服务,中间会通过B机器上安装的nginx进行转发,由于nginx配置了server_name,因此需要在http发放请求的时候带上host这个首部,才能找到正确的转发地址。‘

发现问题

通过curl能访问到服务

curl "http://192.168.132.145:80/user/info/get?page=1&size=10000&ts=1685690510" --header "host: user.info.com" --header "sign: d16ab87deff0b7d69073bae040f00370"

通过golang的http的请求就出来错误

<html>
<head><title>500 Internal Server Error</title></head>
<body bgcolor="white">
<center><h1>500 Internal Server Error</h1></center>
<hr><center>openresty</center>
</body>
</html>

打印golang中的request对象也没发现异常

http request: &{GET http://192.168.132.145:80/user/info/get?page=1&size=10000&ts=1685690510 HTTP/1.1 1 1 map[Host:[user.info.com] Sign:[d16ab87deff0b7d69073bae040f00370]] <nil> <nil> 0 [] false 192.168.132.145:80 map[] map[] <nil> map[]   <nil> <nil> <nil> 0xc00001a110}

定位问题

通过tcpdump命令查找具体的http请求包

tcpdump -i eth0 tcp and  host 192.168.132.145 -Xvvv

发现http的host并没有修改

GET user/info/get?page=1&size=10000&ts=1685691591 HTTP/1.1
Host: 192.168.132.145:80
User-Agent: Go-http-client/1.1
Sign: d16ab87deff0b7d69073bae040f00370
Accept-Encoding: gzip`

查看修改host信息的代码:

req.Header.Set("Host","user.info.com")

查找网上相关的文档,发现Host这么修改是不生效的。

解决办法

这么修改host的话,抓包获取得到的Host就已经被修改了。

    req.Host = "user.info.com"