-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_api.go
More file actions
90 lines (76 loc) · 2.1 KB
/
http_api.go
File metadata and controls
90 lines (76 loc) · 2.1 KB
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
package clset
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type HTTPServer struct {
crdt *CRDT
mux *mux.Router
}
func NewHTTPServer(crdt *CRDT) *HTTPServer {
server := &HTTPServer{
crdt: crdt,
mux: mux.NewRouter(),
}
server.routes()
return server
}
func (s *HTTPServer) routes() {
s.mux.HandleFunc("/key/{key}", s.handleGetKey).Methods("GET")
s.mux.HandleFunc("/key/{key}", s.handlePutKey).Methods("PUT")
s.mux.HandleFunc("/key/{key}", s.handleDeleteKey).Methods("DELETE")
s.mux.HandleFunc("/count", s.handleCountKeys).Methods("GET")
}
func (s *HTTPServer) Serve(addr string) {
log.Printf("HTTP API listening at %s", addr)
log.Fatal(http.ListenAndServe(addr, s.mux))
}
func (s *HTTPServer) handleGetKey(w http.ResponseWriter, r *http.Request) {
key := mux.Vars(r)["key"]
val, exists, err := s.crdt.Get(key)
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if !exists {
http.Error(w, "Key not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(map[string]string{
"key": key,
"value": string(val),
})
}
func (s *HTTPServer) handlePutKey(w http.ResponseWriter, r *http.Request) {
key := mux.Vars(r)["key"]
var data struct {
Value string `json:"value"`
}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if err := s.crdt.Set(key, []byte(data.Value)); err != nil {
http.Error(w, "Failed to set key", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *HTTPServer) handleDeleteKey(w http.ResponseWriter, r *http.Request) {
key := mux.Vars(r)["key"]
if err := s.crdt.Delete(key); err != nil {
http.Error(w, "Failed to delete key", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *HTTPServer) handleCountKeys(w http.ResponseWriter, r *http.Request) {
count, err := s.crdt.KeyCount()
if err != nil {
http.Error(w, "Failed to count keys", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]uint64{"count": count})
}