-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (157 loc) · 4.41 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Package main provides the main implementation of the supermarket api
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"sync"
)
// produce handles different http methods on the /produce endpoint.
func (h *produceHandlers) produce(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.String(), "/")
switch r.Method {
case http.MethodGet:
// TODO: refactor and bugfix this
switch len(parts) {
case 2:
h.get(w, r)
case 3:
h.getById(w, r)
default:
w.WriteHeader(http.StatusNotFound)
return
}
return
case http.MethodPost:
h.post(w, r)
return
case http.MethodDelete:
h.delete(w, r)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
// get handles get request on the /produce endpoint
func (h *produceHandlers) get(w http.ResponseWriter, r *http.Request) {
// Convert map to array of produce items.
produce := make([]Produce, len(h.store))
h.mu.Lock()
i := 0
for _, item := range h.store {
produce[i] = item
i++
}
h.mu.Unlock()
// Convert to JSON bytes and send as response body
jsonBytes, err := json.Marshal(produce)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonBytes)
}
// getById handles get request for a produce by produceCode
func (h *produceHandlers) getById(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.String(), "/")
h.mu.Lock()
item, found := h.store[parts[2]]
h.mu.Unlock()
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
jsonBytes, err := json.Marshal(item)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonBytes)
}
// post handles post requests on the /produce endpoint.
// post accepts valid json that conforms to the Produce spec. Arrays of
// Produce or single Produce JSON is accepted.
func (h *produceHandlers) post(w http.ResponseWriter, r *http.Request) {
bodyBytes, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
ct := r.Header.Get("content-type")
if ct != "application/json" {
w.WriteHeader(http.StatusUnsupportedMediaType)
fmt.Fprintf(w, "need content-type 'application/json', but got '%s'", ct)
return
}
var newProduce []Produce // TODO handle single json object and json arrays
err = json.Unmarshal(bodyBytes, &newProduce)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
h.mu.Lock()
for _, item := range newProduce {
_, exists := h.store[item.ProduceCode]
h.store[item.ProduceCode] = item
w.WriteHeader(http.StatusCreated)
if exists {
// TODO: update when warning is being written out. This causes 200 to be returned early.
fmt.Fprintf(w, "Warning: Duplicate ProduceCodes detected: Item %s already exists.", item.ProduceCode)
}
}
defer h.mu.Unlock()
}
func (h *produceHandlers) delete(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.String(), "/")
if len(parts) != 3 {
w.WriteHeader(http.StatusBadRequest)
return
}
_, exists := h.store[parts[2]]
if !exists {
w.WriteHeader(http.StatusNotFound)
return
}
h.mu.Lock()
delete(h.store, parts[2])
h.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func main() {
produceHandlers := newProduceHandlers()
router := http.NewServeMux()
router.HandleFunc("/produce", produceHandlers.produce)
router.HandleFunc("/produce/", produceHandlers.produce)
log.Fatal(http.ListenAndServe(":6620", router))
}
type Produce struct {
Name string `json:"name"`
ProduceCode string `json:"produceCode"`
UnitPrice float64 `json:"unitPrice"`
}
type produceHandlers struct {
mu sync.Mutex
store map[string]Produce
}
func newProduceHandlers() *produceHandlers {
return &produceHandlers{
store: map[string]Produce{
"A12T-4GH7-QPL9-3N4M": {Name: "Lettuce", ProduceCode: "A12T-4GH7-QPL9-3N4M", UnitPrice: 3.46},
"E5T6-9UI3-TH15-QR88": {Name: "Peach", ProduceCode: "E5T6-9UI3-TH15-QR88", UnitPrice: 2.99},
"YRT6-72AS-K736-L4AR": {Name: "Green Pepper", ProduceCode: "YRT6-72AS-K736-L4AR", UnitPrice: 0.79},
"TQ4C-VV6T-75ZX-1RMR": {Name: "Gala Apple", ProduceCode: "TQ4C-VV6T-75ZX-1RMR", UnitPrice: 3.59},
},
}
}