Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get URL in http.Request

Tags:

go

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.

like image 957
Jerry YY Rain Avatar asked Apr 18 '14 10:04

Jerry YY Rain


People also ask

Where is the URL in a HTTP request?

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.

Does HTTP request contain URL?

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.

How can you retrieve the full URL for the incoming request?

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.

How do I send a post request URL?

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.


2 Answers

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 / 
like image 145
mraron Avatar answered Sep 29 '22 17:09

mraron


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 
like image 42
Mithril Avatar answered Sep 29 '22 17:09

Mithril