[英]Golang http: multiple response.WriteHeader calls
因此,我目前正在为Go Web App编写登录名和注册功能,并且尝试实现一项功能,如果您不填写必填字段“ username”和“ password”,则会为您提供一个http.Error
,然后尝试将其设置为http.Redirect
但重定向发生时却出现此错误。 http: multiple response.WriteHeader calls
这是我的代码。
//Check form submission
var u user
if req.Method == http.MethodPost {
un := req.FormValue("username")
p := req.FormValue("password")
//Checking to see if user filled out required fields.
if un == ""{
http.Error(w, "Please fill out required fields, you will be redirected shortly.", http.StatusForbidden)
time.Sleep(3000 * time.Millisecond)
//http.Redirect(w, req, "/" http.StatusSeeOther)
return
}else if p == "" {
http.Error(w, "Please fill out required fields, you will be redirected shortly.", http.StatusForbidden)
time.Sleep(3000 * time.Millisecond)
//http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
c.Value = un
u = user{un, p}
dbUsers[c.Value] = u
http.Redirect(w, req, "/login", http.StatusSeeOther)
log.Println(dbUsers)
return
}
我确实知道这是因为if / else语句中有多个http调用,但是我还是想不出另一种选择。 任何帮助将不胜感激!
您不能发送对同一请求的多个响应(首先是验证错误(403,但最好是400),然后是重定向(301,...))。
您可以在延迟后使用meta标签或javascript在客户端进行重定向,也可以直接使用http重定向,例如
<meta http-equiv="refresh" content="3; URL=https://your.site/">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.