-
Notifications
You must be signed in to change notification settings - Fork 2
/
domain.go
277 lines (232 loc) · 7.19 KB
/
domain.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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// aahframework.org/router source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package router
import (
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"aahframework.org/ahttp.v0"
"aahframework.org/essentials.v0"
"aahframework.org/log.v0"
"aahframework.org/security.v0"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Domain
//___________________________________
// Domain is used to hold domain related routes and it's route configuration
type Domain struct {
IsSubDomain bool
MethodNotAllowed bool
RedirectTrailingSlash bool
AutoOptions bool
AntiCSRFEnabled bool
CORSEnabled bool
Key string
Name string
Host string
Port string
DefaultAuth string
CORS *CORS
trees map[string]*node
routes map[string]*Route
}
// Lookup method looks up route if found it returns route, path parameters,
// redirect trailing slash indicator for given `ahttp.Request` by domain
// and request URI otherwise returns nil and false.
func (d *Domain) Lookup(req *http.Request) (*Route, ahttp.PathParams, bool) {
// HTTP method override support
overrideMethod := req.Header.Get(ahttp.HeaderXHTTPMethodOverride)
if len(overrideMethod) > 0 && req.Method == ahttp.MethodPost {
req.Method = overrideMethod
}
// get route tree for request method
tree, found := d.trees[req.Method]
if !found {
// get route tree for CORS access control method
if req.Method == ahttp.MethodOptions && d.CORSEnabled {
tree, found = d.trees[req.Header.Get(ahttp.HeaderAccessControlRequestMethod)]
}
if !found {
return nil, nil, false
}
}
route, pathParams, rts, err := tree.find(req.URL.Path)
if route != nil && err == nil {
return route.(*Route), pathParams, rts
} else if rts { // possible Redirect Trailing Slash
return nil, nil, rts
}
return nil, nil, false
}
// LookupByName method returns the route for given route name otherwise nil.
func (d *Domain) LookupByName(name string) *Route {
if route, found := d.routes[name]; found {
return route
}
return nil
}
// AddRoute method adds the given route into domain routing tree.
func (d *Domain) AddRoute(route *Route) error {
if ess.IsStrEmpty(route.Method) {
return errors.New("router: method value is empty")
}
tree := d.trees[route.Method]
if tree == nil {
tree = new(node)
d.trees[route.Method] = tree
}
if err := tree.add(route.Path, route); err != nil {
return err
}
d.routes[route.Name] = route
return nil
}
// Allowed method returns the value for header `Allow` otherwise empty string.
func (d *Domain) Allowed(requestMethod, path string) (allowed string) {
if path == "*" { // server-wide
for method := range d.trees {
if method == ahttp.MethodOptions {
continue
}
// add request method to list of allowed methods
allowed = suffixCommaValue(allowed, method)
}
} else { // specific path
for method := range d.trees {
// Skip the requested method - we already tried this one
if method == requestMethod || method == ahttp.MethodOptions {
continue
}
value, _, _, _ := d.trees[method].find(path)
if value != nil {
// add request method to list of allowed methods
allowed = suffixCommaValue(allowed, method)
}
}
}
return
}
// RouteURLNamedArgs composes reverse URL by route name and key-value pair arguments.
// Additional key-value pairs composed as URL query string.
// If error occurs then method logs it and returns empty string.
func (d *Domain) RouteURLNamedArgs(routeName string, args map[string]interface{}) string {
route, found := d.routes[routeName]
if !found {
log.Errorf("route name '%v' not found", routeName)
return ""
}
argsLen := len(args)
pathParamCnt := countParams(route.Path)
if pathParamCnt == 0 && argsLen == 0 { // static URLs or no path params
return route.Path
}
if argsLen < int(pathParamCnt) { // not enough arguments suppiled
log.Errorf("not enough arguments, path: '%v' params count: %v, suppiled values count: %v",
route.Path, pathParamCnt, argsLen)
return ""
}
// compose URL with values
reverseURL := "/"
for _, segment := range strings.Split(route.Path, "/")[1:] {
if len(segment) == 0 {
continue
}
if segment[0] == paramByte || segment[0] == wildByte {
argName := segment[1:]
if arg, found := args[argName]; found {
reverseURL = path.Join(reverseURL, fmt.Sprintf("%v", arg))
delete(args, argName)
continue
}
log.Errorf("'%v' param not found in given map", segment[1:])
return ""
}
reverseURL = path.Join(reverseURL, segment)
}
// add remaining params into URL Query parameters, if any
if len(args) > 0 {
urlValues := url.Values{}
for k, v := range args {
urlValues.Add(k, fmt.Sprintf("%v", v))
}
reverseURL = fmt.Sprintf("%s?%s", reverseURL, urlValues.Encode())
}
return reverseURL
}
// RouteURL method composes route reverse URL for given route and
// arguments based on index order. If error occurs then method logs it
// and returns empty string.
func (d *Domain) RouteURL(routeName string, args ...interface{}) string {
route, found := d.routes[routeName]
if !found {
log.Errorf("route name '%v' not found", routeName)
return ""
}
argsLen := len(args)
pathParamCnt := countParams(route.Path)
if pathParamCnt == 0 && argsLen == 0 { // static URLs or no path params
return route.Path
}
// too many arguments
if argsLen > int(pathParamCnt) {
log.Errorf("too many arguments, path: '%v' params count: %v, suppiled values count: %v",
route.Path, pathParamCnt, argsLen)
return ""
}
// not enough arguments
if argsLen < int(pathParamCnt) {
log.Errorf("not enough arguments, path: '%v' params count: %v, suppiled values count: %v",
route.Path, pathParamCnt, argsLen)
return ""
}
var values []string
for _, v := range args {
values = append(values, fmt.Sprintf("%v", v))
}
// compose URL with values
reverseURL := "/"
idx := 0
for _, segment := range strings.Split(route.Path, "/") {
if len(segment) == 0 {
continue
}
if segment[0] == paramByte || segment[0] == wildByte {
reverseURL = path.Join(reverseURL, values[idx])
idx++
continue
}
reverseURL = path.Join(reverseURL, segment)
}
return reverseURL
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Domain unexpoted methods
//___________________________________
func (d *Domain) inferKey() {
if len(d.Port) == 0 {
d.Key = strings.ToLower(d.Host)
} else {
d.Key = strings.ToLower(d.Host + ":" + d.Port)
}
}
func (d *Domain) isAuthConfigured(secMgr *security.Manager) ([]string, bool) {
if !ess.IsStrEmpty(d.DefaultAuth) && secMgr.AuthScheme(d.DefaultAuth) != nil {
return []string{}, true
}
names := []string{}
for _, r := range d.routes {
if r.IsStatic || r.Auth == "anonymous" || r.Auth == "authenticated" || r.Method == "WS" {
continue
}
if r.Auth == "" {
names = append(names, r.Name)
} else if secMgr.AuthScheme(r.Auth) == nil {
names = append(names, r.Name)
}
}
return names, len(names) == 0
}