blob: c3e221342557959098e2a95c3eb13430cca3685c (
plain)
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
|
package str
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/Shugyousha/stasher/filter"
"github.com/Shugyousha/stasher/registry"
"github.com/Shugyousha/stasher/work"
)
func init() {
registry.Filterregistry["string"] = New
}
type Replacer interface {
Replace(string) string
}
type StringFilter struct {
FilterFuncMap map[string]Replacer
}
func New(kv map[string]string) filter.Filter {
replmap := make(map[string]Replacer, len(kv))
for field, repl := range kv {
replmap[field] = strings.NewReplacer(strings.Split(repl, "/")...)
}
return &StringFilter{FilterFuncMap: replmap}
}
func (f *StringFilter) Filter(w *work.Work) *work.Work {
dec := json.NewDecoder(bytes.NewReader(w.Data))
jm := make(map[string]string, 10)
err := dec.Decode(&jm)
if err == io.EOF {
fmt.Printf("EOF jm: %v\n", jm)
return w
}
if err != nil {
fmt.Printf("Error when decoding JSON: %q\n", err)
w.Err = err
return w
}
changed := false
for field, repl := range f.FilterFuncMap {
str, ok := jm[field]
if !ok {
continue
}
jm[field] = repl.Replace(str)
changed = true
}
if changed {
bs, err := json.Marshal(jm)
if err != nil {
fmt.Printf("Error when marshalling JSON: %q\n", err)
w.Err = err
} else {
w.Data = bs
}
}
return w
}
|