首页  >  文章  >  后端开发  >  来自 http.Request 的完整 URL

来自 http.Request 的完整 URL

WBOY
WBOY转载
2024-02-09 13:46:04964浏览

来自 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删除