/
router.go
337 lines (286 loc) · 10.4 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// aahframework.org/aah source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package aah
import (
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"aahframework.org/ahttp.v0"
"aahframework.org/essentials.v0"
"aahframework.org/log.v0"
"aahframework.org/router.v0"
"aahframework.org/valpar.v0"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Package methods
//______________________________________________________________________________
// RouteMiddleware method performs the routing logic.
func RouteMiddleware(ctx *Context, m *Middleware) {
if handleRoute(ctx) == flowAbort {
return
}
m.Next(ctx)
}
// CORSMiddleware provides Cross-Origin Resource Sharing (CORS) access
// control feature.
func CORSMiddleware(ctx *Context, m *Middleware) {
// If CORS not enabled or nil move on
if !ctx.domain.CORSEnabled || ctx.route.CORS == nil {
m.Next(ctx)
return
}
// Always add Vary for header Origin
ctx.Reply().HeaderAppend(ahttp.HeaderVary, ahttp.HeaderOrigin)
// CORS OPTIONS request
if ctx.Req.Method == ahttp.MethodOptions &&
ctx.Req.Header.Get(ahttp.HeaderAccessControlRequestMethod) != "" {
handleCORSPreflight(ctx)
return
}
// CORS headers
cors := ctx.route.CORS
origin := ctx.Req.Header.Get(ahttp.HeaderOrigin)
if cors.IsOriginAllowed(origin) {
ctx.Reply().Header(ahttp.HeaderAccessControlAllowOrigin, origin)
}
if len(cors.ExposeHeaders) > 0 {
ctx.Reply().Header(ahttp.HeaderAccessControlExposeHeaders, strings.Join(cors.ExposeHeaders, ", "))
} else if len(cors.AllowHeaders) > 0 {
ctx.Reply().Header(ahttp.HeaderAccessControlExposeHeaders, strings.Join(cors.AllowHeaders, ", "))
}
if cors.AllowCredentials {
ctx.Reply().Header(ahttp.HeaderAccessControlAllowCredentials, "true")
}
m.Next(ctx)
}
func handleCORSPreflight(ctx *Context) {
ctx.Log().Infof("CORS: preflight request - Path[%v]", ctx.Req.Path)
ctx.Reply().
HeaderAppend(ahttp.HeaderVary, ahttp.HeaderAccessControlRequestMethod).
HeaderAppend(ahttp.HeaderVary, ahttp.HeaderAccessControlRequestHeaders)
cors := ctx.route.CORS
// Check Origin
origin := ctx.Req.Header.Get(ahttp.HeaderOrigin)
if cors.IsOriginAllowed(origin) {
ctx.Reply().Header(ahttp.HeaderAccessControlAllowOrigin, origin)
} else {
ctx.Log().Warnf("CORS: preflight request - invalid origin '%s' for %s %s",
origin, ctx.Req.Method, ctx.Req.Path)
ctx.Reply().BadRequest().Error(newError(router.ErrCORSOriginIsInvalid, http.StatusBadRequest))
return
}
// Check Method
method := ctx.Req.Header.Get(ahttp.HeaderAccessControlRequestMethod)
if cors.IsMethodAllowed(method) {
ctx.Reply().Header(ahttp.HeaderAccessControlAllowMethods, strings.Join(cors.AllowMethods, ", "))
} else {
ctx.Log().Warnf("CORS: preflight request - method not allowed '%s' for path %s",
method, ctx.Req.Path)
ctx.Reply().MethodNotAllowed().Error(newError(router.ErrCORSMethodNotAllowed, http.StatusMethodNotAllowed))
return
}
// Check Headers
hdrs := ctx.Req.Header.Get(ahttp.HeaderAccessControlRequestHeaders)
if cors.IsHeadersAllowed(hdrs) {
if len(cors.AllowHeaders) > 0 {
ctx.Reply().Header(ahttp.HeaderAccessControlAllowHeaders, strings.Join(cors.AllowHeaders, ", "))
}
} else {
ctx.Log().Warnf("CORS: preflight request - headers not allowed '%s' for path %s",
hdrs, ctx.Req.Path)
ctx.Reply().Forbidden().Error(newError(router.ErrCORSHeaderNotAllowed, http.StatusForbidden))
return
}
if cors.AllowCredentials {
ctx.Reply().Header(ahttp.HeaderAccessControlAllowCredentials, "true")
}
if !ess.IsStrEmpty(cors.MaxAge) {
ctx.Reply().Header(ahttp.HeaderAccessControlMaxAge, cors.MaxAge)
}
ctx.Reply().Ok().Text("")
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// app methods
//______________________________________________________________________________
func (a *app) Router() *router.Router {
return a.router
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// app Unexported methods
//______________________________________________________________________________
func (a *app) initRouter() error {
rtr, err := router.NewWithApp(a,
path.Join(a.VirtualBaseDir(), "config", "routes.conf"))
if err != nil {
return fmt.Errorf("routes.conf: %s", err)
}
a.router = rtr
return nil
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Unexported methods
//______________________________________________________________________________
// handleRoute method handle route processing for the incoming request.
// It does-
// - finding domain
// - finding route
// - handling static route
// - handling redirect trailing slash
// - auto options
// - route not found
// - if route found then it sets targeted controller into context
// - adds the pathParams into context if present
//
// Returns status as-
// - flowCont
// - flowStop
func handleRoute(ctx *Context) flowResult {
domain := ctx.a.Router().Lookup(ctx.Req.Host)
if domain == nil {
ctx.Log().Warnf("Domain not found, Host: %s, Path: %s", ctx.Req.Host, ctx.Req.Path)
ctx.Reply().NotFound().Error(newError(ErrDomainNotFound, http.StatusNotFound))
return flowAbort
}
ctx.domain = domain
route, pathParams, rts := domain.Lookup(ctx.Req.Unwrap())
if route == nil { // route not found
if err := handleRtsOptionsMna(ctx, domain, rts); err == nil {
return flowAbort
}
ctx.Log().Warnf("Route not found, Host: %s, Path: %s", ctx.Req.Host, ctx.Req.Path)
ctx.Reply().NotFound().Error(newError(ErrRouteNotFound, http.StatusNotFound))
return flowAbort
}
ctx.route = route
ctx.Req.PathParams = pathParams
// Serving static file
if route.IsStatic {
if err := ctx.a.staticMgr.Serve(ctx); err == errFileNotFound {
ctx.Log().Warnf("Static file not found, Host: %s, Path: %s", ctx.Req.Host, ctx.Req.Path)
ctx.Reply().done = false
ctx.Reply().NotFound().Error(newError(ErrStaticFileNotFound, http.StatusNotFound))
}
return flowAbort
}
// Apply route constraints
if errs := valpar.ValidateValues(ctx.Req.PathParams, ctx.route.Constraints); len(errs) > 0 {
ctx.Log().Errorf("Route constraints failed: %s", errs)
ctx.Reply().BadRequest().Error(newErrorWithData(router.ErrRouteConstraintFailed, http.StatusBadRequest, errs))
return flowAbort
}
return flowCont
}
func appendAnchorLink(routePath, anchorLink string) string {
if ess.IsStrEmpty(anchorLink) {
return routePath
}
return routePath + "#" + anchorLink
}
func getRouteNameAndAnchorLink(routeName string) (string, string) {
anchorLink := ""
hashIdx := strings.IndexByte(routeName, '#')
if hashIdx > 0 {
anchorLink = routeName[hashIdx+1:]
routeName = routeName[:hashIdx]
}
return routeName, anchorLink
}
func composeRouteURL(domain *router.Domain, routePath, anchorLink string) string {
if ess.IsStrEmpty(domain.Port) {
routePath = fmt.Sprintf("//%s%s", domain.Host, routePath)
} else {
routePath = fmt.Sprintf("//%s:%s%s", domain.Host, domain.Port, routePath)
}
return appendAnchorLink(routePath, anchorLink)
}
func (a *app) findRouteURLDomain(host, routeName string) (*router.Domain, string) {
idx := strings.IndexByte(routeName, '.')
if idx > 0 {
subDomain := routeName[:idx]
// Returning current subdomain
if strings.HasPrefix(host, subDomain) {
return a.Router().Lookup(host), routeName[idx+1:]
}
// Returning requested subdomain
for k, v := range a.Router().Domains {
if strings.HasPrefix(k, subDomain) && v.IsSubDomain {
return v, routeName[idx+1:]
}
}
}
// return root domain
return a.Router().RootDomain(), routeName
}
func createRouteURL(l log.Loggerer, domain *router.Domain, routeName string, margs map[string]interface{}, args ...interface{}) string {
if routeName == "host" {
return composeRouteURL(domain, "", "")
}
routeName, anchorLink := getRouteNameAndAnchorLink(routeName)
var routePath string
if margs == nil {
routePath = domain.RouteURL(routeName, args...)
} else {
routePath = domain.RouteURLNamedArgs(routeName, margs)
}
// URL escapes
rURL, err := url.Parse(composeRouteURL(domain, routePath, anchorLink))
if err != nil {
l.Error(err)
return ""
}
return rURL.String()
}
// handleRtsOptionsMna method handles 1) Redirect Trailing Slash 2) Options
// 3) Method not allowed
func handleRtsOptionsMna(ctx *Context, domain *router.Domain, rts bool) error {
reqMethod := ctx.Req.Method
reqPath := ctx.Req.Path
reply := ctx.Reply()
// Redirect Trailing Slash
if reqMethod != ahttp.MethodConnect && reqPath != router.SlashString {
if rts && domain.RedirectTrailingSlash {
reply.MovedPermanently()
if reqMethod != ahttp.MethodGet {
reply.TemporaryRedirect()
}
if len(reqPath) > 1 && reqPath[len(reqPath)-1] == '/' {
ctx.Req.URL().Path = reqPath[:len(reqPath)-1]
} else {
ctx.Req.URL().Path = reqPath + "/"
}
reply.Redirect(ctx.Req.URL().String())
ctx.Log().Debugf("RedirectTrailingSlash: %d, %s ==> %s", reply.Code, reqPath, reply.path)
return nil
}
}
// HTTP: OPTIONS
if reqMethod == ahttp.MethodOptions {
if domain.AutoOptions {
if processAllowedMethods(reply, domain.Allowed(reqMethod, reqPath), "Auto 'OPTIONS', ") {
ctx.Reply().Text("")
return nil
}
}
}
// 405 Method Not Allowed
if domain.MethodNotAllowed {
if processAllowedMethods(reply, domain.Allowed(reqMethod, reqPath), "405 response, ") {
ctx.Reply().MethodNotAllowed().Error(newError(ErrHTTPMethodNotAllowed, http.StatusMethodNotAllowed))
return nil
}
}
return errors.New("route not found")
}
func processAllowedMethods(reply *Reply, allowed, prefix string) bool {
if !ess.IsStrEmpty(allowed) {
allowed += ", " + ahttp.MethodOptions
reply.Header(ahttp.HeaderAllow, allowed)
reply.ctx.Log().Debugf("%sAllowed HTTP Methods: %s", prefix, allowed)
return true
}
return false
}