【问题标题】:net/http.Request.URL.Host returns empty stringnet/http.Request.URL.Host 返回空字符串
【发布时间】:2019-04-26 23:16:58
【问题描述】:

我试图将我的客户端重定向到 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")。它还给了我一个空字符串。

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

【问题讨论】:

  • 对于 // 大多数请求,Path 和 RawQuery 以外的字段 // 为空。 (参见 RFC 7230,第 5.3 节) godoc 的这一行很好地描述了为什么 r.URL.Host 为空。但是还有其他方法可以获得非空主机名吗?

标签: http url go request


【解决方案1】:

尝试使用 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
    }
//....
}

【讨论】:

  • 感谢它的工作,并接受作为回答示例的答案。
  • 对于非代理请求,r.URL.Scheme 始终为空字符串。您可以将处理程序的主体缩减为 http.Redirect 调用。
【解决方案2】:

来自go doc 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("Host")

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 2020-07-11
    • 2015-05-25
    • 2011-05-09
    • 1970-01-01
    • 2012-07-20
    • 2011-12-15
    • 2020-11-23
    • 2015-12-21
    相关资源
    最近更新 更多