-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
78 lines (66 loc) · 2.06 KB
/
handlers.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
package main
import (
"encoding/json"
"net/http"
"github.com/google/uuid"
"github.com/gorilla/mux"
)
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func getCustomers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(customers)
}
func getCustomer(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
id := mux.Vars(r)["id"]
if _, ok := customers[id]; ok {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(customers[id])
} else {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode("not found")
}
}
func deleteCustomer(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
id := mux.Vars(r)["id"]
if _, ok := customers[id]; ok {
delete(customers, id)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(customers)
} else {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode("not found")
}
}
func addCustomer(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
id := uuid.New().String()
if _, ok := customers[id]; ok {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode("id already exits, please use the update route")
} else {
var customer Customer
json.NewDecoder(r.Body).Decode(&customer)
customers[id] = customer
respondWithJSON(w, http.StatusCreated, customer)
}
}
func updateCustomer(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
id := mux.Vars(r)["id"]
if _, ok := customers[id]; ok {
var customer Customer
json.NewDecoder(r.Body).Decode(&customer)
customers[id] = customer
respondWithJSON(w, http.StatusOK, customer)
} else {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode("not found")
}
}