【发布时间】: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
但它解决的问题并不多于它产生的问题:
- 为什么请求中有两个不同的
Host字段?我的意思是这不是重复的吗? - 同一个请求中的两个
Host字段可以不同吗? - 我应该在什么情况下使用哪个?
最好使用真实的 HTTP 请求示例来回答。提前致谢。
【问题讨论】: