-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpHandler.go
95 lines (78 loc) · 2.1 KB
/
httpHandler.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
package main
import (
"encoding/json"
"errors"
"net/http"
"github.com/gorilla/mux"
"github.com/iamNoah1/vortex/store"
"github.com/iamNoah1/vortex/transaction"
)
func putKeyValuePairHandler(w http.ResponseWriter, r *http.Request, logger transaction.TransactionLogger) {
vars := mux.Vars(r)
key := vars["key"]
var kv store.KeyValuePair
err := json.NewDecoder(r.Body).Decode(&kv)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = store.Put(key, kv.Value)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = logger.Put(key, kv.Value)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func getKeyValuePairHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
kv, err := store.GetKeyValuePair(key)
if err != nil {
if errors.Is(err, store.ErrorNoSuchKey) {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(kv)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func getAllKeyValuePairsHandler(w http.ResponseWriter, r *http.Request) {
kvs, err := store.GetAllKeyValuePairs()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(kvs)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func deleteKeyValuePairHandler(w http.ResponseWriter, r *http.Request, logger transaction.TransactionLogger) {
vars := mux.Vars(r)
key := vars["key"]
err := store.Delete(key)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = logger.Delete(key)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte("Key deleted successfully"))
}