-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
176 lines (148 loc) · 4.54 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
package potato
import (
ws "code.google.com/p/go.net/websocket"
"net/http"
"reflect"
"regexp"
"strings"
)
const (
CodeTerminate = 0
)
var (
ErrorRouteName string
NotfoundRouteName string
)
type Route struct {
Name string `yaml:"name"`
Controller string `yaml:"controller"`
Action string `yaml:"action"`
Pattern string `yaml:"pattern"`
Keys []string `yaml:"keys"`
Regexp *regexp.Regexp
}
/**
* routes are grouped by their prefixes
* when routing a url, first match the prefixes
* then match the patterns of each route
*/
type PrefixedRoutes struct {
Prefix string `yaml:"prefix"`
Regexp *regexp.Regexp
Routes []*Route `yaml:"routes"`
}
type Router struct {
Event
ws ws.Server
routes []*PrefixedRoutes
errorRoute *Route
notfoundRoute *Route
controllers map[string]reflect.Type
}
func NewRouter() *Router {
return &Router{
Event: Event{make(map[string][]EventHandler)},
ws: ws.Server{},
controllers: make(map[string]reflect.Type),
errorRoute : &Route{},
notfoundRoute: &Route{},
}
}
/**
* Controllers register controllers on router
*/
func (rt *Router) SetControllers(cs map[string]interface{}) {
for n, c := range cs {
elem := reflect.Indirect(reflect.ValueOf(c))
//Controller must embeded from potato.Controller
if elem.FieldByName("Controller").CanSet() {
rt.controllers[n] = elem.Type()
}
}
}
func (rt *Router) LoadRouteConfig(filename string) {
if e := LoadYaml(&rt.routes, filename); e != nil {
L.Fatal(e)
}
for _, pr := range rt.routes {
//prepare regexps for prefixed routes
pr.Regexp = regexp.MustCompile("^" + pr.Prefix + "(.*)$")
for _, r := range pr.Routes {
r.Regexp = regexp.MustCompile("^" + r.Pattern + "$")
if r.Name == ErrorRouteName {
rt.errorRoute = r
}
if r.Name == NotfoundRouteName {
rt.notfoundRoute = r
}
}
}
}
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
route, params := rt.route(r.URL.Path)
request := NewRequest(r, params)
if strings.ToLower(r.Header.Get("Upgrade")) == "websocket" {
if conn := rt.ws.Conn(w, r); conn != nil {
request.WSConn = conn
defer conn.Close()
}
}
response := &Response{ResponseWriter: w}
InitSession(request, response)
rt.TriggerEvent("request_start", request, response)
rt.dispatch(route, request, response)
rt.TriggerEvent("request_end", request, response)
}
func (rt *Router) route(path string) (*Route, map[string]string) {
//case insensitive
//make sure the patterns in routes.yml is lower case too
path = strings.ToLower(path)
//check prefixes
for _, pr := range rt.routes {
if m := pr.Regexp.FindStringSubmatch(path); len(m) == 2 {
//check routes on matched prefix
for _, r := range pr.Routes {
if p := r.Regexp.FindStringSubmatch(m[1]); len(p) > 0 {
//get params for matched route
params := make(map[string]string, len(p)-1)
for i, v := range p[1:] {
params[r.Keys[i]] = v
}
return r, params
}
}
}
}
return rt.notfoundRoute, make(map[string]string)
}
func (rt *Router) dispatch(route *Route, r *Request, p *Response) {
defer func() {
if e := recover(); e != nil {
if code, ok := e.(int); ok && code == CodeTerminate {
return
}
r.Bag.Set("error", e, true)
rt.run(rt.errorRoute, r, p)
L.Println(e)
}
}()
rt.run(route, r, p)
}
func (rt *Router) run(route *Route, r *Request, p *Response) {
if t, has := rt.controllers[route.Controller]; has {
c := NewController(t, r, p)
rt.TriggerEvent("controller_start", c, r, p)
if action := c.MethodByName(route.Action); action.IsValid() {
//if controller has Init method, run it first
if init := c.MethodByName("Init"); init.IsValid() {
init.Call(nil)
}
rt.TriggerEvent("action_start", c, r, p)
action.Call(nil)
rt.TriggerEvent("action_end", c, r, p)
return
}
}
p.WriteHeader(404)
p.Write([]byte("page not found"))
}