-
Notifications
You must be signed in to change notification settings - Fork 2
/
supernova.go
332 lines (274 loc) · 6.98 KB
/
supernova.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
// Package supernova is a fasthttp router that implements a radix tree for fast lookups
package supernova
import (
"fmt"
"net"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/valyala/fasthttp"
)
// Server represents the router and all associated data
type Server struct {
server *fasthttp.Server
ln net.Listener
// radix tree for looking up routes
paths map[string]*Node
middleWare []Middleware
// shutdown function called when ctl-c is intercepted
shutdownHandler func()
// debug defines logging for requests
debug bool
}
// Node holds a single route with accompanying children routes
type Node struct {
route *Route
isEdge bool
children map[string]*Node
}
// CachedObj represents a static asset
type CachedObj struct {
data []byte
timeCached time.Time
}
// CachedStatic holds all cached static assets in memory
type CachedStatic struct {
mutex sync.Mutex
files map[string]*CachedObj
}
// Middleware holds all middleware functions
type Middleware struct {
middleFunc func(*Request, func())
}
// New returns new supernova router
func New() *Server {
s := new(Server)
s.server = &fasthttp.Server{
Handler: s.handler,
}
return s
}
// EnableDebug toggles output for incoming requests
func (sn *Server) EnableDebug(debug bool) {
if debug {
sn.debug = true
}
}
// ListenAndServe starts the server
func (sn *Server) ListenAndServe(addr string) error {
listener, err := net.Listen("tcp4", addr)
if err != nil {
return err
}
sn.ln = NewGracefulListener(listener, time.Second*5)
return sn.server.Serve(sn.ln)
}
// ListenAndServeTLS starts server with ssl
func (sn *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
listener, err := net.Listen("tcp4", addr)
if err != nil {
return err
}
sn.ln = NewGracefulListener(listener, time.Second*5)
return fasthttp.ListenAndServeTLS(addr, certFile, keyFile, sn.handler)
}
// Serve serves incoming connections from the given listener.
func (sn *Server) Serve(ln net.Listener) error {
return sn.server.Serve(ln)
}
// Close closes existing listener
func (sn *Server) Close() error {
return sn.ln.Close()
}
// handler is the main entry point into the router
func (sn *Server) handler(ctx *fasthttp.RequestCtx) {
request := NewRequest(ctx)
var logMethod func()
if sn.debug {
logMethod = getDebugMethod(request)
}
if logMethod != nil {
defer logMethod()
}
// Run Middleware
finished := sn.runMiddleware(request)
if !finished {
return
}
route := sn.climbTree(request.GetMethod(), request.BaseUrl)
if route != nil {
route.call(request)
return
}
ctx.Error("404 Not Found", fasthttp.StatusNotFound)
}
// All adds route for all http methods
func (sn *Server) All(route string, routeFunc func(*Request)) {
sn.addRoute("", buildRoute(route, routeFunc))
}
// Get adds only GET method to route
func (sn *Server) Get(route string, routeFunc func(*Request)) {
sn.addRoute("GET", buildRoute(route, routeFunc))
}
// Post adds only POST method to route
func (sn *Server) Post(route string, routeFunc func(*Request)) {
sn.addRoute("POST", buildRoute(route, routeFunc))
}
// Put adds only PUT method to route
func (sn *Server) Put(route string, routeFunc func(*Request)) {
sn.addRoute("PUT", buildRoute(route, routeFunc))
}
// Delete adds only DELETE method to route
func (sn *Server) Delete(route string, routeFunc func(*Request)) {
sn.addRoute("DELETE", buildRoute(route, routeFunc))
}
// Restricted adds route that is restricted by method
func (sn *Server) Restricted(method, route string, routeFunc func(*Request)) {
sn.addRoute(method, buildRoute(route, routeFunc))
}
// addRoute takes route and method and adds it to route tree
func (sn *Server) addRoute(method string, route *Route) {
routeStr := route.route
if routeStr[len(routeStr)-1] == '/' {
routeStr = routeStr[:len(routeStr)-1]
route.route = routeStr
}
if sn.paths == nil {
sn.paths = make(map[string]*Node)
}
if sn.paths[method] == nil {
node := new(Node)
node.children = make(map[string]*Node)
sn.paths[method] = node
}
parts := strings.Split(routeStr[1:], "/")
currentNode := sn.paths[method]
for index, val := range parts {
childKey := val
if val[0] == ':' {
childKey = ""
} else {
childKey = val
}
if node, ok := currentNode.children[childKey]; ok {
currentNode = node
} else {
node := getNode(false, nil)
currentNode.children[childKey] = node
currentNode = node
}
if index == len(parts)-1 {
node := getNode(true, route)
currentNode.children[childKey] = node
currentNode = node
}
}
}
// getNode builds a new node to be added to the radix tree
func getNode(isEdge bool, route *Route) *Node {
node := new(Node)
node.children = make(map[string]*Node)
if isEdge {
node.isEdge = true
node.route = route
}
return node
}
// climbTree takes in path and traverses tree to find route
func (sn *Server) climbTree(method, path string) *Route {
// strip slashes
if path[len(path)-1] == '/' {
path = path[1 : len(path)-1]
} else {
path = path[1:]
}
parts := strings.Split(path, "/")
pathLen := len(parts) - 1
currentNode, ok := sn.paths[method]
if !ok {
currentNode, ok = sn.paths[""]
if !ok {
return nil
}
}
for index, val := range parts {
var node *Node
node = currentNode.children[val]
if node == nil {
node = currentNode.children[""]
}
// path not found return
if node == nil && method == "" {
return nil
} else if node == nil {
return sn.climbTree("", path)
}
currentNode = node
// if at end return current route
if index == pathLen {
if node, ok := currentNode.children[val]; ok {
return node.route
}
if node, ok = currentNode.children[""]; ok {
return node.route
}
}
}
return nil
}
// buildRoute creates new Route
func buildRoute(route string, routeFunc func(*Request)) *Route {
routeObj := new(Route)
routeObj.routeFunc = routeFunc
routeObj.routeParamsIndex = make(map[int]string)
routeObj.route = route
return routeObj
}
// Use adds a new function to the middleware stack
func (sn *Server) Use(f func(*Request, func())) {
if sn.middleWare == nil {
sn.middleWare = make([]Middleware, 0)
}
middle := new(Middleware)
middle.middleFunc = f
sn.middleWare = append(sn.middleWare, *middle)
}
// Internal method that runs the middleware
func (sn *Server) runMiddleware(req *Request) bool {
stackFinished := true
for m := range sn.middleWare {
nextCalled := false
sn.middleWare[m].middleFunc(req, func() {
nextCalled = true
})
if !nextCalled {
stackFinished = false
break
}
}
return stackFinished
}
// SetShutDownHandler implements function called when SIGTERM signal is received
func (sn *Server) SetShutDownHandler(shutdownFunc func()) {
sn.shutdownHandler = shutdownFunc
sigs := make(chan os.Signal)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
for {
select {
case <-sigs:
err := sn.ln.Close()
if err != nil {
fmt.Printf("Error closing conn: %s\n", err.Error())
}
if shutdownFunc != nil {
shutdownFunc()
}
os.Exit(0)
}
}
}()
}