【问题标题】:What is the difference between `Host` and `URL.Host` for golang `http.Request`?golang`http.Request`的`Host`和`URL.Host`有什么区别?
【发布时间】:2017-03-21 19:43:02
【问题描述】:

在开发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 的文档给出了以下 cmets,而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 行和Host 标头,例如:

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

但它解决的问题并不多于它产生的问题:

  1. 为什么请求中有两个不同的Host 字段?我的意思是这不是重复的吗?
  2. 同一个请求中的两个Host字段可以不同吗?
  3. 我应该在什么情况下使用哪个?

最好使用真实的 HTTP 请求示例来回答。提前致谢。

【问题讨论】:

    标签: http go


    【解决方案1】:

    r.URL 字段是通过解析 HTTP 请求 URI 创建的。

    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.Hostwww.example.org:8080

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

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

    【讨论】:

      【解决方案2】:

      基本上http.Request.Host 是为了方便。

      r.Hostr.Header.Get("Host")r.URL.Host 更容易调用。

      还需要注意的是,某些路由器会从http.Request.URL 中剥离主机,因此http.Request.Host 在这些情况下也很有用。

      因此可以认为 req.Host 提供了 Host 值,即使请求头或 url 已在别处修改。

      【讨论】:

      • "另外需要注意的是,有些路由器会从 http.Request.URL 中剥离主机"——不仅仅是路由器;代理也可以剥离或修改它。
      猜你喜欢
      • 1970-01-01
      • 2018-12-21
      • 2011-10-28
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      • 2011-07-05
      • 2020-05-01
      相关资源
      最近更新 更多