从http.Request中获取完整的URL。

huangapple go评论80阅读模式
英文:

Full URL from http.Request

问题

我需要在响应请求时返回服务器的完整URL地址,最好的方法是什么?

func mainPage(w http.ResponseWriter, r *http.Request) {
   if r.Method == http.MethodPost {
       protocol := "http://"
       if r.TLS != nil {
           protocol = "https://"
       }
       w.Write([]byte(protocol + r.Host + r.RequestURI))
   }
}

我不明白如何在这里添加协议(http://或https://)。

localhost:8080/ => http://localhost:8080/
英文:

I need to return the full URL address of the server in the response to the request, what is the best way to do this?

func mainPage(w http.ResponseWriter, r *http.Request) {
   if r.Method == http.MethodPost {
	
	   w.Write([]byte(r.Host + r.RequestURI))
   }
}

I don't understand how to add the protocol here (http:// or https://).

localhost:8080/ => http://localhost:8080/

答案1

得分: 3

当您启动一个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)))
}
英文:

when You are starting a HTTP/s server You use either ListenAndServe or ListenAndServeTLS or both together on different ports.

If You are using just one of them, then from Listen.. it's obvious which scheme request is using and You don't need a way to check and set it.

but if You are serving on both HTTP and HTTP/s then You can use request.TLS state. if its nil it means it's 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

an example:

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)))
}

huangapple
  • 本文由 发表于 2023年5月1日 05:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76143726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定