-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
84 lines (71 loc) · 1.49 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
package do
import (
"context"
"net/http"
)
type RouteRegister interface {
Handle(method, path string, handlers http.HandlerFunc)
}
type RouteHandler[P, R any] interface {
Parse(req *http.Request, p *P) error
Write(w http.ResponseWriter, r R, err error)
}
// RegisterRouter register router to RouteRegister with http.HandlerFunc
func RegisterRouter[H RouteRegister, RH RouteHandler[P, R], P, R any](
g H,
rh RH,
method, path string,
f func(context.Context, P) (R, error),
) {
g.Handle(method, path, func(w http.ResponseWriter, req *http.Request) {
var (
p P
r R
err error
)
defer func() {
// 返回
rh.Write(w, r, err)
}()
// 参数
err = rh.Parse(req, &p)
if err != nil {
return
}
// 业务
r, err = f(req.Context(), p)
})
}
type HandlerFunc[T any] func(T)
func (h HandlerFunc[T]) HTTPHandlerFunc(t T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if h == nil {
return
}
h(t)
}
}
type Route[T any] struct {
Method string
Path string
Comment string
Handler HandlerFunc[T]
Childs []*Route[T]
}
func (r *Route[T]) WithChilds(childs ...*Route[T]) *Route[T] {
r.Childs = append(r.Childs, childs...)
return r
}
func (r *Route[T]) SetChilds(childs ...*Route[T]) *Route[T] {
r.Childs = childs
return r
}
func NewRoute[T any](method, path, comment string, h HandlerFunc[T], childs ...*Route[T]) *Route[T] {
return &Route[T]{
Method: method,
Path: path,
Comment: comment,
Handler: h,
Childs: childs,
}
}