2

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() ?

vinniyo
  • 787
  • 2
  • 8
  • 21
  • 1
    You could go the simple route and encode your data as a string using `encoding/json` for example. Other options would be a base64 encoded gob. Or just store the various pieces in the session individually like you show above, and use a couple helpers to store from a `t.Token` and recreate a `t.Token` from the session data. – sberry Feb 27 '15 at 06:34

2 Answers2

1

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)
}
icza
  • 389,944
  • 63
  • 907
  • 827
  • I used jsonT, err := json.Marshal(t) and var t *oauth.Transport json.Unmarshal([]byte(c.Session["jsonT"]), &t) Thank you! – vinniyo Feb 27 '15 at 08:08
0

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.

https://revel.github.io/manual/cache.html

anonx
  • 26
  • 4