英文:
Golang http: multiple response.WriteHeader calls
问题
所以我目前正在为我的Go Web应用编写登录和注册功能,我试图实现一个功能,即如果您没有填写必填的表单字段“用户名”和“密码”,它将给出一个http.Error
,然后我试图使用http.Redirect
进行重定向,但是当重定向发生时,我遇到了这个错误:http: multiple response.WriteHeader calls
这是我的代码:
//检查表单提交
var u user
if req.Method == http.MethodPost {
un := req.FormValue("username")
p := req.FormValue("password")
//检查用户是否填写了必填字段。
if un == "" {
http.Error(w, "请填写必填字段,您将很快被重定向。", http.StatusForbidden)
time.Sleep(3000 * time.Millisecond)
//http.Redirect(w, req, "/", http.StatusSeeOther)
return
} else if p == "" {
http.Error(w, "请填写必填字段,您将很快被重定向。", 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调用,但我无法想出替代方案。任何帮助将不胜感激!
英文:
So I am currently writing a login and respectively a signup features for my Go web App and I am attempting to implement a feature that if you don't fill out both the required form fields "username" "password" it will give you an http.Error
and then I am attempting to make it http.Redirect
yet i get this error when redirecting occurs. http: multiple response.WriteHeader calls
Here is my code..
//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
}
I do know that it is because of the multiple http calls within the if/else statement yet I can't quite come up with an alternative. Any help would be greatly appreciated!
答案1
得分: 2
你不能在同一个请求中发送多个响应(首先是验证错误(403,但400可能更好),然后是重定向(301,...))。
你可以使用元标签或JavaScript在客户端上进行延迟后重定向,或直接使用HTTP重定向,例如:
<meta http-equiv="refresh" content="3; URL=https://your.site/">
英文:
You can not send multiple responses to the same request (first the validation error (403 but 400 would be better) and then the redirection (301, ...)).
You could use a meta tag or javascript to redirect on the client side after an delay or directly use the http redirect, like
<meta http-equiv="refresh" content="3; URL=https://your.site/">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论