猿问

net/http.Request.URL.Host 返回空字符串

我试图将我的客户端重定向到 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

        }

//....

}

但它给了我这样的回应:


$ 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>.

神秘的是Location: https:///这一行。我又看了一遍 go doc,发现:


// URL specifies either the URI being requested (for server

// requests) or the URL to access (for client requests).

//

// For server requests the URL is parsed from the URI

// supplied on the Request-Line as stored in RequestURI.  **For

// most requests, fields other than Path and RawQuery will be

// empty. (See RFC 7230, Section 5.3)**

//

// For client requests, the URL's Host specifies the server to

// connect to, while the Request's Host field optionally

// specifies the Host header value to send in the HTTP

// request.

URL *url.URL

然后我明白了为什么它返回和空字符串r.URL.Host。


我也试过r.Header.Get("Host")然后r.Header.Get("Origin")。它还给了我一个空字符串。


还有其他获取主机名的方法吗?


三国纷争
浏览 121回答 2
2回答

慕的地8271018

来自go doc http.request:type Request struct {&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; // For incoming requests, the Host header is promoted to the&nbsp; &nbsp; &nbsp; &nbsp; // Request.Host field and removed from the Header map.&nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; Header Header&nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; // For server requests Host specifies the host on which the&nbsp; &nbsp; &nbsp; &nbsp; // URL is sought. Per RFC 2616, this is either the value of&nbsp; &nbsp; &nbsp; &nbsp; // the "Host" header or the host name given in the URL itself.&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; Host string因此,r.Host不使用r.Header.Get("Host")

繁星淼淼

尝试使用 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) {&nbsp; &nbsp; if r.URL.Scheme != "https" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Redirect(w, r, "https://"+r.Host+r.URL.Path, 301)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }//....}
随时随地看视频慕课网APP

相关分类

Go
我要回答