douche3791 2018-11-24 20:18
浏览 194
已采纳

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

I was trying to redirect my client to https url. And I tried this:

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

But it gave me this response:

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

The mysterious thing is Location: https:/// this line. And I read the go doc again and found:

// 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

Then I've understood that why it's returning and empty string for r.URL.Host.

I have also tried r.Header.Get("Host") and then r.Header.Get("Origin"). It also gave me an empty string.

Any other way to get the host name?

  • 写回答

2条回答 默认 最新

  • dsmgcse8876 2018-11-24 20:36
    关注

    Try using r.Host?

    The docs say:

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

    So Maybe try that?

    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
        }
    //....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题