-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandlers.go
207 lines (165 loc) · 5.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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
import (
"encoding/json"
"net/http"
"fmt"
"strconv"
"github.com/julienschmidt/httprouter"
)
// addDynamicRoutes will dynamically add RESTful routes to the router. Routes are added based off of the keys that
// are present in the parsed JSON file. For instance, if a JSON file is set up like:
//
// {
// "posts": [ { "id": 1, "title": "Foo" } ]
// }
//
// The following routes will be created:
//
// POST /posts (creates a new post record)
// GET /posts (returns all post records)
// GET /posts/:id (returns a specific record)
// PUT /posts/:id (creates or updates a record with the specified ID)
// PATCH /posts/:id (updates a record with the specified ID)
// DELETE /posts/:id (deletes the specified record)
//
//
func addDynamicRoutes(router *httprouter.Router) {
// set up our routes
for _, itemType := range serverData.ItemTypes() {
// Shadow these variables. If this isn't done, then the closures below will see
// `value` and `key` as whatever they were in the last(?) iteration of the above for loop
itemType := itemType
// POST /type
router.POST(fmt.Sprintf("/%s", itemType), func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
data, err := readRequestData(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
dataMutex.Lock()
// The idea with grabbing the record with ID 1 is to see if any records even exist. If none exist, the loop
// should not execute at all, giving the first record id 1
id := int64(1)
_, err = serverData.RecordWithId(itemType, id)
for id = maxIds[itemType]; err != ErrorNotFound; _, err = serverData.RecordWithId(itemType, id) {
id++
}
data["id"] = id
dirty = true
serverData.AddRecord(itemType, data)
maxIds[itemType] = id
dataMutex.Unlock()
w.WriteHeader(http.StatusCreated)
})
// GET /type
router.GET(fmt.Sprintf("/%s", itemType), func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
items, _ := serverData.ItemType(itemType)
genericJsonResponse(w, r, items)
})
// (GET,PATCH,PUT,DELETE) /type/id
for _, method := range []string{"GET", "PATCH", "PUT", "DELETE"} {
method := method
router.Handle(method, fmt.Sprintf("/%s/:id", itemType), func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
idParam, _ := strconv.ParseInt(ps.ByName("id"), 10, 64)
record, err := serverData.RecordWithId(itemType, idParam)
if err != nil {
if err == ErrorNotFound {
// If it's not found, then this request acts as a POST
if method == "PUT" {
newData, err := readRequestData(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if _, hasId := newData["id"]; !hasId {
newData["id"] = idParam
}
dataMutex.Lock()
dirty = true
serverData.AddRecord(itemType, newData)
dataMutex.Unlock()
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusNotFound)
}
} else {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
// The method type determines how we respond
switch method {
case "GET":
genericJsonResponse(w, r, record)
return
case "PATCH":
updatedData, err := readRequestData(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
dataMutex.Lock()
for key, value := range updatedData {
record[key] = value
}
dirty = true
dataMutex.Unlock()
return
case "PUT":
updatedData, err := readRequestData(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
dataMutex.Lock()
for key, _ := range record {
record[key] = nil
}
for key, value := range updatedData {
record[key] = value
}
dirty = true
dataMutex.Unlock()
w.WriteHeader(http.StatusOK)
return
case "DELETE":
dataMutex.Lock()
dirty = true
serverData.DeleteRecord(itemType, idParam)
dataMutex.Unlock()
w.WriteHeader(http.StatusOK)
return
}
})
}
}
}
// addStaticRoutes adds all routes which are present regardless of the JSON file's data. These include
//
// GET /db (returns the entire DB as a JSON structure)
//
//
func addStaticRoutes(router *httprouter.Router) {
router.GET("/db", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
genericJsonResponse(w, r, serverData)
})
}
// genericJsonResponse writes a generic JSON response and handles any errors which may occur
// when marshalling the data
//
func genericJsonResponse(w http.ResponseWriter, r *http.Request, data interface{}) {
jsonData, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// readRequestData parses the JSON body of a request
//
func readRequestData(r *http.Request) (returnData map[string]interface{}, err error) {
returnData = make(map[string]interface{})
err = decodeJson(r.Body, &returnData)
return
}