-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
465 lines (400 loc) · 13.2 KB
/
controller.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package krud
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
// NOTE: Would probably have been much easier to have "AllowedUser" as
// a normal method on the DB and then use a single *sql.DB across
// all connections. A middleware could ensure that each request is checked.
// Now its part of the creation of a handle to the underlying db layer.
// Although this approach has the upside of tying together the user performing queries!
// Databaser should have a better name.
type Databaser interface {
AddAuthor(ctx context.Context, author Author) (id int64, err error)
GetAuthor(ctx context.Context, id int64) (author *Author, err error)
UpdateAuthor(ctx context.Context, author Author) (err error)
AllAuthors(ctx context.Context) (authors []Author, err error)
DeleteAuthor(ctx context.Context, id int64) (err error)
AddBook(ctx context.Context, author int64, book Book) (id int64, err error)
GetBook(ctx context.Context, authorID, bookID int64) (book *Book, err error)
UpdateBook(ctx context.Context, authorID int64, book Book) (err error)
AllBooks(ctx context.Context) (books []Book, err error)
DeleteBook(ctx context.Context, authorID, bookID int64) (err error)
QueryEvents(ctx context.Context, filters ...Filter) (events []Event, err error)
}
// Dialer lets us setup and API that does not have to know what kind of Database is used.
// Enabled injecting a mock when testing.
type Dialer interface {
Dial(context.Context, string) (Databaser, error)
}
type DialFunc func(context.Context, string) (Databaser, error)
func (df DialFunc) Dial(ctx context.Context, user string) (Databaser, error) {
return df(ctx, user)
}
// Controller wires up the endpoints.
type Controller struct {
// dial is used to create handles to some Databaser.
dial Dialer
// log is an injected logger.
log *log.Logger
}
type contextKrudDatabaser struct{}
// NewController adds endpoints under r and hooks them up to the resources behind dial.
func NewController(log *log.Logger, r *mux.Router, dial Dialer) *Controller {
c := Controller{
dial: dial,
log: log,
}
// Make sure any request is from an approved user.
r.Use(c.AuthMiddleware)
r.HandleFunc("/authors", c.CreateAuthor).Methods(http.MethodPost)
r.HandleFunc("/authors", c.ReadAuthor).Methods(http.MethodGet) // Two get routes for w/ and w/o id.
r.HandleFunc("/authors/{authorID:[0-9]+}", c.ReadAuthor).Methods(http.MethodGet)
r.HandleFunc("/authors/{authorID:[0-9]+}", c.UpdateAuthor).Methods(http.MethodPatch)
r.HandleFunc("/authors/{authorID:[0-9]+}", c.DeleteAuthor).Methods(http.MethodDelete)
r.HandleFunc("/authors/{authorID:[0-9]+}/books", c.CreateBook).Methods(http.MethodPost)
r.HandleFunc("/authors/{authorID:[0-9]+}/books", c.ReadBook).Methods(http.MethodGet) // Two get routes for w/ and w/o id.
r.HandleFunc("/authors/{authorID:[0-9]+}/books/{bookID:[0-9]+}", c.ReadBook).Methods(http.MethodGet)
r.HandleFunc("/authors/{authorID:[0-9]+}/books/{bookID:[0-9]+}", c.UpdateBook).Methods(http.MethodPatch)
r.HandleFunc("/authors/{authorID:[0-9]+}/books/{bookID:[0-9]+}", c.DeleteBook).Methods(http.MethodDelete)
r.HandleFunc("/events", c.Events).Methods(http.MethodPost)
return &c
}
func (api Controller) AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Even more basic than r.BasicAuth()...
user := r.Header.Get("user")
// Needs to create DB for this user...
db, err := api.dial.Dial(r.Context(), user)
if err != nil {
api.log.Infof("auth rejected '%s' (%s) access to %s", user, r.RemoteAddr, r.RequestURI)
http.Error(w, "specify approved user in header", http.StatusUnauthorized)
return
}
api.log.Infof("auth approved '%s' (%s) access to %s", user, r.RemoteAddr, r.RequestURI)
// Propagate db decorated for this approved user.
ctx := context.WithValue(r.Context(), contextKrudDatabaser{}, db)
rr := r.WithContext(ctx)
next.ServeHTTP(w, rr)
})
}
// WriteJsonError pack cause in a json body of http response with code set in header.
func WriteJsonError(w http.ResponseWriter, cause error, code int) {
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
// Use anonymous struct to put error string a json.
err := enc.Encode(struct {
Error string `json:"error"`
}{Error: cause.Error()})
if err != nil {
// FIXME: What is the fallback error handling?
return
}
}
func WriteJson(w http.ResponseWriter, item interface{}, code int) {
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
err := enc.Encode(item)
if err != nil {
// FIXME: What is the fallback error handling?
return
}
}
func (api *Controller) CreateAuthor(w http.ResponseWriter, r *http.Request) {
author := Author{}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err := dec.Decode(&author)
if err != nil {
WriteJsonError(w, fmt.Errorf("json decode body: %w", err), http.StatusBadRequest)
return
}
err = author.Validate()
if err != nil {
WriteJsonError(w, err, http.StatusBadRequest)
return
}
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
author.ID, err = db.AddAuthor(r.Context(), author)
if err != nil {
WriteJson(w, err, http.StatusInternalServerError)
return
}
WriteJson(w, author, http.StatusCreated)
}
func (api *Controller) ReadAuthor(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
if _, ok := mux.Vars(r)["authorID"]; ok { // List specific
id, err := GetIntFromRequest(r, "authorID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
author, err := db.GetAuthor(r.Context(), int64(id))
if err != nil {
if errors.Is(err, ErrDoesNotExist) {
WriteJsonError(w, err, http.StatusNotFound)
return
}
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
WriteJson(w, author, http.StatusOK)
} else { // List all
authors, err := db.AllAuthors(r.Context())
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
// Always return some json.
if authors == nil {
authors = []Author{}
}
WriteJson(w, authors, http.StatusOK)
}
}
func (api *Controller) DeleteAuthor(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
id, err := GetIntFromRequest(r, "authorID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
err = db.DeleteAuthor(r.Context(), int64(id))
if err != nil {
if errors.Is(err, ErrDoesNotExist) {
WriteJsonError(w, err, http.StatusNotFound)
return
}
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
// Should we return repr of deleted resource?
w.WriteHeader(http.StatusNoContent)
}
func (api *Controller) UpdateAuthor(w http.ResponseWriter, r *http.Request) {
id, err := GetIntFromRequest(r, "authorID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
// This is a hack because of limited HTTP and database APIs.
// DB update is all or nothing, so write request changes onto existing record.
author, err := db.GetAuthor(r.Context(), int64(id))
if err != nil {
if errors.Is(err, ErrDoesNotExist) {
WriteJsonError(w, err, http.StatusNotFound)
return
}
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
// Hack #2, use anon struct to the request cannot contain som ID conflicting with the URL.
changes := struct {
Name string `json:"name"`
DateOfBirth Date `json:"dateofbirth"`
}{}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err = dec.Decode(&changes)
if err != nil {
WriteJsonError(w, fmt.Errorf("json decode body: %w", err), http.StatusBadRequest)
return
}
// Only override fields which are in the request.
if changes.Name != "" {
author.Name = changes.Name
}
if !time.Time(changes.DateOfBirth).IsZero() {
author.DateOfBirth = changes.DateOfBirth
}
// This is a bit brittle. We block changes if the author is invalid, but this author is
// a combination of the request and current state. If the invalid-ness comes from state
// (after something like a policy change or schema migration) we cannot fix anything through
// the api.
err = author.Validate()
if err != nil {
WriteJsonError(w, err, http.StatusBadRequest)
return
}
err = db.UpdateAuthor(r.Context(), *author)
if err != nil {
if errors.Is(err, ErrDoesNotExist) {
WriteJsonError(w, err, http.StatusNotFound)
return
}
WriteJson(w, err, http.StatusInternalServerError)
return
}
WriteJson(w, author, http.StatusOK)
}
func GetIntFromRequest(r *http.Request, key string) (int, error) {
vars := mux.Vars(r)
id, ok := vars[key]
if !ok {
return 0, fmt.Errorf("handler did not populate: %s", key)
}
return strconv.Atoi(id)
}
func (api *Controller) CreateBook(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
authorID, err := GetIntFromRequest(r, "authorID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
book := Book{}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err = dec.Decode(&book)
if err != nil {
WriteJsonError(w, fmt.Errorf("json decode body: %w", err), http.StatusBadRequest)
return
}
err = book.Validate()
if err != nil {
WriteJsonError(w, err, http.StatusBadRequest)
return
}
book.ID, err = db.AddBook(r.Context(), int64(authorID), book)
if err != nil {
WriteJson(w, err, http.StatusInternalServerError)
return
}
WriteJson(w, book, http.StatusCreated)
}
func (api *Controller) ReadBook(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
authorID, err := GetIntFromRequest(r, "authorID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
}
if _, ok := mux.Vars(r)["bookID"]; ok { // List specific
bookID, err := GetIntFromRequest(r, "bookID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
book, err := db.GetBook(r.Context(), int64(authorID), int64(bookID))
if err != nil {
if errors.Is(err, ErrDoesNotExist) {
WriteJsonError(w, err, http.StatusNotFound)
return
}
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
WriteJson(w, book, http.StatusOK)
} else { // List all
books, err := db.AllBooks(r.Context())
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
// Always return some json.
if books == nil {
books = []Book{}
}
WriteJson(w, books, http.StatusOK)
}
}
func (api *Controller) UpdateBook(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}
func (api *Controller) DeleteBook(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
authorID, err := GetIntFromRequest(r, "authorID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
bookID, err := GetIntFromRequest(r, "bookID")
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
}
err = db.DeleteBook(r.Context(), int64(authorID), int64(bookID))
if err != nil {
if errors.Is(err, ErrDoesNotExist) {
WriteJsonError(w, err, http.StatusNotFound)
return
}
WriteJsonError(w, err, http.StatusInternalServerError)
return
}
// Should we return repr of deleted resource?
w.WriteHeader(http.StatusNoContent)
}
func (api *Controller) Events(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value(contextKrudDatabaser{}).(Databaser)
if !ok {
WriteJson(w, errors.New("internal error"), http.StatusInternalServerError)
return
}
filters := []Filter{}
queries := struct {
Before time.Time `json:"before"`
After time.Time `json:"after"`
}{}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err := dec.Decode(&queries)
if err == io.EOF {
// Indicates no body, i.e. no filters, skip ahead.
} else if err != nil {
WriteJsonError(w, err, http.StatusBadRequest)
return
} else {
if !queries.Before.IsZero() {
filters = append(filters, EventsBefore(queries.Before))
}
if !queries.After.IsZero() {
filters = append(filters, EventsAfter(queries.After))
}
}
events, err := db.QueryEvents(r.Context(), filters...)
if err != nil {
WriteJsonError(w, err, http.StatusInternalServerError)
}
WriteJson(w, events, http.StatusOK)
}