-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontroller.go
55 lines (46 loc) · 1020 Bytes
/
controller.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
package bingo
import (
"github.com/gin-gonic/gin"
"net/http"
)
// Controller 控制器
type Controller interface {
Route(group *Group)
Name() string
}
// Bind 参数绑定
type Bind[T any] struct {
try func(ctx *gin.Context, t *T) any
catch func(ctx *gin.Context, err error)
}
func NewBind[T any]() *Bind[T] {
return &Bind[T]{}
}
// Try 参数绑定验证通过执行
func (b *Bind[T]) Try(f func(ctx *gin.Context, t *T) any) *Bind[T] {
b.try = f
return b
}
// Catch 失败执行
func (b *Bind[T]) Catch(f ...func(ctx *gin.Context, err error)) *Bind[T] {
if len(f) > 0 {
b.catch = f[0]
} else {
b.catch = func(ctx *gin.Context, err error) {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
return b
}
// Complete 完成调用
func (b *Bind[T]) Complete() func(ctx *gin.Context) any {
return func(ctx *gin.Context) any {
var t T
if err := ctx.ShouldBind(&t); err != nil {
b.catch(ctx, err)
return nil
} else {
return b.try(ctx, &t)
}
}
}