-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
143 lines (128 loc) · 2.5 KB
/
database.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"sync"
"time"
)
type DB struct {
lock sync.Mutex
sessions map[string]*Session
counters map[string]*StoredCounter
todos map[string]*StoredTodo
}
func NewDB() *DB {
return &DB{
sessions: make(map[string]*Session),
counters: make(map[string]*StoredCounter),
todos: make(map[string]*StoredTodo),
}
}
type Session struct {
ID string
Created time.Time
LastSeen time.Time
New bool
}
type StoredCounter struct {
ID string
Count int
}
func (db *DB) newSession() (*Session, error) {
id, err := RandomString()
if err != nil {
return nil, fmt.Errorf("RandomString error: %w", err)
}
s := &Session{
ID: id,
Created: time.Now(),
LastSeen: time.Now(),
New: true,
}
db.sessions[id] = s
return s, nil
}
func (db *DB) GetSession(id string) (*Session, error) {
db.lock.Lock()
defer db.lock.Unlock()
if id == "" {
return db.newSession()
}
s, ok := db.sessions[id]
if !ok {
return db.newSession()
}
return s, nil
}
func (db *DB) SetSession(s *Session) error {
db.lock.Lock()
defer db.lock.Unlock()
db.sessions[s.ID] = s
return nil
}
func (db *DB) GetCounter(id string) (*StoredCounter, error) {
db.lock.Lock()
defer db.lock.Unlock()
c, ok := db.counters[id]
if !ok {
c = &StoredCounter{
ID: id,
Count: 0,
}
db.counters[id] = c
}
return c, nil
}
func (db *DB) SetCounter(c *StoredCounter) error {
db.lock.Lock()
defer db.lock.Unlock()
db.counters[c.ID] = c
return nil
}
func RandomString() (string, error) {
// AES 192 == 24 bytes, so that should be enough
// 24 bytes *8/6 = 32 bytes base64 encoded
const length = 24
buf := make([]byte, length)
n, err := rand.Read(buf)
if err != nil {
return "", fmt.Errorf("rand.Read failed: %w", err)
}
if n != length {
return "", fmt.Errorf("short rand.Read: %d", n)
}
str := base64.URLEncoding.EncodeToString(buf)
return str, nil
}
type StoredTodo struct {
SessionID string
Items []StoredTodoItem
}
type StoredTodoItem struct {
ID int
Done bool
Text string
}
func (db *DB) GetTodo(id string) (*StoredTodo, error) {
db.lock.Lock()
defer db.lock.Unlock()
t, ok := db.todos[id]
if !ok {
t = &StoredTodo{
SessionID: id,
Items: []StoredTodoItem{
{ID: 1, Text: "Buy bread", Done: true},
{ID: 2, Text: "Buy oatmilk", Done: false},
},
}
db.todos[id] = t
}
return t, nil
}
func (db *DB) SetTodo(t *StoredTodo) error {
db.lock.Lock()
defer db.lock.Unlock()
db.todos[t.SessionID] = t
return nil
}