在开发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)
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
在我看来,请求中有两个主机值:uri行和Host标题,如:
GET http://localhost:8080/ HTTP/1.1
Host: localhost:8080
Run Code Online (Sandbox Code Playgroud)
但它并没有解决许多问题而不是它造成的问题:
Host请求中有两个不同的字段?我的意思是这不是重复的吗?Host字段在同一个请求中可以不同吗?具有真实HTTP请求示例的答案将是最好的.提前致谢.
Cer*_*món 23
该r.URL字段是通过解析HTTP请求URI创建的.
该r.Host字段是Host请求标头的值.它与呼叫的价值相同r.Header.Get("Host").
如果线路上的HTTP请求是:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.example.org:8080
Run Code Online (Sandbox Code Playgroud)
然后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来确定主机.