douba9425 2017-03-21 08:17 采纳率: 100%
浏览 1113
已采纳

golang`http.Request`的`Host`和`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 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 header,就像:

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

但这并没有解决很多问题,它所带来的麻烦是:

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

要是带有真实HTTP请求示例的答案是最好的。 提前致谢!

  • 写回答

2条回答 默认 最新

  • douxiajia6720 2017-03-21 11:43
    关注

    The r.URL field is created by parsing the HTTP request URI.

    The r.Host field is the value of the Host request header. It's the same value as calling r.Header.Get("Host").

    If the HTTP request on the wire is:

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

    then r.URL.Host is "" and r.Host is www.example.org:8080.

    The value of r.URL.Host and r.Host are almost always different. On a proxy server, r.URL.Host is the host of the target server and r.Host is the host of the proxy server itself. When not connecting through a proxy, the client does not specify a host in the request URI. In this scenario, r.URL.Host is the empty string.

    If you are not implementing a proxy, then you should use r.Host to determine the host.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法