Golang http:多个response.WriteHeader调用

时间:2016-12-24 21:00:06

标签: forms web go

所以我正在为我的Go网络应用程序编写登录和分别注册功能,我正在尝试实现一项功能,如果您没有填写所需的表单字段“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调用,但是我无法想出替代方案。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您无法向同一请求发送多个响应(首先是验证错误(403但400会更好)然后重定向(301,...))。

您可以在延迟后使用元标记或javascript在客户端重定向或直接使用http重定向,例如

<meta http-equiv="refresh" content="3; URL=https://your.site/">