session
session copied to clipboard
How to update session attributes in Store without re-adding cookie
The Manager has Add method for adding, but nothing to update session values.
Any suggestions on storing values?
Getting / setting values in the session is done via the Session interface, not via the Manager.
The Session interface has a Session.Attr() method for getting a value, and a Session.SetAttr() for setting / changing the value of an attribute.
Let's assume you want to have a session attribute "Count" which stores the number of requests associated with the session:
Example:
sess := session.Get(r)
if sess == nil {
// No session (yet)
} else {
// We have a session, use it
count, ok := sess.Attr("Count").(int)
if ok {
log.Printf("Counter: %d", count)
}
sess.SetAttr("Count", count+1) // Increment count
}
Some additional notes after re-reading your question:
Changing attributes in the session is a server side operation, it needs no client, cookie or manager updates.
If another request will access the same session, it will see the updated / changed values. You don't have to do anything to "update a session at the Manager". Changes to session attributes are automatically visible to other requests accessing the same session.
Using a custom Store mechanism (db based) the data won't be updated.
True. But that will only cause "trouble" if you have multiple (web) server nodes.
The GAE (Google App Engine) Memcache store implementation solves this by requiring to call the Manager.Close() method when the request ends (or more precisely when the client is done using / updating the Session). Manager.Close() will call Store.Close(), and the implementation flushes the changed sessions into the Memcache (which would be the database in your case).
You can see the implementation here: https://github.com/icza/session/blob/master/gae_memcache_store.go
And a demo using the GAE memcache store: https://github.com/icza/session/blob/master/gae_session_demo/gae_session_demo.go