如何在http.Request中获取URL

问题描述 投票:0回答:3

我构建了一个 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"

谢谢。

go
3个回答
71
投票

来自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 /

19
投票

我使用

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

10
投票

如果您检测到正在处理相对 URL (

r.URL.IsAbs() == false
),您仍然可以访问
r.Host
参见
http.Request
),即
Host
本身。

将两者连接起来即可得到完整的 URL。

通常,您会看到相反的情况(从 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
}
© www.soinside.com 2019 - 2024. All rights reserved.