-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.go
274 lines (222 loc) · 6.28 KB
/
router.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
package waggy
import (
"context"
"fmt"
"github.com/syke99/waggy/internal/json"
"github.com/syke99/waggy/middleware"
"net/http"
"os"
"strconv"
"strings"
"github.com/syke99/waggy/internal/resources"
)
// Router is used for routing incoming HTTP requests to
// specific *Handlers by the route provided whenever you call
// Handle on the return router and provide a route for the *Handler
// you provide
type Router struct {
logger *Logger
router map[string]*Handler
handlerOrder map[int]string
noRoute WaggyError
noRouteFunc http.HandlerFunc
FullServer bool
middleWare []middleware.MiddleWare
}
// NewRouter initializes a new Router and returns a pointer
// to it
func NewRouter(cgi *FullServer) *Router {
var o bool
var err error
if cgi != nil {
o, err = strconv.ParseBool(string(*cgi))
if err != nil {
o = false
}
}
r := Router{
logger: nil,
router: make(map[string]*Handler),
handlerOrder: make(map[int]string),
noRoute: WaggyError{
Title: "Resource not found",
Detail: "route not found",
Status: 404,
Instance: "/",
},
FullServer: o,
}
return &r
}
// Handle allows you to map a *Handler for a specific route. Just
// in the popular gorilla/mux router, you can specify path parameters
// by wrapping them with {} and they can later be accessed by calling
// Vars(r)
func (wr *Router) Handle(route string, handler *Handler) *Router {
handler.route = route
handler.inheritLogger(wr.logger)
handler.inheritFullServerFlag(wr.FullServer)
wr.router[route] = handler
wr.handlerOrder[len(wr.router)] = route
return wr
}
// Routes returns all the routes that a *Router has
// *Handlers set for in the order that they were added
func (wr *Router) Routes() []string {
r := make([]string, 0)
for i := 0; i <= len(wr.router); i++ {
r = append(r, wr.handlerOrder[i])
}
return r
}
// WithLogger allows you to set a Logger for the entire router. Whenever
// Handle is called, this logger will be passed to the *Handler
// being handled for the given route.
func (wr *Router) WithLogger(logger *Logger) *Router {
wr.logger = logger
return wr
}
// WithDefaultLogger sets wr's logger to the default Logger
func (wr *Router) WithDefaultLogger() *Router {
l := Logger{
logLevel: Info.level(),
key: "",
message: "",
err: "",
vals: make(map[string]interface{}),
log: os.Stderr,
}
wr.logger = &l
return wr
}
// WithNoRouteHandler allows you to set an http.HandlerFunc to be used whenever
// no route is found. If this method is not called and the ServeHTTP method
// has been called, then it will return a generic 404 response, instead
func (wr *Router) WithNoRouteHandler(fn http.HandlerFunc) *Router {
wr.noRouteFunc = fn
return wr
}
// Logger returns the Router's logger
func (wr *Router) Logger() *Logger {
return wr.logger
}
// Use allows you to set Middleware http.Handlers for a *Router
func (wr *Router) Use(middleWare ...middleware.MiddleWare) {
for _, mw := range middleWare {
wr.middleWare = append(wr.middleWare, mw)
}
}
func (wr *Router) Middleware() []middleware.MiddleWare {
return wr.middleWare
}
// ServeHTTP satisfies the http.Handler interface and calls the stored
// handler at the route of the incoming HTTP request
func (wr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rt := ""
r.URL.Opaque = ""
rRoute := r.URL.Path
var handler *Handler
var ok bool
if rRoute == "" || rRoute == "/" {
if handler, ok = wr.router["/"]; !ok {
w.WriteHeader(http.StatusMethodNotAllowed)
wr.noRouteResponse(w, r)
return
} else {
ctx := context.WithValue(r.Context(), resources.RootRoute, true)
r = r.Clone(ctx)
}
}
if handler == nil {
var key string
var h *Handler
for key, h = range wr.router {
if key == "/" {
continue
}
if rRoute[:1] == "/" {
rRoute = rRoute[1:]
}
splitRoute := strings.Split(rRoute, "/")
if key[:1] == "/" {
key = key[1:]
}
splitKey := strings.Split(key, "/")
for i, section := range splitKey {
if len(section) == 0 {
continue
}
beginning := section[:1]
end := section[len(section)-1:]
// check if this section is a query param
if (beginning == "{" &&
end == "}") && (len(splitRoute) != len(splitKey)) {
continue
}
if (beginning == "{" &&
end == "}") && (len(splitRoute) == len(splitKey)) {
rt = key
}
// if the route sections don't match and aren't query
// params, break out as these are not the correctly matched
// routes
if i > len(splitRoute) || splitRoute[i] != section && rt == "" {
break
}
if len(splitKey) > len(splitRoute) &&
i == len(splitRoute) &&
rt == "" {
rt = key
}
// if the end of splitRoute is reached, and we haven't
// broken out of the loop to move on to the next route,
// then the routes match
if (i == len(splitKey)-1 || i == len(splitRoute)) &&
rt == "" {
rt = key
}
}
if rt != "" {
ctx := context.WithValue(r.Context(), resources.MatchedRoute, rRoute)
r = r.Clone(ctx)
handler = h
}
}
if handler == nil {
wr.noRouteResponse(w, r)
}
}
handler.ServeHTTP(w, r)
return
}
func (wr *Router) noRouteResponse(w http.ResponseWriter, r *http.Request) {
if wr.noRouteFunc != nil {
wr.noRouteFunc(w, r)
return
}
w.WriteHeader(http.StatusNotFound)
w.Header().Set("Content-Type", "application/problem+json")
fmt.Fprintln(w, json.BuildJSONStringFromWaggyError(wr.noRoute.Type, wr.noRoute.Title, wr.noRoute.Detail, wr.noRoute.Status, wr.noRoute.Instance, wr.noRoute.Field))
}
// Walk accepts a *Router and a walkFunc to execute on each route that has been
// added to the *Router. It walks the *Router in the order that each
// *Handler was added to the *Router with *Router.Handle(). It returns the first
// error encountered
func (wr *Router) Walk(walkFunc func(method string, route string) error) error {
for i := 1; i <= len(wr.router); i++ {
route, _ := wr.handlerOrder[i]
handler := wr.router[route]
if err := walkMethods(route, handler, walkFunc); err != nil {
return err
}
}
return nil
}
func walkMethods(route string, handler *Handler, walkFunc func(method string, route string) error) error {
for _, method := range handler.Methods() {
if err := walkFunc(method, route); err != nil {
return err
}
}
return nil
}