-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuse.go
135 lines (103 loc) · 2.22 KB
/
fuse.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
package fuse
import (
"errors"
"fmt"
"github.com/phuhao00/network"
)
var (
// ErrNotFound is returned when no route match is found.
ErrNotFound = errors.New("no matching route was found")
)
func NewRouter() *Router {
return &Router{namedRoutes: make(map[string]*Route)}
}
type Router struct {
NotFoundHandler Handler
MethodNotAllowedHandler Handler
routes []*Route
namedRoutes map[string]*Route
KeepContext bool
middlewares []middleware
routeConf
}
type routeConf struct {
matchers []matcher
}
// RouteMatch stores information about a matched route.
type RouteMatch struct {
Handler Handler
Vars map[string]string
MatchErr error
}
func (r *Router) NewRoute() *Route {
route := &Route{namedRoutes: r.namedRoutes}
r.routes = append(r.routes, route)
return route
}
func (r *Router) Match(req *network.Packet, match *RouteMatch) bool {
for _, route := range r.routes {
if route.Match(req, match) {
for i := len(r.middlewares) - 1; i >= 0; i-- {
match.Handler = r.middlewares[i].Middleware(match.Handler)
}
return true
}
}
return false
}
func (r *Router) GetHandler(req *network.Packet) Handler {
var match RouteMatch
if !r.Match(req, &match) {
return nil
}
return match.Handler
}
func (r *Router) AddRoute(Id uint64, f Handler) *Route {
return r.NewRoute().SetId(Id).SetHandler(f)
}
func (r *Route) SetHandler(handler Handler) *Route {
if r.err == nil {
r.handler = handler
}
return r
}
func (r *Route) GetHandler() Handler {
return r.handler
}
func (r *Route) SetDescription(desc string) *Route {
if r.Description != "" {
r.err = fmt.Errorf("route already has Description %q, can't set %q",
r.Description, desc)
}
if r.err == nil {
r.Description = desc
}
return r
}
func (r *Route) GetName() string {
return r.Description
}
func (r *Route) GetError() error {
return r.err
}
func (r *Route) Match(packet *network.Packet, match *RouteMatch) bool {
if r.err != nil {
return false
}
var matchErr error
for _, m := range r.matchers {
if matched := m.Match(packet, match); !matched {
matchErr = ErrNotFound
continue
} else {
matchErr = nil
break
}
}
if matchErr != nil {
match.MatchErr = matchErr
return false
}
match.Handler = r.handler
return true
}