Reputation: 4382
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.
Upvotes: 52
Views: 123455
Reputation: 2551
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 /
Upvotes: 71
Reputation: 13718
I use req.URL.RequestURI()
to get the full url.
From net/http/requests.go
:
// RequestURI is the unmodified Request-URI of the
// Request-Line (RFC 2616, Section 5.1) as sent by the client
// to a server. Usually the URL field should be used instead.
// It is an error to set this field in an HTTP client request.
RequestURI string
Upvotes: 21
Reputation: 1323343
If you detect that you are dealing with a relative URL (r.URL.IsAbs() == false
), you sill have access to r.Host
(see http.Request
), the Host
itself.
Concatenating the two would give you the full URL.
Generally, you see the reverse (extracting Host from an URL), as in gorilla/reverse/matchers.go
// getHost tries its best to return the request host.
func getHost(r *http.Request) string {
if r.URL.IsAbs() {
host := r.Host
// Slice off any port information.
if i := strings.Index(host, ":"); i != -1 {
host = host[:i]
}
return host
}
return r.URL.Host
}
Upvotes: 10