http.Server — 获取URL片段

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

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.

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:

确定