-
Notifications
You must be signed in to change notification settings - Fork 12
/
framework.go
88 lines (78 loc) · 2.55 KB
/
framework.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
package gimlet
import (
"context"
"net/http"
"net/url"
"github.com/mongodb/grip"
"github.com/mongodb/grip/message"
)
// RouteHandler provides an alternate method for defining routes with
// the goals of separating the core operations of handling a rest result.
type RouteHandler interface {
// Factory produces, this makes it possible for you to store
// request-scoped data in the implementation of the Handler
// rather than attaching data to the context. The factory
// allows gimlet to, internally, reconstruct a handler interface
// for every request.
//
// Factory is always called at the beginning of the request.
Factory() RouteHandler
// Parse makes it possible to modify the request context and
// populate the implementation of the RouteHandler. This also
// allows you to isolate your interaction with the request
// object.
Parse(context.Context, *http.Request) error
// Runs the core buinsess logic for the route, returning a
// Responder interface to provide structure around returning
//
// Run methods do not return an error. Implementors are
// responsible for forming a response, even in error cases.
Run(context.Context) Responder
}
// handleHandler converts a RouteHandler implementation into a
// standard go http.HandlerFunc.
func handleHandler(h RouteHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
handler := h.Factory()
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
if err := handler.Parse(ctx, r); err != nil {
WriteResponse(w, newResponder(err, http.StatusBadRequest, JSON))
return
}
resp := handler.Run(ctx)
if resp == nil {
e := ErrorResponse{
StatusCode: http.StatusInternalServerError,
Message: "undefined response",
}
WriteJSONResponse(w, e.StatusCode, e)
return
}
if err := resp.Validate(); err != nil {
WriteResponse(w, newResponder(err, http.StatusBadRequest, JSON))
return
}
// if this response is paginated, add the appropriate metadata.
if resp.Pages() != nil {
routeURL := url.URL{Path: r.URL.Path, RawQuery: r.URL.RawQuery}
w.Header().Set("Link", resp.Pages().GetLinks(routeURL.String()))
}
if resp.Status() >= http.StatusInternalServerError {
m := message.Fields{
"message": "request encountered internal error",
"method": r.Method,
"remote": r.RemoteAddr,
"request": GetRequestID(ctx),
"path": r.URL.Path,
"status": resp.Status(),
"error": resp.Data(),
}
if len(r.URL.Query()) > 0 {
m["params"] = r.URL.Query()
}
grip.Debug(m)
}
WriteResponse(w, resp)
}
}