/
storage_mem.go
99 lines (81 loc) · 2.03 KB
/
storage_mem.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
87
88
89
90
91
92
93
94
95
96
97
98
99
package session
import (
"context"
"io"
"os"
"sync"
"golang.org/x/xerrors"
)
// StorageMemory implements in-memory session storage.
// Goroutine-safe.
type StorageMemory struct {
mux sync.RWMutex
data []byte
}
// Dump dumps raw session data to the given writer.
// Returns ErrNotFound if storage is nil or if underlying session is empty.
func (s *StorageMemory) Dump(w io.Writer) error {
if s == nil {
return ErrNotFound
}
s.mux.RLock()
defer s.mux.RUnlock()
if len(s.data) == 0 {
return ErrNotFound
}
if _, err := w.Write(s.data); err != nil {
return xerrors.Errorf("write session: %w", err)
}
return nil
}
// WriteFile dumps raw session data to the named file, creating it if necessary.
// Returns ErrNotFound if storage is nil or if underlying session is empty.
func (s *StorageMemory) WriteFile(name string, perm os.FileMode) error {
data, err := s.Bytes(nil)
if err != nil {
return err
}
return os.WriteFile(name, data, perm)
}
// Bytes appends raw session data to the given slice.
// Returns ErrNotFound if storage is nil or if underlying session is empty.
func (s *StorageMemory) Bytes(to []byte) ([]byte, error) {
if s == nil {
return nil, ErrNotFound
}
s.mux.RLock()
defer s.mux.RUnlock()
if len(s.data) == 0 {
return nil, ErrNotFound
}
return append(to, s.data...), nil
}
// Clone creates a clone of existing StorageMemory,
func (s *StorageMemory) Clone() *StorageMemory {
s2 := &StorageMemory{}
s2.data, _ = s.Bytes(s2.data)
return s2
}
// LoadSession loads session from memory.
func (s *StorageMemory) LoadSession(context.Context) ([]byte, error) {
if s == nil {
return nil, ErrNotFound
}
s.mux.RLock()
defer s.mux.RUnlock()
if len(s.data) == 0 {
return nil, ErrNotFound
}
cpy := append([]byte(nil), s.data...)
return cpy, nil
}
// StoreSession stores session to memory.
func (s *StorageMemory) StoreSession(ctx context.Context, data []byte) error {
if s == nil {
return xerrors.New("StoreSession called on StorageMemory(nil)")
}
s.mux.Lock()
s.data = data
s.mux.Unlock()
return nil
}