如何在 http.Request 中获取 URL

新手上路,请多包涵

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

谢谢。

原文由 Jerry YY Rain 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 811
2 个回答

从 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 /

原文由 mraron 发布,翻译遵循 CC BY-SA 3.0 许可协议

我使用 req.URL.RequestURI() 来获取完整的 url。

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

原文由 Mithril 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题