【问题标题】:Golang http: multiple response.WriteHeader callsGolang http:多个响应。WriteHeader 调用
【发布时间】: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,这可能是您的错误的来源。不过,我不确定你是否有意为这篇文章评论了它。

标签: forms web go


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢!我最终添加了另一个 gohtml 模板并添加了此代码,以便当用户错误地填写表单时,他们会被重定向到“forbidden.gohtml”页面。给出错误消息并重定向回来。非常感谢!
猜你喜欢
  • 2017-03-28
  • 2021-05-31
  • 2018-12-27
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 2014-05-14
  • 2013-09-20
相关资源
最近更新 更多