英文:
http.Server — get URL fragment
问题
无法使用标准的http.Server
提取片段数据(foo
在http://domain.com/path#foo中)。
package main
import (
"fmt"
"net/http"
)
type Handler struct {
}
func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Path = \"%v\" Fragment = \"%v\"\n", r.URL.Path, r.URL.Fragment)
}
func main() {
var handler Handler
http.ListenAndServe(":30000", handler)
}
对于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
.
package main
import (
"fmt"
"net/http"
)
type Handler struct {
}
func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Path = \"%v\" Fragment = \"%v\"\n", r.URL.Path, r.URL.Fragment)
}
func main() {
var handler Handler
http.ListenAndServe(":30000", handler)
}
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
的文档已经更改为:
// 对于服务器请求,URL是从Request-Line中提供的URI解析而来的,该URI存储在RequestURI中。
// 对于大多数请求,除了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:
// For server requests the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI. For
// most requests, fields other than Path and RawQuery will be
// 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论