This repository was archived by the owner on Oct 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathrouter.go
More file actions
187 lines (166 loc) · 5.04 KB
/
router.go
File metadata and controls
187 lines (166 loc) · 5.04 KB
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
package GoGym
import (
log "github.com/Sirupsen/logrus"
"net/http"
"reflect"
"strings"
)
const (
ServiceRouter = "Router"
)
// Router service
type Router struct {
// App is the Service Container
App *Gym
// ControllerRegistry is where all registered controllers exist
ControllerRegistry map[string]interface{}
MethodVerbs []string
RouteCollection []Route
}
// Prepare is a method prepares the router service
func (r *Router) Prepare(g *Gym) {
r.InjectServiceContainer(g)
r.ControllerRegistry = make(map[string]interface{})
r.MethodVerbs = []string{GETMethod, POSTMethod, PUTMethod, PATCHMethod, DELETEMethod, OPTIONSMethod}
}
// InjectServiceContainer is a method sets the service container into the Router
func (r *Router) InjectServiceContainer(g *Gym) {
r.App = g
}
// GetServiceContainer is a method gets the service container
func (r *Router) GetServiceContainer() *Gym {
return r.App
}
func (r *Router) CallMethod(method string, param []interface{}) []reflect.Value {
return nil
}
// NewRoute is a method that creates a new route to RouteCollection
func (r *Router) NewRoute(uri string, methods []string, action string) {
if !r.IsActionLegal(action) {
log.Fatalf("Action %s is illegal", action)
return
}
var route Route
route.uri = uri
route.methods = methods
route.action = action
route.extractTokens(route.uri)
route.compile(route.uri)
r.RouteCollection = append(r.RouteCollection, route)
}
// IsActionLegal checks if an action is legal
func (r *Router) IsActionLegal(action string) bool {
result := false
if strings.Contains(action, "@") {
result = true
}
return result
}
// Get is a method handles GET requests
func (r *Router) Get(path, action string) {
methods := []string{GETMethod}
r.NewRoute(path, methods, action)
}
// Post is a method handles POST requests
func (r *Router) Post(path, action string) {
methods := []string{POSTMethod}
r.NewRoute(path, methods, action)
}
// Put is a method handles PUT requests
func (r *Router) Put(path, action string) {
methods := []string{PUTMethod}
r.NewRoute(path, methods, action)
}
// Patch is a method handles PATCH requests
func (r *Router) Patch(path, action string) {
methods := []string{PATCHMethod}
r.NewRoute(path, methods, action)
}
// Options is a method handles Options requests
func (r *Router) Options(path, action string) {
methods := []string{OPTIONSMethod}
r.NewRoute(path, methods, action)
}
// Delete is a method handles Delete requests
func (r *Router) Delete(path, action string) {
methods := []string{DELETEMethod}
r.NewRoute(path, methods, action)
}
// ServeHTTP is a method serve http service
func (r *Router) ServeHTTP(rw http.ResponseWriter, request *http.Request) {
requestService := r.GetServiceContainer().Request
responseService := r.GetServiceContainer().Response
requestService.accept(request)
responseService.wait()
routes := r.FindRoute(request.URL.Path)
if routes == nil {
rsp := make(map[string]interface{})
rsp["err"] = "Not found"
responseService.JsonResponse(rsp, HTTPStatusNotFound, http.Header{})
} else {
methodMatch := false
var handlingRoute Route
for k, route := range routes {
for _, mth := range route.methods {
if mth == request.Method {
methodMatch = true
handlingRoute = routes[k]
}
}
}
if !methodMatch {
rsp := make(map[string]interface{})
rsp["err"] = "Method not allowed"
responseService.JsonResponse(rsp, HTTPStatusMethodNotAllowed, http.Header{})
} else {
// Binding path variables
requestService.bindPathVar(handlingRoute.compiled.Tokens)
// Handling request
r.Handle(handlingRoute, rw, request)
}
}
for k, v := range responseService.Header {
for _, h := range v {
rw.Header().Add(k, h)
}
}
rw.WriteHeader(responseService.StatusCode)
rw.Write(responseService.Response)
}
// FindRoute is a method finding a group of Route whose Uri is matched wit request Uri
func (r *Router) FindRoute(uri string) []Route {
var matchedCollection []Route
matched := false
for _, route := range r.RouteCollection {
if route.match(uri) {
route.assignValuesToTokens(uri)
matchedCollection = append(matchedCollection, route)
matched = true
}
}
if matched {
return matchedCollection
}
return nil
}
// Handle is a method for using route passed in to handle the request
func (r *Router) Handle(route Route, rw http.ResponseWriter, request *http.Request) {
actionSlice := strings.Split(route.action, "@")
method := actionSlice[1]
controllerKey := "*" + actionSlice[0]
controller := r.ControllerRegistry[controllerKey]
in := make([]reflect.Value, 1)
in[0] = reflect.ValueOf(r.GetServiceContainer())
reflect.ValueOf(controller).MethodByName(method).Call(in)
}
// RegisterController is a method registers controller
func (r *Router) RegisterController(controller interface{}) {
controllerType := GetType(controller)
r.ControllerRegistry[controllerType] = controller
}
// RegisterControllers is a method registers a bunch of controllers into controllerRegistry
func (r *Router) RegisterControllers(controllers []interface{}) {
for _, v := range controllers {
r.RegisterController(v)
}
}