为什么这段大猩猩会话代码不起作用?

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年3月11日 04:07:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/28973138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定