2014-04-18 13 views
8

Zbudowałem serwer HTTP. Korzystam z poniższego kodu, aby uzyskać adres URL żądania, ale nie otrzymuję pełnego adresu URL.Jak uzyskać adres URL w http.Request

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

ja tylko dostać "Req:/" i "Req: /favicon.ico".

Chcę uzyskać pełny adres URL żądania klienta jako "1.2.3.4/" lub "1.2.3.4/favicon.ico".

Dzięki.

Odpowiedz

14

Z dokumentacji pakietu netto/http:

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 
    ... 
} 

Zmodyfikowana wersja swój kod:

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

E Wyjście XAMPLE:

Req: localhost:8888/
3

Jeśli wykryjesz, że masz do czynienia ze względnym adresem URL (r.URL.IsAbs() == false), będziesz mieć dostęp do r.Host (see http.Request), samego siebie, Host.

Łączenie obu da pełny adres URL.

Generalnie widać odwrotnie (wyodrębnianie hosta z adresu URL), podobnie jak w gorilla/reverse/matchers.go

+0

byłem zaskoczony tym, dopóki nie zobaczyłem czek ze względnej zawartości, dobry połów! Mam względny URL i podążam za twoim przewodnikiem, mogę teraz uzyskać hosta, ale potrzebuję również schematu, czy wiesz, jak go zdobyć? – nullgraph

+0

@ nullgraph nie jesteś pewien teraz: możesz zadać to pytanie samodzielnie. – VonC

1

używam req.URL.RequestURI() aby uzyskać pełny adres URL.

Od 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 
Powiązane problemy