Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

How to update session attributes in Store without re-adding cookie #12

Open
orian opened this issue Mar 21, 2018 · 4 comments
Open

How to update session attributes in Store without re-adding cookie #12

orian opened this issue Mar 21, 2018 · 4 comments

Comments

@orian
Copy link

orian commented Mar 21, 2018

The Manager has Add method for adding, but nothing to update session values.
Any suggestions on storing values?

@icza
Copy link
Owner

icza commented Mar 21, 2018

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
}

@icza
Copy link
Owner

icza commented Mar 21, 2018

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.

@orian
Copy link
Author

orian commented Mar 21, 2018

Using a custom Store mechanism (db based) the data won't be updated.

@icza
Copy link
Owner

icza commented Mar 21, 2018

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

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants