What is the difference between `Host` and `URL.Host` for golang `http.Request`?

前端 未结 2 2031
走了就别回头了
走了就别回头了 2021-02-04 04:19

When developing golang http application, I use http.Request a lot. When accessing request host address, I would use req.Host, but I find that there is

相关标签:
2条回答
  • 2021-02-04 04:29

    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.

    0 讨论(0)
  • 2021-02-04 04:41

    Essentially http.Request.Host is for convenience.

    r.Host is much easier to call than r.Header.Get("Host") or r.URL.Host.

    Also to be noted that some routers strip the host from http.Request.URL so http.Request.Host is useful in those cases as well.

    Hence it can be considered that req.Host provides the Host value even when the request header or url has been modified elsewhere.

    0 讨论(0)
提交回复
热议问题