Go 的默认 HTTP 服务器实现合并 HTTP 请求中的斜杠,返回一个 HTTP 重定向响应到“清理”路径:
https://code.google.com/p/go/source/browse/src/pkg/net/http/server.go#1420
因此,如果您发出 HTTP 请求 GET/http://foo.com/
,服务器将响应 301 Moved Permanently ... Location:/http:/foo.com/
。
我想禁用此行为并自己处理所有路径。
我是 Go 新手,似乎我可以创建自己的 Server
实例并覆盖 Handler
属性,但我不确定如何?
最佳答案
I'd like to disable this behaviour and handle all paths myself.
I'm a Go newbie, and it seems as if I could create my own Server instance and override the Handler attribute, but I'm not sure how to?
不是通过 http.Handle
或 http.HandleFunc
方法向 http.DefaultServeMux
注册处理程序,只需调用:
http.ListenAndServe(":8080", MyHandler)
其中 MyHandler
是实现 http.Handler
的类型的实例界面。
http.ListenAndServe
in turn 只是一种简写方法,它执行以下操作:
func ListenAndServe(addr string, handler http.Handler) error {
server := &http.Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
因此您也可以直接这样做。
在您的处理程序中,您可以按照自己的意愿解析/路由 URI,如下所示:
func (h *MyHandlerType) ServeHTTP(w http.ResponseWriter, r *http.Request) {
uri := r.URL.Path
// ...use uri...
}
关于http - 覆盖 Go 的默认 HTTP 服务器重定向行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888285/