Skip to content

Commit 735823f

Browse files
committed
Merge branch 'develop/memorystore'
2 parents 243fbd7 + a1f59b1 commit 735823f

File tree

2 files changed

+35
-13
lines changed

2 files changed

+35
-13
lines changed

memorystore.go

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ package sessions
22

33
import (
44
"crypto/rand"
5-
"fmt"
6-
"io"
5+
"crypto/sha256"
6+
"encoding/hex"
77
"sync"
88
"time"
99

10+
"io"
11+
1012
"github.com/go-http-utils/cookie"
1113
)
1214

@@ -26,7 +28,13 @@ func NewMemoryStore(options ...*Options) (store *MemoryStore) {
2628
opts.Secure = temp.Secure
2729
opts.HTTPOnly = temp.HTTPOnly
2830
}
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+
3038
go store.cleanCache()
3139
return
3240
}
@@ -42,6 +50,7 @@ type MemoryStore struct {
4250
store map[string]*sessionValue
4351
ticker *time.Ticker
4452
lock sync.Mutex
53+
done chan bool
4554
}
4655

4756
// Load a session by name and any kind of stores
@@ -70,7 +79,7 @@ func (m *MemoryStore) Save(session Sessions) (err error) {
7079
}
7180
sid := session.GetSID()
7281
if sid == "" {
73-
sid, _ = newUUID()
82+
sid = NewSID(val)
7483
}
7584
m.lock.Lock()
7685
defer m.lock.Unlock()
@@ -88,9 +97,21 @@ func (m *MemoryStore) Len() int {
8897
defer m.lock.Unlock()
8998
return len(m.store)
9099
}
100+
101+
// Destroy goroutine cleanCache thread
102+
func (m *MemoryStore) Destroy() {
103+
close(m.done)
104+
}
105+
91106
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+
}
94115
}
95116
}
96117
func (m *MemoryStore) clean() {
@@ -122,11 +143,10 @@ func (m *MemoryStore) clean() {
122143
}
123144
}
124145

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))
132152
}

memorystore_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,8 @@ func TestMemoryStore(t *testing.T) {
237237
assert.Equal(int64(0), session.Age)
238238
})
239239
handler.ServeHTTP(recorder, req)
240+
241+
store.Destroy()
240242
})
241243
}
242244
func genID() string {

0 commit comments

Comments
 (0)