猿问

Gorilla web 工具包:len(session.Flashes()) 为 0

我有一个注册表格,我想用简单的逻辑放在一起,我在服务器端用简单的 ifs 检查了表单验证,例如


if username == "" || < 5 {

    session.AddFlash("Username is too short")

    session.Save(r, w)

}

这工作正常然后在我做的验证结束时(用于调试目的)


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 语句的第一部分呢?我只是不确定为什么会这样。谢谢,如果您需要更多信息,请告诉我,实际代码片段:


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)

}



叮当猫咪
浏览 152回答 1
1回答

holdtom

它没有很好的记录,但显然从会话中Flashes 删除了闪烁并返回它们:func (s *Session) Flashes(vars ...string) []interface{} {&nbsp; &nbsp; var flashes []interface{}&nbsp; &nbsp; key := flashesKey&nbsp; &nbsp; if len(vars) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; key = vars[0]&nbsp; &nbsp; }&nbsp; &nbsp; if v, ok := s.Values[key]; ok {&nbsp; &nbsp; &nbsp; &nbsp; // Drop the flashes and return it.&nbsp; &nbsp; &nbsp; &nbsp; delete(s.Values, key)&nbsp; &nbsp; &nbsp; &nbsp; flashes = v.([]interface{})&nbsp; &nbsp; }&nbsp; &nbsp; return flashes}源代码在这里。这里的解决方案是使用单独的变量来保存验证状态:valid := trueif username == "" || len(username) < 4 {&nbsp; &nbsp; valid = false&nbsp; &nbsp; session.AddFlash("Username is too short")&nbsp; &nbsp; session.Save(r, w)}// ...if !valid {&nbsp; &nbsp; // ...} else {&nbsp; &nbsp; // ...}编辑:另一种获取闪光灯而不删除它们的方法是Values直接从以下位置获取它们:flashes := session.Values["_flash"].([]interface{})
随时随地看视频慕课网APP

相关分类

Go
我要回答