Search code examples
go

How to get URL in http.Request


I built an HTTP server. I am using the code below to get the request URL, but it does not get full URL.

func Handler(w http.ResponseWriter, r *http.Request) {  
    fmt.Printf("Req: %s %s", r.URL.Host, r.URL.Path)
}

I only get "Req: / " and "Req: /favicon.ico".

I want to get full client request URL as "1.2.3.4/" or "1.2.3.4/favicon.ico".

Thanks.


Solution

  • From the documentation of net/http package:

    type Request struct {
       ...
       // The host on which the URL is sought.
       // Per RFC 2616, this is either the value of the Host: header
       // or the host name given in the URL itself.
       // It may be of the form "host:port".
       Host string
       ...
    }
    

    Modified version of your code:

    func Handler(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Req: %s %s\n", r.Host, r.URL.Path) 
    }
    

    Example output:

    Req: localhost:8888 /