/
middleware.go
80 lines (68 loc) · 2.02 KB
/
middleware.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
package middleware
import (
"fmt"
"strings"
"github.com/linzhengen/gin-admin-with-frontend-sample/internal/app/errors"
"github.com/linzhengen/gin-admin-with-frontend-sample/internal/app/ginplus"
"github.com/gin-gonic/gin"
)
// NoMethodHandler 未找到请求方法的处理函数
func NoMethodHandler() gin.HandlerFunc {
return func(c *gin.Context) {
ginplus.ResError(c, errors.ErrMethodNotAllow)
}
}
// NoRouteHandler 未找到请求路由的处理函数
func NoRouteHandler() gin.HandlerFunc {
return func(c *gin.Context) {
ginplus.ResError(c, errors.ErrNotFound)
}
}
// SkipperFunc 定义中间件跳过函数
type SkipperFunc func(*gin.Context) bool
// AllowPathPrefixSkipper 检查请求路径是否包含指定的前缀,如果包含则跳过
func AllowPathPrefixSkipper(prefixes ...string) SkipperFunc {
return func(c *gin.Context) bool {
path := c.Request.URL.Path
pathLen := len(path)
for _, p := range prefixes {
if pl := len(p); pathLen >= pl && path[:pl] == p {
return true
}
}
return false
}
}
// AllowPathPrefixNoSkipper 检查请求路径是否包含指定的前缀,如果包含则不跳过
func AllowPathPrefixNoSkipper(prefixes ...string) SkipperFunc {
return func(c *gin.Context) bool {
path := c.Request.URL.Path
pathLen := len(path)
for _, p := range prefixes {
if pl := len(p); pathLen >= pl && path[:pl] == p {
return false
}
}
return true
}
}
// AllowMethodAndPathPrefixSkipper 检查请求方法和路径是否包含指定的前缀,如果不包含则跳过
func AllowMethodAndPathPrefixSkipper(prefixes ...string) SkipperFunc {
return func(c *gin.Context) bool {
path := JoinRouter(c.Request.Method, c.Request.URL.Path)
pathLen := len(path)
for _, p := range prefixes {
if pl := len(p); pathLen >= pl && path[:pl] == p {
return true
}
}
return false
}
}
// JoinRouter 拼接路由
func JoinRouter(method, path string) string {
if len(path) > 0 && path[0] != '/' {
path = "/" + path
}
return fmt.Sprintf("%s%s", strings.ToUpper(method), path)
}