-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathshamoji.go
70 lines (57 loc) · 1.16 KB
/
shamoji.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
package shamoji
import (
"context"
"errors"
"golang.org/x/sync/errgroup"
)
type (
// Tokenizer implements Tokenize method.
Tokenizer interface {
Tokenize(sentence string) (tokens [][]byte)
}
// Filter implements Test method.
Filter interface {
Test(src []byte) (result bool)
}
// Serve has Tokenizer and Filter interfaces.
Serve struct {
Tokenizer Tokenizer
Filer Filter
}
)
// Do filtering sentence.
func (s *Serve) Do(sentence string) (bool, string) {
ts := s.Tokenizer.Tokenize(sentence)
if len(ts) == 0 {
return false, ""
}
for i := range ts {
if s.Filer.Test(ts[i]) {
return true, string(ts[i])
}
}
return false, ""
}
// DoAsync filtering sentence.
func (s *Serve) DoAsync(ctx context.Context, sentence string) (bool, string) {
ts := s.Tokenizer.Tokenize(sentence)
if len(ts) == 0 {
return false, ""
}
eg, _ := errgroup.WithContext(ctx)
for i := range ts {
i := i
eg.Go(func() error {
if s.Filer.Test(ts[i]) {
// define found error type...
//nolint: goerr113
return errors.New(string(ts[i]))
}
return nil
})
}
if err := eg.Wait(); err != nil {
return true, err.Error()
}
return false, ""
}