簡體   English   中英

Golang http:多個響應.WriteHeader調用

[英]Golang http: multiple response.WriteHeader calls

因此,我目前正在為Go Web App編寫登錄名和注冊功能,並且嘗試實現一項功能,如果您不填寫必填字段“ 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調用,但是我還是想不出另一種選擇。 任何幫助將不勝感激!

您不能發送對同一請求的多個響應(首先是驗證錯誤(403,但最好是400),然后是重定向(301,...))。

您可以在延遲后使用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