-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
63 lines (51 loc) · 1.23 KB
/
server.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/c-Brooks/zookeeper-demo/persistence"
)
// serve listens and serves HTTP on port 8080
func serve(kvrw persistence.KeyValueReadWriter) {
h := handler{kvrw}
http.ListenAndServe(":8080", h)
}
// handler implements the http.Handler interface (ServeHTTP)
type handler struct {
kvrw persistence.KeyValueReadWriter
}
// handle requests to /
// body should contain {"key": key, "value": value}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logrus.Infof("handling %s request to %s", r.Method, r.URL)
var m map[string]string
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Warn(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
err = json.Unmarshal(body, &m)
if err != nil {
logrus.Warn(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
key := m["key"]
value := m["value"]
switch r.Method {
case http.MethodPost:
t := persistence.NewTuple(key, value)
err := h.kvrw.CreateResource(t)
if err != nil {
logrus.Warn(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
case http.MethodPut:
// edit k/v
case http.MethodDelete:
// delete k/v
}
}