-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
258 lines (216 loc) · 6.36 KB
/
main.go
File metadata and controls
258 lines (216 loc) · 6.36 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
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
package rou
import (
"net/http"
"strings"
)
const (
MethodGet = "GET"
MethodPost = "POST"
MethodPut = "PUT"
MethodPatch = "PATCH"
MethodDelete = "DELETE"
MethodOptions = "OPTIONS"
MethodHead = "HEAD"
)
const (
MessageBodyIsNotValid = "Request body is not valid"
MessageMethodNotAllowed = "Method not allowed"
MessagePageNotFound = "Page not found"
)
type MiddlewareFunction func(http.ResponseWriter, *http.Request) bool
type RouterMethods interface {
Middleware(middlewares ...MiddlewareFunction)
}
type routerBuilder struct {
value map[string]string
}
func (r *routerBuilder) Delete(name string) {
delete(r.value, name)
}
func (r routerBuilder) Has(name string) bool {
_, has := r.value[name]
return has
}
func (r *routerBuilder) Set(name, value string) {
r.value[name] = value
}
func (r routerBuilder) Get(name string) string {
return r.value[name]
}
type Route struct {
Path string
Handler func(*Context)
middlewares []MiddlewareFunction
}
// Store all middllewares for a specific router
//
// Every middleware should return TRUE if the rule succeeds
// If the middleware returns FALSE - other middlewares will not be triggered
func (r *Route) Middleware(middlewares ...MiddlewareFunction) {
r.middlewares = append(r.middlewares, middlewares...)
}
type existingRoute struct {
Method string
Path string
}
type routes struct {
existingRoutesWithMethod map[existingRoute]bool
routes map[string][]*Route
}
// Stores route to if it is not exists
func (r *routes) storeRoute(method string, route string, handler func(*Context)) *Route {
newRoute := existingRoute{Method: method, Path: route}
if !r.existingRoutesWithMethod[newRoute] {
r.existingRoutesWithMethod[newRoute] = true
newRoute := &Route{Path: route, Handler: handler}
r.routes[method] = append(r.routes[method], newRoute)
return newRoute
}
return nil
}
// Check for route exists in Routes with given method and path
func (r routes) Exists(requestPath string) bool {
for route := range r.existingRoutesWithMethod {
_, equal := isEqualPaths(route.Path, requestPath)
if equal {
return true
}
}
return false
}
func (r routes) GetRoutes(method string) []*Route {
return r.routes[method]
}
// Initial struct to create HTTP server provide this structure to http.ListenAndServe function
// It has a list of routes which is stored to serve
type SimpleRouter struct {
Routes *routes
ContentType string
middlewares []MiddlewareFunction
}
// Create a new SimpleRouter instance
func NewRouter() *SimpleRouter {
routes := routes{
existingRoutesWithMethod: make(map[existingRoute]bool),
routes: make(map[string][]*Route),
}
return &SimpleRouter{Routes: &routes}
}
func (sr *SimpleRouter) Use(middlewares ...MiddlewareFunction) {
sr.middlewares = append(sr.middlewares, middlewares...)
}
func (sr SimpleRouter) GetRoutes(method string) []*Route {
return sr.Routes.GetRoutes(method)
}
func (sr *SimpleRouter) storeRoute(method string, route string, handler func(*Context)) RouterMethods {
return sr.Routes.storeRoute(method, route, handler)
}
// Add route by method GET
func (sr SimpleRouter) Get(route string, handler func(*Context)) RouterMethods {
return sr.storeRoute(MethodGet, route, handler)
}
// Add route by method POST
func (sr SimpleRouter) Post(route string, handler func(*Context)) RouterMethods {
return sr.storeRoute(MethodPost, route, handler)
}
// Add route by method PUT
func (sr SimpleRouter) Put(route string, handler func(*Context)) RouterMethods {
return sr.storeRoute(MethodPut, route, handler)
}
// Add route by method PATCH
func (sr SimpleRouter) Patch(route string, handler func(*Context)) RouterMethods {
return sr.storeRoute(MethodPatch, route, handler)
}
// Add route by method DELETE
func (sr SimpleRouter) Delete(route string, handler func(*Context)) RouterMethods {
return sr.storeRoute(MethodDelete, route, handler)
}
// Add route by method OPTIONS
func (sr SimpleRouter) Options(route string, handler func(*Context)) {
sr.storeRoute(MethodOptions, route, handler)
}
// Add route by method HEAD
func (sr SimpleRouter) Head(route string, handler func(*Context)) RouterMethods {
return sr.storeRoute(MethodHead, route, handler)
}
func (sr SimpleRouter) createContext(w http.ResponseWriter, r *http.Request) *Context {
return &Context{
responseWriter: w,
request: r,
routeParams: &routerBuilder{value: make(map[string]string)},
}
}
func prepareURLChunks(url string) []string {
return strings.Split(strings.Trim(url, "/"), "/")
}
func isEqualPaths(route string, requestPath string) (*map[string]string, bool) {
params := make(map[string]string)
if route == requestPath {
return ¶ms, true
}
clearRoutePath := prepareURLChunks(route)
clearRequestPath := prepareURLChunks(requestPath)
if len(clearRoutePath) != len(clearRequestPath) {
return nil, false
}
for i := 0; i < len(clearRoutePath); i++ {
routeChunk := clearRoutePath[i]
if clearRoutePath[i][0] == ':' {
params[routeChunk[1:]] = clearRequestPath[i]
} else {
if clearRequestPath[i] != routeChunk {
return nil, false
}
}
}
return ¶ms, true
}
func runMiddleWares(route *Route, w http.ResponseWriter, r *http.Request) bool {
for _, middleware := range route.middlewares {
if !middleware(w, r) {
return false
}
}
return true
}
// Implements an http.Handler interface to use it like server handler in http.ListenAndServe
func (sr *SimpleRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, middleware := range sr.middlewares {
if !middleware(w, r) {
return
}
}
ctx := sr.createContext(w, r)
routesByMethod := sr.GetRoutes(r.Method)
ROUTES_BY_METHOD:
for _, route := range routesByMethod {
if r.URL.Path == route.Path {
if !runMiddleWares(route, w, r) {
return
}
route.Handler(ctx)
return
}
params, equal := isEqualPaths(route.Path, r.URL.Path)
if !equal {
continue ROUTES_BY_METHOD
}
if !runMiddleWares(route, w, r) {
return
}
for name, value := range *params {
ctx.RouterParams().Set(name, value)
}
route.Handler(ctx)
return
}
if sr.Routes.Exists(r.URL.Path) {
ctx.ErrorJSONResponse(http.StatusMethodNotAllowed, MessageMethodNotAllowed)
return
}
ctx.ErrorJSONResponse(http.StatusNotFound, MessagePageNotFound)
}
// Runs server with http.ListenAndServe
func (sr *SimpleRouter) RunServer(addr string) error {
return http.ListenAndServe(addr, sr)
}