描述
最近在写一个文件下载(下载一个 Shell 脚本并执行),遇到了获取 Request Hostname 为空的问题
细节
模板:
#!/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
代码:
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 中也会被屏蔽掉。
