forked from Eodomius/router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
79 lines (63 loc) · 1.92 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
package router
import (
"fmt"
"net/http"
"regexp"
)
func New() Router {
return Router{
routes: make(map[string]Route),
paramsRegex: regexp.MustCompile(`({[^/]+})`),
}
}
func (ro Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
req.URL.Path = normalizePath(req.URL.Path)
route, exist := resolveRoute(ro, req)
if !exist {
return
}
var result = Result{
Params: make(map[string]string),
}
resolveParams(&route, req, &result)
route.Execute(res, req, &result)
}
func (ro Router) HandleRoute(path, method string, cb func(w http.ResponseWriter, r *http.Request, route *Result)){
route := Route{
Path: path,
Method: method,
Execute: cb,
ParamsNames: []string{},
}
paramsNames := ro.paramsRegex.FindAllString(path, -1)
for i, paramName := range paramsNames {
paramsNames[i] = regexp.MustCompile("{|}").ReplaceAllString(paramName, "")
}
route.ParamsNames = paramsNames
var replacedRoute = ro.paramsRegex.ReplaceAllString(path, `([^/]+)`)
replacedRoute = "^" + replacedRoute + "$";
route.PathRegex = regexp.MustCompile(replacedRoute)
ro.routes[method + ": " + path] = route
fmt.Println(method + ": " + route.Path)
}
/****************** Methods handlers ******************/
// GET
func (ro Router) Get(path string, cb func(w http.ResponseWriter, r *http.Request, route *Result)){
ro.HandleRoute(path, "GET", cb)
}
// POST
func (ro Router) Post(path string, cb func(w http.ResponseWriter, r *http.Request, route *Result)){
ro.HandleRoute(path, "POST", cb)
}
// PATCH
func (ro Router) Patch(path string, cb func(w http.ResponseWriter, r *http.Request, route *Result)){
ro.HandleRoute(path, "PATCH", cb)
}
// PUT
func (ro Router) Put(path string, cb func(w http.ResponseWriter, r *http.Request, route *Result)){
ro.HandleRoute(path, "PUT", cb)
}
// DELETE
func (ro Router) Delete(path string, cb func(w http.ResponseWriter, r *http.Request, route *Result)){
ro.HandleRoute(path, "DELETE", cb)
}