我一直在尝试解决 weird problem现在已经有一段时间了。在单步执行大量角度代码后,我注意到在通过 Charles 将请求记录到我的服务器时有些奇怪。
当我发布到 url /myurl
时,请求实际上从未到达我的服务器。相反,它得到一个 301 响应,然后一个 GET 请求访问我的服务器。
这真是令人费解。还有其他人遇到过这个问题吗?如果您有兴趣,我已经上传了我的 Charles 日志的屏幕截图。
作为引用,这是我的服务器的样子:
type FormStruct struct {
Test string
}
func PHandler(w http.ResponseWriter, r *http.Request) {
var t FormStruct
req, _ := httputil.DumpRequest(r, true)
log.Println(string(req))
log.Println(r.Method) // GET
log.Println(r.Body)
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&t)
log.Println("Decoding complete")
if err != nil {
log.Println("Error")
panic(err.Error()+"\n\n")
}
log.Println(t.Test)
w.Write([]byte("Upload complete, no errors"))
}
func main() {
http.HandleFunc("/myurl/", PHandler)
fmt.Println("Go Server listening on port 8001")
http.ListenAndServe(":8001", nil)
}
最佳答案
解释很简单:因为您在注册PHandler
时使用了"/myurl/"
路径(注意结尾的斜杠/
!) 但您将浏览器定向到 /myurl
(注意没有尾部斜杠)。默认情况下,http
包实现将执行(发回)重定向请求,因此如果浏览器遵循它(它会),新 URL 将匹配注册路径。
这记录在类型 http.ServeMux
中:
If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.
如果您将浏览器直接指向 /myurl/
,您将不会遇到重定向。
或者,如果您不需要处理有根子树而只需要处理一个路径(例如 /myurl
),则只将您的处理程序注册到这个路径:
http.HandleFunc("/myurl", PHandler)
然后当然将您的浏览器定向到 /myurl
,您也不会遇到任何重定向。
...或者如文档所建议的那样:如果您确实需要,请将这两个路径都注册到您的处理程序:
http.HandleFunc("/myurl", PHandler)
http.HandleFunc("/myurl/", PHandler)
现在无论您调用哪个路径(/myurl
或 /myurl/
),两者都会导致调用您的处理程序而不会发生任何重定向。
注意事项:
在您将重定向发送回浏览器的情况下,浏览器不会重复 POST 请求(而只是一个“简单的”GET 请求)。
一般来说,浏览器不会将 POST 数据发送到重定向 URL,因为浏览器没有资格决定您是否愿意将您打算发送到原始 URL 的相同数据发送到新 URL(想想密码、信用卡号和其他敏感数据)。但不要试图绕过它,只需使用您的处理程序的注册路径进行 POST 操作,或使用上述任何其他技巧。
您可以在此处阅读有关该主题的更多信息:
关于http - Go Web 服务器自动重定向 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36316429/