我有一个正在尝试放在一起的注册表单,用简单的逻辑在服务器端用简单的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语句的第一部分呢?我只是不确定为什么会这样发生。谢谢,如果您需要更多信息,请告诉我,实际的代码片段:
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) }
它的文档记录不是很好,但是显然从会话中Flashes 删除了 闪烁并返回了它们:
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 }
源代码在这里。
这里的解决方案是使用一个单独的变量来保存验证状态:
valid := true if username == "" || len(username) < 4 { valid = false session.AddFlash("Username is too short") session.Save(r, w) } // ... if !valid { // ... } else { // ... }
编辑: 获取闪光灯而不删除它们的另一种方法是Values直接从其中获取它们:
Values
flashes := session.Values["_flash"].([]interface{})