-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
182 lines (157 loc) · 4.58 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
package controller
import (
"context"
"log"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/sotoz/ferrytale/entities"
)
// ErrResponse defines a struct for the error responses.
type ErrResponse struct {
Err error `json:"-"` // low-level runtime error
HTTPStatusCode int `json:"-"` // http response status code
StatusText string `json:"status"` // user-level status message
AppCode int64 `json:"code,omitempty"` // application-specific error code
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
}
var pageCtxKey string
type pageOpts struct {
Page int
Limit int
}
func paginate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var page, limit int
var err error
pageParam := r.URL.Query().Get("page")
limitParam := r.URL.Query().Get("limit")
if pageParam == "" {
page = 1
} else {
page, err = strconv.Atoi(pageParam)
if err != nil {
render.Status(r, http.StatusBadRequest)
log.Print(err)
}
}
if limitParam == "" {
limit = 1
} else {
limit, err = strconv.Atoi(limitParam)
if err != nil {
render.Status(r, http.StatusBadRequest)
}
}
ctx := context.WithValue(r.Context(), pageCtxKey, &pageOpts{
Page: page,
Limit: limit,
})
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func listDocks(w http.ResponseWriter, r *http.Request) {
if err := render.RenderList(w, r, NewDocksListResponse(entities.Docks)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
func listFerries(w http.ResponseWriter, r *http.Request) {
pgOpts := r.Context().Value(pageCtxKey).(*pageOpts)
log.Print("Fetching Ferries")
ferries, err := entities.GetFerries(pgOpts.Page, pgOpts.Limit)
if err != nil {
log.Printf("error: %s", err)
}
if err := render.RenderList(w, r, NewFerriesListResponse(ferries)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
func listLines(w http.ResponseWriter, r *http.Request) {
pgOpts := r.Context().Value(pageCtxKey).(*pageOpts)
log.Print("Fetching Lines")
lines, err := entities.GetLines(pgOpts.Page, pgOpts.Limit)
if err != nil {
log.Printf("error: %s", err)
}
if err := render.RenderList(w, r, NewLinesListResponse(lines)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
func listRoutes(w http.ResponseWriter, r *http.Request) {
log.Print("Fetching Routes")
line := r.Context().Value("line").(*entities.Line)
routes, err := entities.GetRoutes(line.ID)
if err != nil {
log.Printf("error: %s", err)
}
if err := render.RenderList(w, r, NewRoutesListResponse(routes)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
func nextDeparture(w http.ResponseWriter, r *http.Request) {
log.Print("Getting next departure")
line := r.Context().Value("line").(*entities.Line)
t, n, err := entities.CalculateNextDeparture(line.ID)
if err != nil {
log.Printf("error: %s", err)
}
if err := render.Render(w, r, NewNextDepartureResponse(t, n)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
// Router is the default controller that has the routes for the application.
func Router() http.Handler {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Set a timeout value on the request context (ctx), that will signal
// through ctx.Done() that the request has timed out and further
// processing should be stopped.
r.Use(middleware.Timeout(60 * time.Second))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome to Amsterdam's Ferries webservice."))
})
r.Route("/docks", func(r chi.Router) {
r.With(paginate).Get("/", listDocks)
})
r.Route("/ferries", func(r chi.Router) {
r.With(paginate).Get("/", listFerries)
})
r.Route("/lines", func(r chi.Router) {
r.With(paginate).Get("/", listLines)
r.Route("/{lineID}", func(r chi.Router) {
r.Use(LineCtx)
r.Get("/", listRoutes)
r.Get("/nextdeparture", nextDeparture)
})
})
return r
}
// LineCtx
func LineCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lineID := chi.URLParam(r, "lineID")
if lineID == "" {
http.Error(w, http.StatusText(400), 400)
return
}
line, err := entities.GetLine(lineID)
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
log.Printf("from %s to %s", line.From, line.To)
ctx := context.WithValue(r.Context(), "line", line)
next.ServeHTTP(w, r.WithContext(ctx))
})
}