handler.go
938 字节
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
package handler
import (
jsoniter "github.com/json-iterator/go"
"github.com/tal-tech/go-stash/stash/es"
"github.com/tal-tech/go-stash/stash/filter"
)
type MessageHandler struct {
writer *es.Writer
indexer *es.Index
filters []filter.FilterFunc
}
func NewHandler(writer *es.Writer, indexer *es.Index) *MessageHandler {
return &MessageHandler{
writer: writer,
indexer: indexer,
}
}
func (mh *MessageHandler) AddFilters(filters ...filter.FilterFunc) {
for _, f := range filters {
mh.filters = append(mh.filters, f)
}
}
func (mh *MessageHandler) Consume(_, val string) error {
m := make(map[string]interface{})
if err := jsoniter.Unmarshal([]byte(val), &m); err != nil {
return err
}
index := mh.indexer.GetIndex(m)
for _, proc := range mh.filters {
if m = proc(m); m == nil {
return nil
}
}
bs, err := jsoniter.Marshal(m)
if err != nil {
return err
}
return mh.writer.Write(index, string(bs))
}