Golang http:多个响应.WriteHeader调用 [英] Golang http: multiple response.WriteHeader calls

查看:366
本文介绍了Golang http:多个响应.WriteHeader调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我目前正在为Go Web App编写登录名和注册功能,并且尝试实现一项功能,如果您不填写必填字段用户名"和密码",它将提供您一个http.Error,然后我尝试将其设置为http.Redirect,但重定向发生时却出现此错误. 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. 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
}

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

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!

推荐答案

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

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, ...)).

您可以在延迟后使用meta标签或javascript在客户端进行重定向,也可以直接使用http重定向,例如

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/">

这篇关于Golang http:多个响应.WriteHeader调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆