@@ -2,11 +2,13 @@ package sessions
2
2
3
3
import (
4
4
"crypto/rand"
5
- "fmt "
6
- "io "
5
+ "crypto/sha256 "
6
+ "encoding/hex "
7
7
"sync"
8
8
"time"
9
9
10
+ "io"
11
+
10
12
"github.com/go-http-utils/cookie"
11
13
)
12
14
@@ -26,7 +28,13 @@ func NewMemoryStore(options ...*Options) (store *MemoryStore) {
26
28
opts .Secure = temp .Secure
27
29
opts .HTTPOnly = temp .HTTPOnly
28
30
}
29
- store = & MemoryStore {opts : opts , ticker : time .NewTicker (time .Second ), store : make (map [string ]* sessionValue )}
31
+ store = & MemoryStore {
32
+ opts : opts ,
33
+ ticker : time .NewTicker (time .Second ),
34
+ store : make (map [string ]* sessionValue ),
35
+ done : make (chan bool , 1 ),
36
+ }
37
+
30
38
go store .cleanCache ()
31
39
return
32
40
}
@@ -42,6 +50,7 @@ type MemoryStore struct {
42
50
store map [string ]* sessionValue
43
51
ticker * time.Ticker
44
52
lock sync.Mutex
53
+ done chan bool
45
54
}
46
55
47
56
// Load a session by name and any kind of stores
@@ -70,7 +79,7 @@ func (m *MemoryStore) Save(session Sessions) (err error) {
70
79
}
71
80
sid := session .GetSID ()
72
81
if sid == "" {
73
- sid , _ = newUUID ( )
82
+ sid = NewSID ( val )
74
83
}
75
84
m .lock .Lock ()
76
85
defer m .lock .Unlock ()
@@ -88,9 +97,21 @@ func (m *MemoryStore) Len() int {
88
97
defer m .lock .Unlock ()
89
98
return len (m .store )
90
99
}
100
+
101
+ // Destroy goroutine cleanCache thread
102
+ func (m * MemoryStore ) Destroy () {
103
+ close (m .done )
104
+ }
105
+
91
106
func (m * MemoryStore ) cleanCache () {
92
- for range m .ticker .C {
93
- m .clean ()
107
+ defer m .ticker .Stop ()
108
+ for {
109
+ select {
110
+ case <- m .ticker .C :
111
+ m .clean ()
112
+ case <- m .done :
113
+ return
114
+ }
94
115
}
95
116
}
96
117
func (m * MemoryStore ) clean () {
@@ -122,11 +143,10 @@ func (m *MemoryStore) clean() {
122
143
}
123
144
}
124
145
125
- // newUUID generates a random UUID according to RFC 4122
126
- func newUUID () (string , error ) {
127
- uuid := make ([]byte , 16 )
128
- io .ReadFull (rand .Reader , uuid )
129
- uuid [8 ] = uuid [8 ]&^0xc0 | 0x80
130
- uuid [6 ] = uuid [6 ]&^0xf0 | 0x40
131
- return fmt .Sprintf ("%x%x%x%x%x" , uuid [0 :4 ], uuid [4 :6 ], uuid [6 :8 ], uuid [8 :10 ], uuid [10 :]), nil
146
+ // NewSID generates a random SID
147
+ func NewSID (val string ) string {
148
+ h := sha256 .New ()
149
+ h .Write ([]byte (val ))
150
+ io .CopyN (h , rand .Reader , 8 )
151
+ return hex .EncodeToString (h .Sum (nil ))
132
152
}
0 commit comments