-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathrouter.go
179 lines (152 loc) · 4.88 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
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
package bunrouter
import (
"net/http"
"net/url"
"strings"
"sync"
)
// Router is the main router structure that implements HTTP request routing.
// It maintains a routing tree and handles incoming HTTP requests.
type Router struct {
config // embedded router configuration
Group // embedded route group
mu sync.Mutex // protects the routing tree
tree node // root node of the routing tree
}
// New creates and returns a new Router instance with the given options.
// Options can include middleware, custom handlers for 404 and 405 responses,
// and other router configurations.
func New(opts ...Option) *Router {
r := &Router{
tree: node{
part: "/",
},
}
r.Group.router = r
r.config.group = &r.Group
r.methodNotAllowedHandler = methodNotAllowedHandler
for _, opt := range opts {
opt.apply(&r.config)
}
// Do it after processing middlewares from the options.
if r.notFoundHandler == nil {
r.notFoundHandler = r.group.wrap(notFoundHandler)
}
return r
}
var _ http.Handler = (*Router)(nil)
// ServeHTTP implements the http.Handler interface.
// It processes the incoming HTTP request and routes it to the appropriate handler.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
_ = r.ServeHTTPError(w, req)
}
// ServeHTTPError is similar to ServeHTTP but also returns any error
// that occurred during request handling.
func (r *Router) ServeHTTPError(w http.ResponseWriter, req *http.Request) error {
handler, params := r.lookup(w, req)
return handler(w, newRequestParams(req, params))
}
// lookup finds the appropriate handler and parameters for the given HTTP request.
// It returns the handler function and parsed route parameters.
func (r *Router) lookup(w http.ResponseWriter, req *http.Request) (HandlerFunc, Params) {
path := req.URL.RawPath
if path == "" {
path = req.URL.Path
}
node, handler, wildcardLen := r.tree.findRoute(req.Method, path)
if node == nil {
if redir := r.redir(req.Method, path); redir != nil {
return redir, Params{}
}
return r.notFoundHandler, Params{}
}
if handler == nil {
if redir := r.redir(req.Method, path); redir != nil {
return redir, Params{}
}
handler = node.handlerMap.notAllowed
}
return handler.fn, Params{
node: node,
handler: handler,
path: path,
wildcardLen: uint16(wildcardLen),
}
}
// redir handles URL redirects for cleaned paths and trailing slash variations.
// It returns a redirect handler if a redirect is needed, nil otherwise.
func (r *Router) redir(method, path string) HandlerFunc {
if path == "/" {
return nil
}
// Path was not found. Try cleaning it up and search again.
if cleanPath := CleanPath(path); cleanPath != path {
if _, handler, _ := r.tree.findRoute(method, cleanPath); handler != nil {
return redirectHandler(cleanPath)
}
}
if strings.HasSuffix(path, "/") {
// Try path without a slash.
cleanPath := path[:len(path)-1]
if _, handler, _ := r.tree.findRoute(method, cleanPath); handler != nil {
return redirectHandler(cleanPath)
}
return nil
}
// Try path with a slash.
cleanPath := path + "/"
if _, handler, _ := r.tree.findRoute(method, cleanPath); handler != nil {
return redirectHandler(cleanPath)
}
return nil
}
//------------------------------------------------------------------------------
// CompatRouter provides compatibility layer for the router.
type CompatRouter struct {
*Router
*CompatGroup
}
// Compat returns a new CompatRouter instance that wraps the current router.
func (r *Router) Compat() *CompatRouter {
return &CompatRouter{
Router: r,
CompatGroup: r.Group.Compat(),
}
}
// VerboseRouter provides a verbose interface to the router.
type VerboseRouter struct {
*Router
*VerboseGroup
}
// Verbose returns a new VerboseRouter instance that wraps the current router.
func (r *Router) Verbose() *VerboseRouter {
return &VerboseRouter{
Router: r,
VerboseGroup: r.Group.Verbose(),
}
}
//------------------------------------------------------------------------------
// redirectHandler creates a handler function that performs HTTP redirects
// to the specified new path while preserving query parameters and fragments.
func redirectHandler(newPath string) HandlerFunc {
return func(w http.ResponseWriter, req Request) error {
newURL := url.URL{
Path: newPath,
RawQuery: req.URL.RawQuery,
Fragment: req.URL.Fragment,
}
http.Redirect(w, req.Request, newURL.String(), http.StatusMovedPermanently)
return nil
}
}
// methodNotAllowedHandler is the default handler for requests with methods
// that are not allowed for the matched route.
func methodNotAllowedHandler(w http.ResponseWriter, r Request) error {
w.WriteHeader(http.StatusMethodNotAllowed)
return nil
}
// notFoundHandler is the default handler for requests that don't match any route.
func notFoundHandler(w http.ResponseWriter, req Request) error {
http.NotFound(w, req.Request)
return nil
}