Home  >  Article  >  Backend Development  >  Full URL from http.Request

Full URL from http.Request

WBOY
WBOYforward
2024-02-09 13:46:04964browse

来自 http.Request 的完整 URL

Question content

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

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 protocol here (http:// or https://).

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

Solution

When you start the http/s server, you can use listenandserve or listenandservetls or both at the same time on different ports By.

If you only use one of these, it will be obvious from listen.. which scheme request is being used, and you don't need a way to check and set it.

But if you serve on both http and http/s, then you can use the request.tls status. If it's 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

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

The above is the detailed content of Full URL from http.Request. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete