亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
三國紛爭 2023-05-15 09:41:05
我試圖將我的客戶端重定向到 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://localhostHTTP/1.1 301 Moved PermanentlyContent-Type: text/html; charset=utf-8Location: https:///Date: Sat, 24 Nov 2018 20:02:33 GMTContent-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")。它還給了我一個空字符串。還有其他獲取主機名的方法嗎?
查看完整描述

2 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

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


查看完整回答
反對 回復 2023-05-15
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

嘗試使用 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

    }

//....

}


查看完整回答
反對 回復 2023-05-15
  • 2 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號