-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
66 lines (49 loc) · 1.22 KB
/
storage.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
package ltt
import (
"context"
"errors"
)
type storageContextKeyType int
var storageContextKey storageContextKeyType
// Local storage for each user instance
type Storage struct {
data map[string]interface{}
}
var ErrInvalidStorageValue = errors.New("invalid storage value")
func (s *Storage) GetInt(key string) (int, error) {
if v, ok := s.Get(key).(int); ok {
return v, nil
}
return 0, ErrInvalidStorageValue
}
func (s *Storage) GetInt64(key string) (int64, error) {
if v, ok := s.Get(key).(int64); ok {
return v, nil
}
return 0, ErrInvalidStorageValue
}
func (s *Storage) GetString(key string) (string, error) {
if v, ok := s.Get(key).(string); ok {
return v, nil
}
return "", ErrInvalidStorageValue
}
func (s *Storage) Get(key string) interface{} {
v, _ := s.data[key]
return v
}
func (s *Storage) Set(key string, value interface{}) {
s.data[key] = value
}
func NewStorageContext(ctx context.Context, s *Storage) context.Context {
return context.WithValue(ctx, storageContextKey, s)
}
func StorageFromContext(ctx context.Context) *Storage {
if s, ok := ctx.Value(storageContextKey).(*Storage); ok {
return s
}
return nil
}
func NewStorage() *Storage {
return &Storage{data: make(map[string]interface{})}
}