【发布时间】:2016-12-24 21:00:06
【问题描述】:
所以我目前正在为我的 Go web 应用程序分别编写登录和注册功能,并且我正在尝试实现一个功能,如果您不填写必填的表单字段“用户名”“密码”,它将给出你是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 调用,但我无法完全想出替代方案。任何帮助将不胜感激!
【问题讨论】:
-
显示所有的请求处理程序。另一个标题写入来自我们看不到的代码。
-
您不能先调用
http.Error,然后再调用http.Redirect,这可能是您的错误的来源。不过,我不确定你是否有意为这篇文章评论了它。