我一直在使用golang的默认http.ServeMux进行http路由处理。
wrap := func(h func(t *MyStruct, w http.ResponseWriter, r *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
h(t, w, r)
}
}
// Register handlers with default mux
httpMux := http.NewServeMux()
httpMux.HandleFunc("/", wrap(payloadHandler))假设这个服务器可以通过http://example.com/访问
我的客户端的请求很少是路径http://example.com/api//module (注意额外的斜杠),它被重定向为301 Moved Permanently。在golang的http ServeMux.Handler(r *Request)函数中进行探索,似乎是有意的。
path := cleanPath(r.URL.Path)
// if there is any change between actual and cleaned path, the request is 301 ed
if path != r.URL.Path {
_, pattern = mux.handler(host, path)
url := *r.URL
url.Path = path
return RedirectHandler(url.String(), StatusMovedPermanently), pattern
}我也研究过其他类似的问题。
go-web-server-is-automatically-redirecting-post-requests
上面的qn存在注册模式本身的冗余/问题,但我的用例不是寄存器模式(在一些与注册模式无关的嵌套路径中)。
问题是,由于我的客户端请求是POST,浏览器处理带有新GET请求的301号请求,具有精确的查询参数和POST主体。但是,HTTP方法中的更改会导致请求失败。
我已经指示客户端在url中修复冗余的/,但是修复可能只需要很少的(?)在所有客户地点部署数周。
此外,这些冗余的/在Apache Tomcat中处理得很好,但只在golang服务器上失败。那么,这是我的用例(嵌套路径中的冗余/ )中的预期行为,还是可能的bug?
我正在考虑重写ServeMux的ServeMux函数的方法,但是它不会有用,因为Handler调用是在内部进行的。希望禁用这301行为,帮助将不胜感激。
相关链接
发布于 2017-11-24 15:11:52
清洁和重定向是有意的行为。
用移除双斜杠的处理程序包装mux:
type slashFix struct {
mux http.Handler
}
func (h *slashFix) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.Replace(r.URL.Path, "//", "/", -1)
h.mux.ServeHTTP(w, r)
}像这样使用它:
httpMux := http.NewServeMux()
httpMux.HandleFunc("/", wrap(payloadHandler))
http.ListenAndServe(addr, &slashFix{httpMux})发布于 2017-11-24 16:05:27
接入式答案解决了问题
另一种方法是使用大猩猩和设置SkipClean(true)。但是一定要知道它的文档的副作用
SkipClean定义了新路由的路径清理行为。初始值为假。用户应该小心哪些路线没有被清理。如果路由路径为"/ path //to",则它将保留双斜杠。如果您有一个类似于: /fetch/http://xkcd.com/534/的路由,这是很有帮助的 当路径为false时,路径将被清除,因此/fetch/http://xkcd.com/534/将变为/fetch/http/xkcd.com/534
func (r *Router) SkipClean(value bool) *Router {
r.skipClean = value
return r
}https://stackoverflow.com/questions/47475802
复制相似问题