-
Notifications
You must be signed in to change notification settings - Fork 2
/
local_store.go
64 lines (52 loc) · 1.28 KB
/
local_store.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
package toy
import (
"context"
"fmt"
"sync"
"github.com/sbogacz/going-serverless/02_separate_binaries/internal/httperrs"
)
// LocalStore is an in-memory implementation of our
// store interface
type LocalStore struct {
store map[string]string
lock *sync.RWMutex
}
// NewLocalStore returns a local implementation of the
// Store interface
func NewLocalStore() *LocalStore {
return &LocalStore{
store: make(map[string]string),
lock: &sync.RWMutex{},
}
}
// Set stores the given data at the given key
func (l *LocalStore) Set(ctx context.Context, key, data string) error {
l.lock.Lock()
l.store[key] = data
l.lock.Unlock()
return nil
}
// Get retrieves the data stored at the given key
func (l *LocalStore) Get(ctx context.Context, key string) (string, error) {
l.lock.RLock()
data, ok := l.store[key]
l.lock.RUnlock()
if !ok {
return "", httperrs.NotFound(fmt.Errorf("no item found at %s", key), "")
}
return data, nil
}
// Del removes the data stored at the given key
func (l *LocalStore) Del(ctx context.Context, key string) error {
l.lock.RLock()
_, ok := l.store[key]
l.lock.RUnlock()
if !ok {
return httperrs.NotFound(fmt.Errorf("no item found at %s", key), "")
}
// if we have the item, delete
l.lock.Lock()
delete(l.store, key)
l.lock.Unlock()
return nil
}