登录
首页 >  Golang >  Go问答

net/http.Request.URL.Host 返回值为空

来源:stackoverflow

时间:2024-03-11 21:18:25 377浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《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

Moved Permanently.

神秘的是location:https:///这一行。我再次阅读了 go 文档,发现:

// url 指定正在请求的 uri(对于服务器 // 请求)或要访问的 url(对于客户端请求)。 // // 对于服务器请求,url 是从 uri 中解析出来的 // 在请求行上提供并存储在 requesturi 中。 **为了 // 大多数请求,除了 path 和 rawquery 之外的字段 // 空的。 (参见 rfc 7230,第 5.3 节)** // // 对于客户端请求,url 的 host 指定服务器 // 连接到,而请求的主机字段可选 // 指定要在 http 中发送的 host 标头值 // 要求。 网址 *url.url

然后我就明白了为什么它返回 r.url.host 的空字符串。

我还尝试了 r.header.get("host")r.header.get("origin")。它还给了我一个空字符串。

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


解决方案


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

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

今天关于《net/http.Request.URL.Host 返回值为空》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>