-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathregexp.go
50 lines (39 loc) · 981 Bytes
/
regexp.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
package decoder
import (
"errors"
"fmt"
"regexp"
"github.com/cloudflare/ebpf_exporter/v2/config"
)
// Regexp is a decoder that only allows inputs matching regexp
type Regexp struct {
cache map[string]*regexp.Regexp
}
// Decode only allows inputs matching regexp
func (r *Regexp) Decode(in []byte, conf config.Decoder) ([]byte, error) {
if conf.Regexps == nil {
return nil, errors.New("no regexps defined in config")
}
if r.cache == nil {
r.cache = map[string]*regexp.Regexp{}
}
for _, expr := range conf.Regexps {
if _, ok := r.cache[expr]; !ok {
compiled, err := regexp.Compile(expr)
if err != nil {
return nil, fmt.Errorf("error compiling regexp %q: %w", expr, err)
}
r.cache[expr] = compiled
}
matches := r.cache[expr].FindSubmatch(in)
// First sub-match if present
if len(matches) == 2 {
return matches[1], nil
}
// General match
if len(matches) == 1 {
return matches[0], nil
}
}
return nil, ErrSkipLabelSet
}