forked from eolinker/apinto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
checker-regex.go
93 lines (79 loc) · 2.16 KB
/
checker-regex.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
package checker
import (
"fmt"
"regexp"
"strings"
)
//checkerAll 实现了Checker接口,能进行正则匹配
type checkerRegexp struct {
pattern string
rex *regexp.Regexp
tp CheckType
}
//Key 返回路由指标检查器带有完整规则符号的检测值
func (t *checkerRegexp) Key() string {
if t.tp == CheckTypeRegularG {
return fmt.Sprintf("~*= %s", t.pattern)
}
return fmt.Sprintf("~= %s", t.pattern)
}
//newCheckerAll 创建一个区分大小写的正则匹配类型的检查器
func newCheckerRegexp(pattern string) (*checkerRegexp, error) {
pattern = fmt.Sprintf("%s", formatPattern(pattern))
rex, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return &checkerRegexp{
pattern: pattern,
rex: rex,
tp: CheckTypeRegular,
}, nil
}
//newCheckerAll 创建一个不区分大小写的正则匹配类型的检查器
func newCheckerRegexpG(pattern string) (*checkerRegexp, error) {
pattern = fmt.Sprintf(`(?i)(%s)`, formatPattern(pattern))
//rex,err:= regexp.CompilePOSIX(pattern)
//if err!= nil{
// return nil,err
//}
rex, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return &checkerRegexp{
pattern: pattern,
rex: rex,
tp: CheckTypeRegularG,
}, nil
}
//Value 返回路由指标检查器的检测值
func (t *checkerRegexp) Value() string {
return t.pattern
}
//Check 判断待检测的路由指标值是否满足检查器的匹配规则
func (t *checkerRegexp) Check(v string, has bool) bool {
//当待检测的路由指标值满足检查器的正则表达式值时匹配成功
if !has {
return false
}
return t.rex.MatchString(v)
}
//CheckType 返回检查器的类型值
func (t *checkerRegexp) CheckType() CheckType {
return t.tp
}
//formatPattern 格式化正则表达式的值
func formatPattern(pattern string) string {
pattern = strings.TrimSpace(pattern)
if len(pattern) == 0 {
return pattern
}
//if strings.HasPrefix(pattern,"/") && strings.HasSuffix(pattern,"/"){
// return strings.TrimSuffix(pattern[1:],"/")
//}
//if strings.HasPrefix(pattern,"/") && strings.HasSuffix(pattern,"/i"){
// return strings.TrimSuffix(pattern[1:],"/i")
//}
return pattern
}