【发布时间】:2018-05-08 14:49:58
【问题描述】:
我一直在使用 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,浏览器会使用带有精确查询参数和POST 正文的新GET 请求来处理301。但是更改 HTTP 方法会导致请求失败。
我已经指示客户修复 url 中多余的 /,但修复可能需要几个 (?) 周才能部署到所有客户端位置。
这些多余的/ 在Apache Tomcat 中也可以很好地处理,但仅在 golang 服务器中失败。那么这是我的用例中的预期行为(嵌套路径中的冗余 /)与 golang 或可能的错误?
我正在考虑覆盖ServeMux 的Handler 函数的方法,但它不会有用,因为Handler 调用是在内部进行的。希望禁用此 301 行为,我们将不胜感激。
相关链接
【问题讨论】:
标签: http redirect go http-status-code-301