package gorilla import ( "fmt" "net/http" "forge.cadoles.com/wpetit/goweb/service/session" "github.com/gorilla/sessions" ) // Session is an implementation of the session.Session service // backed by github.com/gorilla/sessions Session type Session struct { sess *sessions.Session } // Get retrieve a value from the session func (s *Session) Get(key string) interface{} { return s.sess.Values[key] } // Set updates a value in the session func (s *Session) Set(key string, value interface{}) { s.sess.Values[key] = value } // Unset remove a value in the session func (s *Session) Unset(key string) { delete(s.sess.Values, key) } // AddFlash adds the given flash message to the stack func (s *Session) AddFlash(flashType session.FlashType, message string) { s.sess.AddFlash(message, s.flashKey(flashType)) } // Flashes retrieves the flash messages of the given types in the stack func (s *Session) Flashes(flashTypes ...session.FlashType) []session.Flash { flashes := make([]session.Flash, 0) for _, ft := range flashTypes { rawFlashes := s.sess.Flashes(s.flashKey(ft)) for _, f := range rawFlashes { message := fmt.Sprintf("%v", f) flashes = append(flashes, session.NewBaseFlash(ft, message)) } } return flashes } func (s *Session) flashKey(flashType session.FlashType) string { return fmt.Sprintf("_%s_flash", flashType) } // Save saves the session with its current values func (s *Session) Save(w http.ResponseWriter, r *http.Request) error { return s.sess.Save(r, w) } // Delete deletes the session func (s *Session) Delete(w http.ResponseWriter, r *http.Request) error { s.sess.Options.MaxAge = -1 return s.sess.Save(r, w) } // NewSession returns a new Session func NewSession(sess *sessions.Session) *Session { return &Session{sess} }