net/http.Request.URL.Host返回空字符串
我试图将我的客户端重定向到https url。我试过这个:net/http.Request.URL.Host返回空字符串,http,url,go,request,Http,Url,Go,Request,我试图将我的客户端重定向到https url。我试过这个: func index(w http.ResponseWriter, r *http.Request) { if r.URL.Scheme != "https" { http.Redirect(w, r, "https://"+r.URL.Host+r.URL.Path, 301) return } //.... } 但它给了我这样的回答:
func index(w http.ResponseWriter, r *http.Request) {
if r.URL.Scheme != "https" {
http.Redirect(w, r, "https://"+r.URL.Host+r.URL.Path, 301)
return
}
//....
}
但它给了我这样的回答:
$ curl -i http://localhost
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: https:///
Date: Sat, 24 Nov 2018 20:02:33 GMT
Content-Length: 44
<a href="https:///">Moved Permanently</a>.
然后我理解了为什么它返回r.URL.Host
的空字符串
我还尝试了r.Header.Get(“主机”)
和r.Header.Get(“源代码”)
。它也给了我一个空字符串
是否有其他方法获取主机名?尝试使用r.host
文件说:
// For server requests Host specifies the host on which the URL
// is sought. Per RFC 7230, section 5.4, this is either the value
// of the "Host" header or the host name given in the URL itself.
那就试试吧
func index(w http.ResponseWriter, r *http.Request) {
if r.URL.Scheme != "https" {
http.Redirect(w, r, "https://"+r.Host+r.URL.Path, 301)
return
}
//....
}
从
转到文档http.request
:
type Request struct {
...
// For incoming requests, the Host header is promoted to the
// Request.Host field and removed from the Header map.
...
Header Header
...
// 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.
...
Host string
因此,对于//大多数请求,使用
r.Host
而不是r.Header.Get(“主机”)
,除Path和RawQuery之外的字段将//为空。(参见RFC 7230,第5.3节)godoc的这一行很好地描述了r.URL.Host
为空的原因。但是,还有其他方法可以获得非空主机名吗?谢谢,它起到了作用,并被接受为回答示例的答案。对于非代理请求,r.URL.Scheme始终是空字符串。您可以将处理程序主体简化为http.Redirect
调用。
type Request struct {
...
// For incoming requests, the Host header is promoted to the
// Request.Host field and removed from the Header map.
...
Header Header
...
// 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.
...
Host string