1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package sessions
import (
"net/http"
"sync"
"github.com/google/uuid"
)
type SessionValues map[string]any
type Session struct {
id string
values SessionValues
lock *sync.Mutex
}
type SessionCtxKey string
var _sessions map[string]*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
// TODO make secure
http.SetCookie(w, &http.Cookie{
Name: "session_token",
Value: token,
})
// create session and store
s := &Session{
id: token,
values: SessionValues(values),
lock: &sync.Mutex{},
}
_sessions[token] = s
return s
}
func GetSession(id string) (*Session, bool) {
s, ok := _sessions[id]
return s, ok
}
func (s *Session) Id() string {
return s.id
}
func (s *Session) Get(key string) interface{} {
s.lock.Lock()
defer s.lock.Unlock()
return s.values[key]
}
func (s *Session) Set(key string, value interface{}) bool {
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: "",
})
}
|