-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (98 loc) · 2.15 KB
/
main.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
package main
import (
"log"
"net/http"
"os"
"sync"
"github.com/gorilla/mux"
)
type Store struct {
store sync.Map
}
type APP struct {
router *mux.Router
KVS *Store
}
func (app *APP) setup() {
app.router.HandleFunc("/health", ping)
app.router.HandleFunc("/set/{key}/{value}", app.SetHandler)
app.router.HandleFunc("/get/{key}", app.GETHandler)
app.router.HandleFunc("/delete/{key}", app.DeleteHandler)
}
func (app *APP) run() {
var port = os.Getenv("PORT")
if port == "" {
port = "8080"
}
app.setup()
log.Println("Server is running on port: " + port)
log.Fatal(http.ListenAndServe(":"+port, app.router))
}
func (s *Store) Set(key string, value string) {
s.store.LoadOrStore(key, value)
}
func (s *Store) Get(key string) (string, bool) {
value, ok := s.store.Load(key)
if !ok {
return "", false
}
return value.(string), true
}
func (s *Store) Delete(key string) {
s.store.Delete(key)
}
func (s *Store) setupRoute(key string) {
s.store.Delete(key)
}
func ping(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}
func (a *APP) GETHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
if key == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("key is required"))
}
value, found := a.KVS.Get(key)
if !found {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("value not found"))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(value))
}
func (a *APP) DeleteHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
if key == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("key is required"))
}
a.KVS.Delete(key)
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
func (a *APP) SetHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
value := vars["value"]
if key == "" || value == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("key/value is required"))
return
}
a.KVS.Set(key, value)
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
func main() {
var app = &APP{
router: mux.NewRouter(),
KVS: &Store{
store: sync.Map{},
},
}
app.run()
}