英文:
Revel - Storing an object in session
问题
我正在使用oauth包"code.google.com/p/goauth2/oauth"与revel,并且它创建了一些包含大量信息的结构。我需要这些信息在整个会话期间保持持久性,但会话只能是字符串类型。有没有比以下方法更好的方法?
c.Session["AccessToken"] = t.Token.AccessToken
c.Session["RefreshToken"] = t.Token.RefreshToken
...
如果没有,如何重新分配字符串以创建另一个结构来调用Client.Get()?
英文:
I'm using the oauth package "code.google.com/p/goauth2/oauth" with revel and the it creates a few structures with quite a bit of information in it. I need this information to be persistent throughout the session but sessions can only be type string. Is there a better way of doing this than the following?
c.Session["AccessToken"] = t.Token.AccessToken
c.Session["RefreshToken"] = t.Token.RefreshToken
...
If not how do I reassign the strings to create another structure to call Client.Get() ?
答案1
得分: 1
你可以使用json
包将结构体转换为string
,反之亦然。只需知道只有导出的字段才会以这种方式进行序列化。
由于oauth.Token
只有导出的字段,所以这样做是可行的:
if data, err := json.Marshal(t.Token); err == nil {
c.Session["Token"] = string(data)
} else {
panic(err)
}
以下是如何从会话中重建令牌的方法:
if err := json.Unmarshal([]byte(c.Session["Token"]), &t.Token); err != nil {
panic(err)
}
英文:
You can use the json
package to "convert" structs to string
and vice versa. Just know that only exported fields are serialized this way.
Since oauth.Token
has only exported fields, this will work:
if data, err := json.Marshal(t.Token); err == nil {
c.Session["Token"] = string(data)
} else {
panic(err)
}
And this is how you can reconstruct the token from the session:
if err := json.Unmarshal([]byte(c.Session["Token"]), &t.Token); err != nil {
panic(err)
}
答案2
得分: 0
你可以尝试将一些字符串ID保存到Session
中,并将所需的对象保存到Cache
中,而不是使用上述的方法:
c.Session["id"] = id
go cache.Set("token_"+id, t.Token, 30*time.Minute)
然后按照以下方式使用它:
var token oauth.Token
id := c.Session["id"]
if err := cache.Get("token_"+id, &token); err != nil {
// TODO: token not found, do something
}
// TODO: 在这里使用你的token...
这种方法的优点是你不需要显式地使用json
包,并且缓存有几种不同的后端可供选择:内存、Redis、Memcached。此外,与基于Cookie
的Session
相比,你没有4K的限制。
https://revel.github.io/manual/cache.html
英文:
Instead of that you can try to save some string ID to Session
and the object you need to Cache
:
c.Session["id"] = id
go cache.Set("token_"+id, t.Token, 30*time.Minute)
And then use it as follows:
var token oauth.Token
id := c.Session["id"]
if err := cache.Get("token_"+id, &token); err != nil {
// TODO: token not found, do something
}
// TODO: use your token here...
The advantage of this approach is you do not have to work with json
package explicitly and cache has a few different back-ends out of the box: memory, redis, memcached. Moreover, you do not have a limitation of 4K as in case of Cookie
based Session
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论