forked from trussworks/go-sample-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdogs.go
58 lines (49 loc) · 1.21 KB
/
dogs.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
package handlers
import (
"context"
"encoding/json"
"net/http"
"bin/bork/pkg/apperrors"
"bin/bork/pkg/models"
)
type fetchDogs func(ctx context.Context) (*models.Dogs, error)
// NewDogsHandler is a constructor for a DogHandler
func NewDogsHandler(base HandlerBase, fetch fetchDogs) DogsHandler {
return DogsHandler{
HandlerBase: base,
fetchDogs: fetch,
}
}
// DogsHandler is the handler for API operations on dog lists
type DogsHandler struct {
HandlerBase
fetchDogs fetchDogs
}
// Handle handles a request for a dog
func (h DogsHandler) Handle() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
dogs, err := h.fetchDogs(r.Context())
if err != nil {
h.WriteErrorResponse(r.Context(), w, err)
return
}
responseBody, err := json.Marshal(dogs)
if err != nil {
h.WriteErrorResponse(r.Context(), w, err)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(responseBody)
if err != nil {
h.WriteErrorResponse(r.Context(), w, err)
return
}
return
default:
h.WriteErrorResponse(r.Context(), w, &apperrors.MethodNotAllowedError{Method: r.Method})
return
}
}
}