首頁 > 後端開發 > Golang > 主體

來自 http.Request 的完整 URL

WBOY
發布: 2024-02-09 13:46:04
轉載
962 人瀏覽過

来自 http.Request 的完整 URL

問題內容

我需要在請求回應中傳回伺服器的完整 url 位址,最好的方法是什麼?

func mainpage(w http.responsewriter, r *http.request) {
   if r.method == http.methodpost {
    
       w.write([]byte(r.host + r.requesturi))
   }
}
登入後複製

我不明白如何在此處新增協定(http:// 或 https://)。

localhost:8080/ => http://localhost:8080/
登入後複製

解決方法

當您啟動http/s 伺服器時,您可以在不同連接埠上使用listenandservelistenandservetls 或同時使用兩者。

如果您只使用其中一個,那麼從 listen.. 可以明顯看出正在使用哪個方案請求,並且您不需要一種方法來檢查和設定它。

但是如果您同時在 http 和 http/s 上提供服務,那麼您可以使用 request.tls 狀態。如果是 nil 則表示它是 http。

// tls allows http servers and other software to record
    // information about the tls connection on which the request
    // was received. this field is not filled in by readrequest.
    // the http server in this package sets the field for
    // tls-enabled connections before invoking a handler;
    // otherwise it leaves the field nil.
    // this field is ignored by the http client.
    tls *tls.connectionstate
登入後複製

範例:

func index(w http.ResponseWriter, r *http.Request) {
    scheme := "http"
    if r.TLS != nil {
        scheme = "https"
    }
    w.Write([]byte(fmt.Sprintf("%v://%v%v", scheme, r.Host, r.RequestURI)))
}
登入後複製

以上是來自 http.Request 的完整 URL的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!