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.
The URL does not appear in the request line in the origin form, the most common form of HTTP request target. Only specific components of a URL normally appear in the request, i.e. the host (and port if applicable) which appears in the Host header, and the path and query string which appear in the request line.
An HTTP request is made by a client, to a named host, which is located on a server. The aim of the request is to access a resource on the server. To make the request, the client uses components of a URL (Uniform Resource Locator), which includes the information needed to access the resource.
By design, getRequestURL() gives you the full URL, missing only the query string. . getScheme() will give you "https" if it was a https://domain request.
POST request in itself means sending information in the body. I found a fairly simple way to do this. Use Postman by Google, which allows you to specify the content-type (a header field) as application/json and then provide name-value pairs as parameters. Just use your URL in the place of theirs.
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 /
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With