forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession_store.go
86 lines (69 loc) · 1.42 KB
/
session_store.go
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
76
77
78
79
80
81
82
83
84
85
86
package inmem
import (
"errors"
"sync"
"time"
)
type SessionStore struct {
data map[string]string
timers map[string]*time.Timer
mu sync.RWMutex
}
func NewSessionStore() *SessionStore {
return &SessionStore{
data: map[string]string{},
timers: map[string]*time.Timer{},
}
}
func (s *SessionStore) Set(key, val string, expireAt time.Time) error {
if !expireAt.IsZero() && expireAt.Before(time.Now()) {
// key is already expired. no problem
return nil
}
s.mu.Lock()
s.data[key] = val
s.mu.Unlock()
if !expireAt.IsZero() {
return s.ExpireAt(key, expireAt)
}
return nil
}
func (s *SessionStore) Get(key string) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
return s.data[key], nil
}
func (s *SessionStore) Delete(key string) error {
s.mu.Lock()
defer s.mu.Unlock()
timer := s.timers[key]
if timer != nil {
timer.Stop()
}
delete(s.data, key)
delete(s.timers, key)
return nil
}
func (s *SessionStore) ExpireAt(key string, expireAt time.Time) error {
s.mu.Lock()
existingTimer, ok := s.timers[key]
if ok {
if !existingTimer.Stop() {
return errors.New("session has expired")
}
}
duration := time.Until(expireAt)
if duration <= 0 {
s.mu.Unlock()
s.Delete(key)
return nil
}
s.timers[key] = time.AfterFunc(time.Until(expireAt), s.timerExpireFunc(key))
s.mu.Unlock()
return nil
}
func (s *SessionStore) timerExpireFunc(key string) func() {
return func() {
s.Delete(key)
}
}