Skip to content

Commit 9042fc3

Browse files
committed
refactor!: 中间件添加 router 参数
用以区分当前路由项属于哪个路由
1 parent 3a44d80 commit 9042fc3

File tree

10 files changed

+35
-23
lines changed

10 files changed

+35
-23
lines changed

examples/std/std_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import (
1919
var (
2020
_ http.Handler = &Router{}
2121
_ http.Handler = &Routers{}
22-
_ Middleware = MiddlewareFunc(func(http.Handler, string, string) http.Handler { return nil })
22+
_ Middleware = MiddlewareFunc(func(_ http.Handler, _, _, _ string) http.Handler { return nil })
2323
)
2424

2525
func TestRouter(t *testing.T) {

group/group.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ func (g *GroupOf[T]) Use(m ...types.MiddlewareOf[T]) {
130130
for _, r := range g.routers {
131131
r.r.Use(m...)
132132
}
133-
g.notFound = tree.ApplyMiddleware(g.notFound, "", "", m...)
133+
g.notFound = tree.ApplyMiddleware(g.notFound, "", "", "", m...)
134134

135135
g.middleware = append(g.middleware, m...)
136136
}

group/host.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ type Hosts struct {
2424
func NewHosts(lock bool, domain ...string) *Hosts {
2525
i := syntax.NewInterceptors()
2626
f := func(types.Node) any { return nil }
27-
t := tree.New(lock, i, nil, false, f, f)
27+
t := tree.New("", lock, i, nil, false, f, f)
2828
h := &Hosts{tree: t, i: i}
2929
h.Add(domain...)
3030
return h

internal/tree/method.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -98,19 +98,19 @@ func (n *node[T]) addMethods(h T, pattern string, ms []types.MiddlewareOf[T], me
9898
}
9999

100100
if m == http.MethodGet {
101-
n.handlers[http.MethodHead] = ApplyMiddleware(h, http.MethodHead, pattern, ms...)
101+
n.handlers[http.MethodHead] = ApplyMiddleware(h, http.MethodHead, pattern, n.root.Name(), ms...)
102102
}
103103

104-
n.handlers[m] = ApplyMiddleware(h, m, pattern, ms...)
104+
n.handlers[m] = ApplyMiddleware(h, m, pattern, n.root.Name(), ms...)
105105
}
106106

107107
// 查看是否需要添加 OPTIONS
108108
if _, found := n.handlers[http.MethodOptions]; !found {
109-
n.handlers[http.MethodOptions] = ApplyMiddleware(n.root.optionsBuilder(n), http.MethodOptions, pattern, ms...)
109+
n.handlers[http.MethodOptions] = ApplyMiddleware(n.root.optionsBuilder(n), http.MethodOptions, pattern, n.root.Name(), ms...)
110110
}
111111

112112
if _, found := n.handlers[methodNotAllowed]; !found {
113-
n.handlers[methodNotAllowed] = ApplyMiddleware(n.root.methodNotAllowedBuilder(n), "", pattern, ms...)
113+
n.handlers[methodNotAllowed] = ApplyMiddleware(n.root.methodNotAllowedBuilder(n), "", pattern, n.root.Name(), ms...)
114114
}
115115

116116
n.buildMethods()

internal/tree/node.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -333,17 +333,17 @@ func (n *node[T]) checkAmbiguous(pattern string, hasNonString bool) (*node[T], b
333333

334334
func (n *node[T]) applyMiddleware(ms ...types.MiddlewareOf[T]) {
335335
for m, h := range n.handlers {
336-
n.handlers[m] = ApplyMiddleware(h, m, n.Pattern(), ms...)
336+
n.handlers[m] = ApplyMiddleware(h, m, n.Pattern(), n.root.Name(), ms...)
337337
}
338338

339339
for _, c := range n.children {
340340
c.applyMiddleware(ms...)
341341
}
342342
}
343343

344-
func ApplyMiddleware[T any](h T, method, pattern string, f ...types.MiddlewareOf[T]) T {
344+
func ApplyMiddleware[T any](h T, method, pattern, router string, f ...types.MiddlewareOf[T]) T {
345345
for _, ff := range f {
346-
h = ff.Middleware(h, method, pattern)
346+
h = ff.Middleware(h, method, pattern, router)
347347
}
348348
return h
349349
}

internal/tree/test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,13 @@ import (
1919

2020
// NewTestTree 返回以 http.Handler 作为参数实例化的 Tree
2121
func NewTestTree(a *assert.Assertion, lock, trace bool, i *syntax.Interceptors) *Tree[http.Handler] {
22-
t := New(lock, i, http.NotFoundHandler(), trace, BuildTestNodeHandlerFunc(http.StatusMethodNotAllowed), BuildTestNodeHandlerFunc(http.StatusOK))
22+
t := New("", lock, i, http.NotFoundHandler(), trace, BuildTestNodeHandlerFunc(http.StatusMethodNotAllowed), BuildTestNodeHandlerFunc(http.StatusOK))
2323
a.NotNil(t)
2424
return t
2525
}
2626

2727
func BuildTestMiddleware(a *assert.Assertion, text string) types.MiddlewareOf[http.Handler] {
28-
return types.MiddlewareFuncOf[http.Handler](func(next http.Handler, _, _ string) http.Handler {
28+
return types.MiddlewareFuncOf[http.Handler](func(next http.Handler, _, _, _ string) http.Handler {
2929
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3030
next.ServeHTTP(w, r) // 先输出被包含的内容
3131
_, err := w.Write([]byte(text))

internal/tree/tree.go

+15-2
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ import (
3737
// |
3838
// +---- emails
3939
type Tree[T any] struct {
40+
name string // 名称
41+
4042
methods map[string]int // 保存着每个请求方法在所有子节点上的数量。
4143
node *node[T] // 空节点,正好用于处理 OPTIONS *。
4244

@@ -50,13 +52,22 @@ type Tree[T any] struct {
5052
methodNotAllowedBuilder types.BuildNodeHandleOf[T]
5153
}
5254

53-
func New[T any](lock bool, i *syntax.Interceptors, notFound T, trace bool, methodNotAllowedBuilder, optionsBuilder types.BuildNodeHandleOf[T]) *Tree[T] {
55+
func New[T any](
56+
name string,
57+
lock bool,
58+
i *syntax.Interceptors,
59+
notFound T,
60+
trace bool,
61+
methodNotAllowedBuilder,
62+
optionsBuilder types.BuildNodeHandleOf[T],
63+
) *Tree[T] {
5464
s, err := i.NewSegment("")
5565
if err != nil {
5666
panic("发生了不该发生的错误,应该是 syntax.NewSegment 逻辑发生变化" + err.Error())
5767
}
5868

5969
t := &Tree[T]{
70+
name: name,
6071
methods: make(map[string]int, len(Methods)),
6172
node: &node[T]{segment: s, methodIndex: methodIndexMap[http.MethodOptions]},
6273

@@ -79,6 +90,8 @@ func New[T any](lock bool, i *syntax.Interceptors, notFound T, trace bool, metho
7990
return t
8091
}
8192

93+
func (tree *Tree[T]) Name() string { return tree.name }
94+
8295
// Add 添加路由项
8396
//
8497
// methods 可以为空,表示添所有支持的请求方法,其中的 HEAD 和 OPTIONS 不受控。
@@ -291,6 +304,6 @@ func (tree *Tree[T]) URL(buf *errwrap.StringBuilder, pattern string, ps map[stri
291304

292305
// ApplyMiddleware 为已有的路由项添加中间件
293306
func (tree *Tree[T]) ApplyMiddleware(ms ...types.MiddlewareOf[T]) {
294-
tree.notFound = ApplyMiddleware(tree.notFound, "", "", ms...)
307+
tree.notFound = ApplyMiddleware(tree.notFound, "", "", tree.Name(), ms...)
295308
tree.node.applyMiddleware(ms...)
296309
}

router.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ type (
2727
// Handle("/api/{version:\\d+}",h3, http.MethodGet, http.MethodPost) // 只匹配 GET 和 POST
2828
// http.ListenAndServe(router)
2929
RouterOf[T any] struct {
30-
name string
3130
tree *tree.Tree[T]
3231
call CallOf[T]
3332

@@ -74,8 +73,7 @@ func NewRouterOf[T any](name string, call CallOf[T], notFound T, methodNotAllowe
7473
}
7574

7675
r := &RouterOf[T]{
77-
name: name,
78-
tree: tree.New(opt.Lock, opt.Interceptors, notFound, opt.Trace, methodNotAllowedBuilder, optionsBuilder),
76+
tree: tree.New(name, opt.Lock, opt.Interceptors, notFound, opt.Trace, methodNotAllowedBuilder, optionsBuilder),
7977
call: call,
8078

8179
cors: opt.CORS,
@@ -222,7 +220,7 @@ func (r *RouterOf[T]) ServeContext(w http.ResponseWriter, req *http.Request, ctx
222220
}
223221

224222
// Name 路由名称
225-
func (r *RouterOf[T]) Name() string { return r.name }
223+
func (r *RouterOf[T]) Name() string { return r.tree.Name() }
226224

227225
func (p *PrefixOf[T]) Handle(pattern string, h T, m []types.MiddlewareOf[T], methods ...string) *PrefixOf[T] {
228226
m = slices.Concat(m, p.middleware)

router_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ func TestPrefix_Resource(t *testing.T) {
268268
a.NotNil(def)
269269

270270
buildTestMiddleware := func(a *assert.Assertion, text string) types.MiddlewareOf[ctx.Handler] {
271-
return types.MiddlewareFuncOf[ctx.Handler](func(next ctx.Handler, _, _ string) ctx.Handler {
271+
return types.MiddlewareFuncOf[ctx.Handler](func(next ctx.Handler, _, _, _ string) ctx.Handler {
272272
return ctx.HandlerFunc(func(ctx *ctx.CTX) {
273273
next.Handle(ctx) // 先输出被包含的内容
274274
_, err := ctx.W.Write([]byte(text))

types/types.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -116,16 +116,17 @@ type MiddlewareOf[T any] interface {
116116
// next 路由项的处理函数;
117117
// method 当前路由的请求方法;
118118
// pattern 当前路由的匹配项;
119+
// router 路由名称,即 [mux.RouterOf.Name] 的值;
119120
//
120121
// NOTE: method 和 pattern 在某些特殊的路由项中会有特殊的值:
121122
// - 404 method 和 pattern 均为空;
122123
// - 405 method 为空,pattern 正常;
123-
Middleware(next T, method, pattern string) T
124+
Middleware(next T, method, pattern, router string) T
124125
}
125126

126127
// MiddlewareFuncOf 中间件处理函数
127-
type MiddlewareFuncOf[T any] func(T, string, string) T
128+
type MiddlewareFuncOf[T any] func(next T, method, pattern, router string) T
128129

129-
func (f MiddlewareFuncOf[T]) Middleware(next T, method, pattern string) T {
130-
return f(next, method, pattern)
130+
func (f MiddlewareFuncOf[T]) Middleware(next T, method, pattern, router string) T {
131+
return f(next, method, pattern, router)
131132
}

0 commit comments

Comments
 (0)