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

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

How to set session variable in golang gorilla framework?

问题

我的以下代码

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。然而,结果和err都是nil,表示函数没有问题。

我应该如何进一步调试?

我使用的是64位Ubuntu,Google App Engine,带有Gorilla工具包的Go语言。

英文:

My following code

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)
}

and in handler,

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)
}

do not set any cookie on browser side. how ever result and err are nil indicating no problem with the functions.

How I should debug further ?

I am using Ubuntu 64 bit, Google App Engine, Go with Gorilla tool kit.

答案1

得分: 4

请查看我对之前问题的回答这里

简短形式:

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

// 授权密钥
var authKey = []byte("somesecret")

// 加密密钥
var encKey = []byte("someothersecret")

var store = sessions.NewCookieStore(authKey, encKey)

func initSession(r *http.Request) *sessions.Session {
    session, _ := store.Get(r, "my_cookie") // 在真实代码中不要忽略错误
    if session.IsNew { // 设置一些cookie选项
        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)
....

你的代码似乎做了相同的事情,所以没有更多的示例,我看不出任何问题。我可以说我发布的示例(稍微修改过)来自一个工作的服务器。

英文:

Have a look at my answer to a previous question here.

In short form:

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
}

Then, in your handlers:

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

Your code seems to do the same thing, so without more of an example I can't see any problem with it. I can say that the example I've posted is (very slightly modified) from a working server.

答案2

得分: 3

代码session.save()应该在模板执行代码之前。这一点没有提到过。但这就是整个错误。

英文:

the code session.save() should come before template execution code. it has been mentioned no where. but that was the whole mistake.

huangapple
  • 本文由 发表于 2013年7月30日 19:45:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/17946157.html
匿名

发表评论

匿名网友

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

确定