/
lost.go
45 lines (35 loc) · 1.1 KB
/
lost.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
package puppy
import (
"net/http"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
// LostAPIHandler implements REST API handler of lost service.
type LostAPIHandler struct{}
// NewLostAPIHandler creates a LostAPIHandler.
func NewLostAPIHandler() *LostAPIHandler {
return &LostAPIHandler{}
}
// HandlePostLostPuppy handles http request to lost puppy service.
func (a *LostAPIHandler) HandlePostLostPuppy(w http.ResponseWriter, r *http.Request) {
var lostPuppyRequest LostPuppyRequest
if err := render.DecodeJSON(r.Body, &lostPuppyRequest); err != nil {
sendErrorResponse(w, http.StatusBadRequest, ErrorEf(ErrInvalid, err, ""))
return
}
var responseStatus int
switch lostPuppyRequest.ID % 2 {
case 0:
responseStatus = http.StatusCreated
case 1:
responseStatus = http.StatusInternalServerError
}
time.Sleep(2 * time.Second)
w.WriteHeader(responseStatus)
render.JSON(w, r, struct{ Status int }{responseStatus})
}
// WireRoutes route requests to corresponding REST API handler method.
func (a *LostAPIHandler) WireRoutes(r chi.Router) {
r.Post("/api/lostpuppy/", a.HandlePostLostPuppy)
}