dpwjx32578146
2016-12-24 21:00
浏览 319
已采纳

Golang http:多个响应.WriteHeader调用

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!

图片转代码服务由CSDN问答提供 功能建议

因此,我目前正在为Go Web App编写登录名和注册功能,并尝试实现 的功能,如果您不填写必填字段“用户名”和“密码”,则会给您一个 http.Error ,然后尝试将其设置为 http.Redirect < / code>但重定向时发生此错误。 http:多次响应。WriteHeader调用这是我的代码。

  //检查表单提交
var u用户
if req.Method ==  http.MethodPost {
 un:= req.FormValue(“用户名”)
p:= req.FormValue(“密码”)
 
 
 //检查用户是否填写了必填字段。
 if  un ==“” {
 http.Error(w,“请填写必填字段,您将很快被重定向。”,http.StatusForbidden)
 time.Sleep(3000 * time.Millisecond)
 // http  .redirect(w,req,“ /” http.StatusSeeOther)
 return 
 
}否则,如果p ==“” {
 http.Error(w,“请填写必填字段,您将很快被重定向 ”,http.StatusForbidden)
 time.Sleep(3000 * time.Millisecond)
 //http.Redirect(w,req,“ /”,http.StatusSeeOther)
 return 
} 
 
 c  .Value = un 
u =用户{un,p} 
 
 dbUsers [c.Value] = u 
 http.Redirect(w,req,“ / login”,http.StatusSeeOther)
 
日志。  Println(dbUsers)
返回
} 
   \  n 
 

我确实知道这是因为if / else语句中有多个http调用,但我还是想不出另一种选择。 任何帮助将不胜感激!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulianglou0898 2016-12-24 21:34
    已采纳

    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/">
    
    打赏 评论

相关推荐 更多相似问题