Go 学习笔记 - Go Request Header 中的 Host 为空

本文最后更新于:2023年4月25日 晚上

描述

最近在写一个文件下载(下载一个 Shell 脚本并执行),遇到了获取 Request Hostname 为空的问题

细节

模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/sh

set -e

curl -kSL https://XXX/download/linux_x`getconf LONG_BIT`/XXX_`uname -m` -o /usr/bin/XXX

if [ ! -s /usr/bin/XXX ]; then
echo "Download Error : No agent version suitable for the current system was found";
else
chmod +x /usr/bin/XXX

XXX register --host --paramA paramA --paramB paramB

XXX install

XXX start
fi

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func ShellDownload(c *gin Context) {
var (
err error
paramA string
paramB string
content string
hostname string
)
defer func() {
if err != nil {
c.String(http.StatusBadRequest, content)
return
}
}()

params := map[string]interface{}{
"Host": c.Request.Header.Get("Hostname"),
"paramA": paramA,
"paramB": paramB,
}
buf := &bytes.Buffer{}
err = config.Tpl.ExecuteTemplate(buf, config.InstallTpl, params)
if err != nil {
content = `echo "Download Error : System Internal Error"`
return
}

c.String(http.Status0K, buf.String())
}

总结

根据 Go 语言 http 包解释,当服务器接受的请求带有 header line,会把 host 的头从映射中删除,并把 host 放到 Request.Host 中,所以从 Request.Host 中获取就可以了,当然,如果你请求时指定 host 如果是直接放在 header 中也会被屏蔽掉。

参考


Go 学习笔记 - Go Request Header 中的 Host 为空
https://agopher.com/2019/11/22/tech/2019_go_get_hostname_failed/
作者
冷宇生(Allen)
发布于
2019年11月22日
更新于
2023年4月25日
许可协议