我构建了一个HTTP服务器。我使用下面的代码来获取请求URL,但它没有获得完整的URL。
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Req: %s %s", r.URL.Host, r.URL.Path)
}
我只获得"Req: / "
和"Req: /favicon.ico"
。
我希望将完整的客户请求网址设为"1.2.3.4/"
或"1.2.3.4/favicon.ico"
。
感谢。
答案 0 :(得分:27)
来自net / 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
...
}
修改后的代码版本:
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Req: %s %s\n", r.Host, r.URL.Path)
}
示例输出:
Req: localhost:8888 /
答案 1 :(得分:8)
我使用req.URL.RequestURI()
获取完整的网址。
来自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
答案 2 :(得分:3)
如果您检测到您正在处理相对网址(r.URL.IsAbs() == false
),则您可以访问r.Host
(see http.Request
),Host
本身。
连接这两个将为您提供完整的URL。
通常,您会看到相反的情况(从网址中提取主机),如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
}