goweb/session/gorilla/session.go

69 lines
1.7 KiB
Go
Raw Permalink Normal View History

2018-12-06 15:18:05 +01:00
package gorilla
import (
"fmt"
"net/http"
"github.com/gorilla/sessions"
2019-07-28 13:11:23 +02:00
"gitlab.com/wpetit/goweb/service/session"
2018-12-06 15:18:05 +01:00
)
// 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 {
2018-12-09 13:21:51 +01:00
s.sess.Options.MaxAge = -1
2018-12-06 15:18:05 +01:00
return s.sess.Save(r, w)
}
// NewSession returns a new Session
func NewSession(sess *sessions.Session) *Session {
return &Session{sess}
}