http.Server — 获取URL片段

huangapple go评论123阅读模式
英文:

http.Server — get URL fragment

问题

无法使用标准的http.Server提取片段数据(foo在http://domain.com/path#foo中)。

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. type Handler struct {
  7. }
  8. func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  9. fmt.Printf("Path = \"%v\" Fragment = \"%v\"\n", r.URL.Path, r.URL.Fragment)
  10. }
  11. func main() {
  12. var handler Handler
  13. http.ListenAndServe(":30000", handler)
  14. }

对于http://127.0.0.1:30000/path#foo,会产生空的片段:

Path = "/path" Fragment = ""

如何使用Go语言的内置http.Server获取片段数据?

英文:

Have no luck with extracting fragment data (foo in http://domain.com/path#foo) with standard http.Server.

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. type Handler struct {
  7. }
  8. func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  9. fmt.Printf("Path = \"%v\" Fragment = \"%v\"\n", r.URL.Path, r.URL.Fragment)
  10. }
  11. func main() {
  12. var handler Handler
  13. http.ListenAndServe(":30000", handler)
  14. }

produces empty fragment for http://127.0.0.1:30000/path#foo:

Path = "/path" Fragment = ""

How can I get fragment data using golang's builtin http.Server?

答案1

得分: 16

你不能这样做。这不是Go的问题——URL片段不会通过HTTP发送到服务器。它们只是浏览器的概念。

这里有一个相关的问题,http.Request的文档已经更改为:

  1. // 对于服务器请求,URL是从Request-Line中提供的URI解析而来的,该URI存储在RequestURI中。
  2. // 对于大多数请求,除了Path和RawQuery之外的字段都将为空。(参见RFC 2616,第5.1.2节)

如果出于某种原因你需要它,你可以使用一些JavaScript将片段作为GET参数包含在请求中。

英文:

You can't. This isn't a Go thing -- URL fragments are not sent to the server over HTTP. They're just a browser concept.

Here is a relevant issue, where the docs for http.Request were changed to say:

  1. // For server requests the URL is parsed from the URI
  2. // supplied on the Request-Line as stored in RequestURI. For
  3. // most requests, fields other than Path and RawQuery will be
  4. // empty. (See RFC 2616, Section 5.1.2)

If for some reason you need it, you could probably string together some JavaScript to include the fragment in the request as a GET parameter or something.

huangapple
  • 本文由 发表于 2014年8月25日 23:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/25489843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定