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

标签 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
        }
//....
}

但它给了我这样的回应:

$ 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 文档,发现:

// 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")。它还给了我一个空字符串。

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

最佳答案

来自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")

关于http - net/http.Request.URL.Host 返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462002/

相关文章:

javascript - 有一个接收帖子的 go web 服务,但不清楚如何将响应发送回 jquery

pointers - 调用结构属性方法时 Golang 结构指针引用丢失

javascript - 使用 reactJs 和 NodeJs 发出 http post 请求

http - 重用连接时必须重新发送哪些 HTTP header 字段?

python - 我应该使用哪种 HTTP 方法来更新 session 属性?

java - 线程中的异常 "main"java.lang.IllegalStateException : Already connected

go - 上传到互联网站点

http - 如何在 Rust 中使用 hyper、tokio 和 futures 为 HTTP 请求设置超时?

asp.net-mvc - ASP.NET MVC 中 htmlAttributes 的匿名类和 IDictionary<string,object> 之间的速度差异

node.js - 如何重新翻译其他网站的图像(隐藏源 URL)