github.com/fasmat/buffalo@v0.11.0/session.go (about) 1 package buffalo 2 3 import ( 4 "net/http" 5 6 "github.com/gorilla/sessions" 7 "github.com/pkg/errors" 8 ) 9 10 // Session wraps the "github.com/gorilla/sessions" API 11 // in something a little cleaner and a bit more useable. 12 type Session struct { 13 Session *sessions.Session 14 req *http.Request 15 res http.ResponseWriter 16 } 17 18 // Save the current session. 19 func (s *Session) Save() error { 20 return s.Session.Save(s.req, s.res) 21 } 22 23 // Get a value from the current session. 24 func (s *Session) Get(name interface{}) interface{} { 25 return s.Session.Values[name] 26 } 27 28 // GetOnce gets a value from the current session and then deletes it. 29 func (s *Session) GetOnce(name interface{}) interface{} { 30 if x, ok := s.Session.Values[name]; ok { 31 s.Delete(name) 32 return x 33 } 34 return nil 35 } 36 37 // Set a value onto the current session. If a value with that name 38 // already exists it will be overridden with the new value. 39 func (s *Session) Set(name, value interface{}) { 40 s.Session.Values[name] = value 41 } 42 43 // Delete a value from the current session. 44 func (s *Session) Delete(name interface{}) { 45 delete(s.Session.Values, name) 46 } 47 48 // Clear the current session 49 func (s *Session) Clear() { 50 for k := range s.Session.Values { 51 s.Delete(k) 52 } 53 } 54 55 // Get a session using a request and response. 56 func (a *App) getSession(r *http.Request, w http.ResponseWriter) *Session { 57 if a.root != nil { 58 return a.root.getSession(r, w) 59 } 60 session, _ := a.SessionStore.Get(r, a.SessionName) 61 return &Session{ 62 Session: session, 63 req: r, 64 res: w, 65 } 66 } 67 68 func sessionSaver(next Handler) Handler { 69 return func(c Context) error { 70 err := next(c) 71 if err != nil { 72 return errors.WithStack(err) 73 } 74 return c.Session().Save() 75 } 76 }