加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang`http.Request`的`Host`和`URL.Host`有什么区别?

发布时间:2020-12-16 19:04:23 所属栏目:大数据 来源:网络整理
导读:在开发golang http应用程序时,我经常使用http.Request.当访问请求主机地址时,我会使用req.Host,但我发现有req.URL.Host字段,但是当我打印它时,它是空的. func handler(w http.ResponseWriter,r *http.Request) { fmt.Println("uri Host: " + r.URL.Host + "
在开发golang http应用程序时,我经常使用http.Request.当访问请求主机地址时,我会使用req.Host,但我发现有req.URL.Host字段,但是当我打印它时,它是空的.
func handler(w http.ResponseWriter,r *http.Request) {
    fmt.Println("uri Host: " + r.URL.Host + " Scheme: " + r.URL.Scheme)
    fmt.Println("Host: " + r.Host)
}

http.Request的文档给出了以下注释,而net / url没有提供太多线索.

// For server requests Host specifies the host on which the
// URL is sought. Per RFC 2616,this is either the value of
// the "Host" header or the host name given in the URL itself.
// It may be of the form "host:port". For international domain
// names,Host may be in Punycode or Unicode form. Use
// golang.org/x/net/idna to convert it to either format if
// needed.
//
// 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

在我看来,请求中有两个主机值:uri行和主机头,如:

GET http://localhost:8080/ HTTP/1.1
Host: localhost:8080

但它并没有解决许多问题而不是它造成的问题:

>为什么请求中有两个不同的主机字段?我的意思是这不是重复的吗?
>同一个请求中的两个主机字段可以不同吗?
>我应该在哪种情况下使用哪一个?

具有真实HTTP请求示例的答案将是最好的.提前致谢.

通过解析HTTP请求URI来创建 r.URL字段.

r.Host字段是Host request header的值.它与调用r.Header.Get(“Host”)的值相同.

如果线路上的HTTP请求是:

GET /pub/WWW/TheProject.html HTTP/1.1
 Host: www.example.org:8080

然后r.URL.Host是“”而r.Host是www.example.org:8080.

r.URL.Host和r.Host的值几乎总是不同的.在代理服务器上,r.URL.Host是目标服务器的主机,r.Host是代理服务器本身的主机.未通过代理连接时,客户端不会在请求URI中指定主机.在这种情况下,r.URL.Host是空字符串.

如果您没有实现代理,那么您应该使用r.Host来确定主机.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读