简体   繁体   English

Golang http:多个响应.WriteHeader调用

[英]Golang http: multiple response.WriteHeader calls

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. 因此,我目前正在为Go Web App编写登录名和注册功能,并且尝试实现一项功能,如果您不填写必填字段“ username”和“ password”,则会为您提供一个http.Error ,然后尝试将其设置为http.Redirect但重定向发生时却出现此错误。 http: multiple response.WriteHeader calls Here is my code.. 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
}

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. 我确实知道这是因为if / else语句中有多个http调用,但是我还是想不出另一种选择。 Any help would be greatly appreciated! 任何帮助将不胜感激!

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, ...)). 您不能发送对同一请求的多个响应(首先是验证错误(403,但最好是400),然后是重定向(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标签或javascript在客户端进行重定向,也可以直接使用http重定向,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM