英文:
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服务器时,您可以使用ListenAndServe
、ListenAndServeTLS
或两者一起在不同的端口上使用。
如果您只使用其中一个,那么从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)))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论