假设我有一个可以打开新页面的按钮。此按钮的操作由对 Golang API 的 AJAX 调用处理。此 Golang API 由中间件 Verify
包装,它将在定向到该页面之前验证所有内容。传入中间件的函数中定义的页面使用的是 Golang HTML 模板。
router.GET("/newpage", Verify(newpageHandler))
func Verify(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
//verify everything here
//if all verify, call newpageHandler to redirect to new page
h.ServeHTTP(w,r)
}
}
func newpageHandler(w http.ResponseWriter, r *http.Request) {
//this handler will process the html template
}
当我单击按钮(AJAX 调用 /newpage
)时,它不会打开新页面,而只会从 newpageHandler
处理程序返回 HTML 内容。我可以看到从浏览器的开发人员工具返回的 HTML,但它没有获得 newpageHandler
中定义的新页面。
可以使用 http.Redirect
吗?
最佳答案
AJAX 调用将隐含地遵循重定向。 las,没有办法阻止这种情况。因此,使用 http.Redirect
不是一个好的选择。
如果请求被接受,您可以在验证功能中发出信号。这可以使用 http 状态代码轻松完成。如果一切正常,您可以返回一个 2xx 代码。如果出现错误,您可以返回 4xx 代码。
func Verify(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
//verify everything here. verifcationFunc() returns a bool
if verifcationFunc() {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
}
您现在可以在 JavaScript 中评估返回的状态代码。在 200 上,您可以在 JavaScript 中设置新位置。这可以通过 window.location
来完成。对于 401 代码(在上面的示例中),您可以输出一条错误消息。
关于go - 直接转到 Golang 中间件内的新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827245/