golang martini session.Set没有设置任何值

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

golang martini session.Set not setting any value

问题

这里没有太多的上下文,因为这实际上是一个应该工作但却没有工作的情况。

我正在使用martini框架。在一个处理程序中,我使用了以下代码:

session.Set("deployed", "true")
r.Redirect("/myOtherURL", http.StatusSeeOther)

其中,'session'是传递给处理程序的sessions.Session对象。
在加载myOtherURL的处理程序中,我使用了session.Get,但没有返回任何内容。我打印出了所有的session内容,但'deployed'并不存在。

可能是什么原因导致了这个问题?我可能漏掉了什么?如果我能提供更多的上下文,我会的,但实际上情况就是这么简单。

英文:

There isn't much context with this because it really is a situation where something should work, but it just doesn't.

I am using the martini framework. In one handler I'm using this:

session.Set("deployed", "true")
r.Redirect("/myOtherURL", http.StatusSeeOther)

Whereby 'session' is the sessions.Session object passed through to the handler.
In the handler that loads myOtherURL, I'm using session.Get but nothing is being returned. I printed out all of the session content and the 'deployed' is not present.

What could be causing this problem? What could I possibly be missing out? I would give more context if I could but it really is as simple as this.

答案1

得分: 1

只需在我的评论中进行扩展/帮助其他人在将来:

  • 当您设置一个没有明确Path值的cookie时,该cookie将采用当前路径。
  • Cookie仅发送到该路径及其以下路径,而不是上面的路径,例如:
  1. 当您通过session.Set(val, key)隐式设置它时,为/modules设置cookie。
  2. Cookie 发送到/modules/modules/all/modules/detail/12
  3. Cookie 不会发送到/about/

可以通过显式设置路径来解决此问题:

var store = sessions.NewCookieStore([]byte("secret123"))

func main() {
    store.Options.Path = "/"
    ...
}

请注意,您可能不希望为所有路由发送cookie(这就是/所做的),因此请谨慎使用。

英文:

Just to extend on my comment/help others in the future:

  • When you set a cookie without an explicit Path value, the cookie takes on the current path.
  • Cookies are only sent for that path and paths below - not above - e.g.
  1. Cookie set for /modules when you implicitly set it for the first time via session.Set(val, key)
  2. Cookie is sent for /modules, /modules/all and /modules/detail/12
  3. Cookie is NOT sent for /about or /

This can be fixed by explicitly setting the path:

var store = sessions.NewCookieStore([]byte("secret123"))

func main() {
    store.Options.Path = "/"
    ...
}

Be aware that you may not want to send a cookie for all routes (which is what / will do) - so use judgement.

huangapple
  • 本文由 发表于 2015年9月9日 18:20:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/32476956.html
匿名

发表评论

匿名网友

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

确定