如何在http.Request中获取URL

Jer*_*ain 19 go

我构建了一个HTTP服务器.我使用下面的代码来获取请求URL,但它没有获得完整的URL.

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

我只有"Req: / ""Req: /favicon.ico".

我希望将完整的客户端请求URL作为"1.2.3.4/""1.2.3.4/favicon.ico".

谢谢.

mra*_*ron 30

从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
   ...
}
Run Code Online (Sandbox Code Playgroud)

修改后的代码版本:

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

示例输出:

Req: localhost:8888 /
Run Code Online (Sandbox Code Playgroud)


Mit*_*ril 9

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
Run Code Online (Sandbox Code Playgroud)


Von*_*onC 7

如果您检测到您正在处理一个相对 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
}
Run Code Online (Sandbox Code Playgroud)