-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathregex.go
49 lines (37 loc) · 771 Bytes
/
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
package rio
import (
"context"
"regexp"
"sync"
"github.com/hungdv136/rio/internal/log"
)
var defaultRegexCompiler = ®exCompiler{}
type regexCompiler struct {
exprs map[string]*regexp.Regexp
l sync.RWMutex
}
func (c *regexCompiler) compile(ctx context.Context, expr string) (*regexp.Regexp, error) {
if r := c.getFromCache(expr); r != nil {
return r, nil
}
c.l.Lock()
defer c.l.Unlock()
r, err := regexp.Compile(expr)
if err != nil {
log.Error(ctx, err)
return nil, err
}
if c.exprs == nil {
c.exprs = map[string]*regexp.Regexp{}
}
c.exprs[expr] = r
return r, nil
}
func (c *regexCompiler) getFromCache(expr string) *regexp.Regexp {
c.l.RLock()
defer c.l.RUnlock()
if r, ok := c.exprs[expr]; ok {
return r
}
return nil
}