-
Notifications
You must be signed in to change notification settings - Fork 1
/
routes.go
107 lines (84 loc) · 2.23 KB
/
routes.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
package routes
import (
"fmt"
"strings"
"github.com/valyala/fasthttp"
)
// Routes represents the fasthttp aware routes
// and configuration that determine which route to choose
type Routes struct {
Routes map[string]fasthttp.RequestHandler
Catcher fasthttp.RequestHandler
}
// New is a friendly, convenience function for returning
// an instance of routes.Routes that can be used in client code
func New() *Routes {
return &Routes{
Routes: make(map[string]fasthttp.RequestHandler),
Catcher: func(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "404 - no such route %s", string(ctx.Path()))
},
}
}
// Add takes a pattern, a function, and adds them to its self
// so requests can be routed correctly.
//
// A pattern can be a full url, or can use parameters.
// Params in URLs look like:
// /users/:user/address
// This would match on:
// /users/12345/address
// (For instance)
//
// Add() does no checking for existing routes; it is the responsibility
// of the developer to ensure there are no duplicates. The last function
// assigned to a patter will be used.
func (r *Routes) Add(pattern string, f fasthttp.RequestHandler) {
r.Routes[normaliseRoute(pattern)] = f
}
// Route will send a fasthttp request to the correct function based
// on the path in the request.
// Parameters, as defined in a route, are accessed by ctx.userValue(param)
func (r Routes) Route(ctx *fasthttp.RequestCtx) {
path := normaliseRoute(string(ctx.Path()))
pathSplit := strings.Split(path, "/")
for spec, f := range r.Routes {
if spec == path {
f(ctx)
return
}
params := make(map[string]string)
specSplit := strings.Split(spec, "/")
if len(pathSplit) != len(specSplit) {
continue
}
for idx, elem := range specSplit {
pathElem := pathSplit[idx]
if strings.HasPrefix(elem, ":") {
params[elem] = pathElem
} else if elem != pathElem {
goto BADROUTE
}
}
for k, v := range params {
ctx.SetUserValue(stripTemplateChars(k), v)
}
f(ctx)
return
BADROUTE:
}
r.Catcher(ctx)
return
}
func normaliseRoute(s string) string {
if !strings.HasPrefix(s, "/") {
s = "/" + s
}
if strings.HasSuffix(s, "/") {
return s
}
return s + "/"
}
func stripTemplateChars(s string) string {
return strings.TrimPrefix(s, ":")
}