package str import ( "bytes" "encoding/json" "fmt" "io" "os" "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 { field := strings.Replace(field, "\"", "", -1) repl := strings.Replace(repl, "\"", "", -1) 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.Fprintf(os.Stderr, "EOF jm: %v\n", jm) return w } if err != nil { fmt.Fprintf(os.Stderr, "Error when decoding JSON: %q\n", err) w.SetError(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.Fprintf(os.Stderr, "Error when marshaling JSON: %q\n", err) w.SetError(err) } else { w.Data = bs } } return w }