-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
135 lines (114 loc) · 2.35 KB
/
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
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
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
)
type InMemoryStore struct {
sync.Mutex
store map[string]string
}
func NewInMemoryStore() *InMemoryStore {
return &InMemoryStore{
store: make(map[string]string),
}
}
// Set a key-value pair
func (s *InMemoryStore) Set(key string, value string) {
s.Lock()
defer s.Unlock()
s.store[key] = value
}
// Get a value by key
func (s *InMemoryStore) Get(key string) (string, bool) {
s.Lock()
defer s.Unlock()
value, ok := s.store[key]
return value, ok
}
// Delete a key-value pair
func (s *InMemoryStore) Delete(key string) {
s.Lock()
defer s.Unlock()
delete(s.store, key)
}
func (s *InMemoryStore) Drop() {
s.Lock()
defer s.Unlock()
s.store = make(map[string]string)
}
type Response struct {
Error string `json:"error,omitempty"`
Data any `json:"data,omitempty"`
}
type StoredData struct {
Key string `json:"key"`
Value string `json:"value"`
}
func main() {
s := NewInMemoryStore()
apiKey := ""
port := "9191"
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
providedAPIKey := r.Header.Get("X-API-KEY")
if providedAPIKey != apiKey {
w.WriteHeader(http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "application/json")
// Fetch
if r.Method == http.MethodGet {
key := r.URL.Query().Get("key")
value, ok := s.Get(key)
resp := &Response{}
if ok {
resp.Data = value
json.NewEncoder(w).Encode(resp)
return
}
resp.Error = "missing"
json.NewEncoder(w).Encode(resp)
return
}
// Update
if r.Method == http.MethodPost {
var b StoredData
resp := &Response{}
err := json.NewDecoder(r.Body).Decode(&b)
if err != nil {
log.Println("could not insert new key", err)
resp.Error = "internalError"
json.NewEncoder(w).Encode(resp)
return
}
s.Set(b.Key, b.Value)
resp.Data = b
json.NewEncoder(w).Encode(resp)
return
}
// Delete
if r.Method == http.MethodDelete {
q := r.URL.Query()
// Drop the whole store.
drop := q.Get("drop")
if drop == "true" {
s.Drop()
resp := &Response{
Data: true,
}
json.NewEncoder(w).Encode(resp)
return
}
// Delete by key.
key := q.Get("key")
s.Delete(key)
resp := &Response{
Data: true,
}
json.NewEncoder(w).Encode(resp)
return
}
})
log.Fatal(http.ListenAndServe(":"+port, nil))
}