我构建了一个 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"
。
我想获取完整的客户端请求 URL,如
"1.2.3.4/"
或 "1.2.3.4/favicon.ico"
。
谢谢。
来自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 /
我使用
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
如果您检测到正在处理相对 URL (
r.URL.IsAbs() == false
),您仍然可以访问 r.Host
(参见 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
}