英文:
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仅发送到该路径及其以下路径,而不是上面的路径,例如:
- 当您通过
session.Set(val, key)
隐式设置它时,为/modules
设置cookie。 - Cookie 被发送到
/modules
,/modules/all
和/modules/detail/12
。 - 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.
- Cookie set for
/modules
when you implicitly set it for the first time viasession.Set(val, key)
- Cookie is sent for
/modules
,/modules/all
and/modules/detail/12
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论