diff options
Diffstat (limited to 'src/sessions/sessions.go')
| -rw-r--r-- | src/sessions/sessions.go | 38 |
1 files changed, 26 insertions, 12 deletions
diff --git a/src/sessions/sessions.go b/src/sessions/sessions.go index 34fe91c..0124c51 100644 --- a/src/sessions/sessions.go +++ b/src/sessions/sessions.go @@ -7,19 +7,23 @@ import ( "github.com/google/uuid" ) -type sessionvalues map[string]any +type SessionValues map[string]any type Session struct { id string - values sessionvalues - mu *sync.Mutex + values SessionValues + lock *sync.Mutex } type SessionCtxKey string -var _sessions map[string]Session +var _sessions map[string]*Session -func NewSession(w http.ResponseWriter, values map[string]any) Session { +func InitStore() { + _sessions = map[string]*Session{} +} + +func NewSession(w http.ResponseWriter, values map[string]any) *Session { token := uuid.NewString() // set secure cookie in http.ResponseWriter @@ -30,15 +34,16 @@ func NewSession(w http.ResponseWriter, values map[string]any) Session { }) // create session and store - s := Session{ + s := &Session{ id: token, - values: sessionvalues(values), + values: SessionValues(values), + lock: &sync.Mutex{}, } _sessions[token] = s return s } -func GetSession(id string) (Session, bool) { +func GetSession(id string) (*Session, bool) { s, ok := _sessions[id] return s, ok } @@ -48,14 +53,23 @@ func (s *Session) Id() string { } func (s *Session) Get(key string) interface{} { - s.mu.Lock() - defer s.mu.Unlock() + s.lock.Lock() + defer s.lock.Unlock() return s.values[key] } func (s *Session) Set(key string, value interface{}) bool { - s.mu.Lock() - defer s.mu.Unlock() + s.lock.Lock() + defer s.lock.Unlock() s.values[key] = value + _sessions[s.id] = s return true } + +func (s *Session) Destroy(w http.ResponseWriter) { + delete(_sessions, s.id) + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: "", + }) +} |
