Full URL from http.Request

WBOY
Release: 2024-02-09 13:46:04
forward
963 people have browsed it

来自 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))
   }
}
Copy after login

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

localhost:8080/ => http://localhost:8080/
Copy after login

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
Copy after login

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)))
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!