-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
78 lines (63 loc) · 1.34 KB
/
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
package session
import (
"sync"
"github.com/yonzay/tlsfiber"
"github.com/yonzay/tlsfiber/internal/gotiny"
"github.com/yonzay/tlsfiber/internal/storage/memory"
)
type Store struct {
Config
}
var mux sync.Mutex
func New(config ...Config) *Store {
// Set default config
cfg := configDefault(config...)
if cfg.Storage == nil {
cfg.Storage = memory.New()
}
return &Store{
cfg,
}
}
// RegisterType will allow you to encode/decode custom types
// into any Storage provider
func (s *Store) RegisterType(i interface{}) {
gotiny.Register(i)
}
// Get will get/create a session
func (s *Store) Get(c *fiber.Ctx) (*Session, error) {
var fresh bool
// Get key from cookie
id := c.Cookies(s.CookieName)
// If no key exist, create new one
if len(id) == 0 {
id = s.KeyGenerator()
fresh = true
}
// Create session object
sess := acquireSession()
sess.ctx = c
sess.config = s
sess.id = id
sess.fresh = fresh
// Fetch existing data
if !fresh {
raw, err := s.Storage.Get(id)
// Unmashal if we found data
if raw != nil && err == nil {
mux.Lock()
gotiny.Unmarshal(raw, &sess.data)
mux.Unlock()
sess.fresh = false
} else if err != nil {
return nil, err
} else {
sess.fresh = true
}
}
return sess, nil
}
// Reset will delete all session from the storage
func (s *Store) Reset() error {
return s.Storage.Reset()
}