diff options
author | Silvan Jegen <s.jegen@gmail.com> | 2017-01-21 12:34:51 +0100 |
---|---|---|
committer | Silvan Jegen <s.jegen@gmail.com> | 2017-01-21 12:34:51 +0100 |
commit | 2eb6ecf4e9d8040bd2a698dbfa80bcd45b0c371e (patch) | |
tree | 732693efaf7e9c925a79a8cf412ceb2714d98b3c /filter/str | |
parent | 5c24009f2b1fd5a7e5abd4dc33ebdec0c6eaaf25 (diff) |
Use the registry for filter modules as well
Diffstat (limited to 'filter/str')
-rw-r--r-- | filter/str/string.go | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/filter/str/string.go b/filter/str/string.go new file mode 100644 index 0000000..0ae407d --- /dev/null +++ b/filter/str/string.go @@ -0,0 +1,56 @@ +package str + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + + "github.com/Shugyousha/stasher/work" +) + +type StringFilter struct { + FilterFuncMap map[string]func(string) string +} + +func New(ffmap map[string]func(string) string) *StringFilter { + return &StringFilter{FilterFuncMap: ffmap} +} + +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, ff := range f.FilterFuncMap { + str, ok := jm[field] + if !ok { + continue + } + + jm[field] = ff(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 +} |