Gorilla web toolikit:len(session.Flashes())为0

时间:2015-08-26 06:23:51

标签: go

我有一个寄存器表单,我正在尝试将它放在一起,通过简单的逻辑,我在服务器端检查了表单验证,例如。

fmt.Println(len(session.Flashes())) which returns 3

在我做的验证结束时(为了调试目的),它可以正常工作

if len(session.Flashes()) != 0 {
    // Perform Redirect and show flashes
} else {
    // Set proper session variables and log user in
}

然后我检查是否有任何形式错误,如此

3 > 0

所以如果else为什么if username == "" || len(username) < 4 { session.AddFlash("Username is too short") session.Save(r, w) } if email == "" || len(email) < 5 { session.AddFlash("Email is too short") session.Save(r, w) } if firstname == "" || len(firstname) < 3 { session.AddFlash("Firstname is too short") session.Save(r, w) } if lastname == "" || len(lastname) < 3 { session.AddFlash("Lastname is too short") session.Save(r, w) } fmt.Println(len(session.Flashes()) > 0) // true if len(session.Flashes()) != 0 { fmt.Println("Why am I here also") type Page struct { Title string Username interface{} Errors []interface{} } session, _ := common.GetSession(r) data := &Page{"Register", session.Values["username"], session.Flashes()} session.Save(r, w) tmpl, err := template.ParseFiles("views/register/register.html") if err != nil { http.Error(w, "Failed to load page.", 500) } tmpl.ExecuteTemplate(w, "register", data) } else { fmt.Println("Why am I here") _, err := db.Query("// Perform DB Query") if err != nil { http.Error(w, "Sorry we had trouble saving your account to the database, try again in a bit.", 500) } session.Values["username"] = r.FormValue("username") session.Values["authenticated"] = true session.Save(r, w) http.Redirect(w, r, "/", 303) } 语句被触发而不是if语句的第一部分?我只是不确定为什么会发生这种情况。如果您需要更多信息,请告诉我们,实际的代码段:

Add Movie

1 个答案:

答案 0 :(得分:1)

记录不是很好,但显然Flashes 会从会话中删除闪烁并返回它们:

func (s *Session) Flashes(vars ...string) []interface{} {
    var flashes []interface{}
    key := flashesKey
    if len(vars) > 0 {
        key = vars[0]
    }
    if v, ok := s.Values[key]; ok {
        // Drop the flashes and return it.
        delete(s.Values, key)
        flashes = v.([]interface{})
    }
    return flashes
}

源代码here

这里的解决方案是使用单独的变量来保存验证状态:

valid := true
if username == "" || len(username) < 4 {
    valid = false
    session.AddFlash("Username is too short")
    session.Save(r, w)
}
// ...
if !valid {
    // ...
} else {
    // ...
}

编辑:另一种在不删除闪存的情况下获取闪存的方法是直接从Values获取闪存:

flashes := session.Values["_flash"].([]interface{})