如何在golang gorilla框架中设置会话变量?

时间:2013-07-30 11:45:10

标签: google-app-engine session go session-cookies

我的以下代码

package inqzincrm

import (
    "github.com/gorilla/pat"
    "github.com/gorilla/sessions"
    "net/http"
)

var store = sessions.NewCookieStore([]byte("X12h8v6BZC4QJl53KfNLshtr85gkC5OZ"), []byte("X12h8vasdf6BZC4QJl53KfNLshtr85gk"))

func init() {

    r := pat.New()
    r.Get("/", Home)

    http.Handle("/", r)
}

并在处理程序中,

package inqzincrm

import (
    "appengine"
    "html/template"
    "net/http"
)

var aTmplt = template.Must(template.ParseFiles(
    "inqzincrm/templates/base.html",
    "inqzincrm/templates/index.html",
))

func Home(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)

    session, err := store.Get(r, "x")

    c.Infof("HOST: %s", r.Host)

    if session.IsNew {
        session.Options.Domain = r.Host
        session.Options.Path = "/"
        session.Options.MaxAge = 0
        session.Options.HttpOnly = false
        session.Options.Secure = false
    }

    if err != nil {
        c.Infof("Error getting session: %v", err)
    }
    c.Infof("Requested URL: %v", session.Values["foo"])
    session.Values["foo"] = "asdf"
    if err := aTmplt.ExecuteTemplate(w, "index.html", nil); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    session.Save(r, w)
}

不要在浏览器端设置任何cookie。怎么有结果和错误是零,表明功能没有问题。

我应该如何进一步调试?

我正在使用Ubuntu 64位,Google App Engine,Go with Gorilla工具包。

2 个答案:

答案 0 :(得分:3)

查看我对上一个问题的回答here

简短形式:

import (
    "github.com/gorilla/sessions"
    "net/http"
)

// Authorization Key
var authKey = []byte("somesecret")

// Encryption Key
var encKey = []byte("someothersecret")

var store = sessions.NewCookieStore(authKey, encKey)

func initSession(r *http.Request) *sessions.Session {
    session, _ := store.Get(r, "my_cookie") // Don't ignore the error in real code
    if session.IsNew { //Set some cookie options
        session.Options.Domain = "example.org"
        session.Options.MaxAge = 0
        session.Options.HttpOnly = false
        session.Options.Secure = true
    }
    return session
}

然后,在你的处理程序中:

func ViewPageHandler(w http.ResponseWriter, r *http.Request) {
    session := initSession(r)
    session.Values["page"] = "view"
    session.Save(r, w)
....

你的代码似乎做同样的事情,所以没有更多的例子,我看不出任何问题。我可以说我发布的示例是(非常略微修改)来自工作服务器。

答案 1 :(得分:3)

代码session.save()应该出现在模板执行代码之前。它已被提到没有。但那是整个错误。