英文:
Why does this gorilla session code not work?
问题
我是一个golang新手,所以我正在通过设置一个基于gorilla的种子项目来制作我的第一个玩具应用程序。进展顺利,但是会话代码不像我期望的那样工作,这里是完整的代码,以下是相关的代码片段:
func getMyCounter(w http.ResponseWriter, r *http.Request){
session, _ := sessionStore.Get(r, counterSession)
if session.IsNew {
session.Values[myCounter] = 0
}
val := session.Values[myCounter].(int)
log.Printf("getMyCounter %d", val)
m := make(map[string]int)
m["counter"] = val
js, _ := json.Marshal(m)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func incrementMyCounter(w http.ResponseWriter, r *http.Request){
log.Println("incrementMyCounter")
session, _ := sessionStore.Get(r, counterSession)
if session.IsNew {
session.Values[myCounter] = 0
}
val := session.Values[myCounter].(int)
session.Values[myCounter] = val + 1
getMyCounter(w, r)
}
我的对getMyCounter和incrementMyCounter的调用总是返回0。
英文:
I'm a golang noob, so I'm making my first toy app by setting up a seed project for a gorilla based web app. It's going well but the session code doesn't work as I expect it to, here is the full code, and here is just the relevant snippet:
func getMyCounter(w http.ResponseWriter, r *http.Request){
session, _ := sessionStore.Get(r, counterSession)
if session.IsNew {
session.Values[myCounter] = 0
}
val := session.Values[myCounter].(int)
log.Printf("getMyCounter %d", val)
m := make(map[string]int)
m["counter"] = val
js, _ := json.Marshal(m)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func incrementMyCounter(w http.ResponseWriter, r *http.Request){
log.Println("incrementMyCounter")
session, _ := sessionStore.Get(r, counterSession)
if session.IsNew {
session.Values[myCounter] = 0
}
val := session.Values[myCounter].(int)
session.Values[myCounter] = val + 1
getMyCounter(w, r)
}
my calls to getMyCounter and incrementMyCounter always return 0
答案1
得分: 0
感谢JimB指出了非常明显的问题,我需要在创建/编辑会话后添加对session.Save(r, w)
的调用。
英文:
thanks to JimB for pointing out the painfully obvious, I needed to add a call to session.Save(r, w)
after creating/editing the session.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论