-
Notifications
You must be signed in to change notification settings - Fork 111
/
mask.go
94 lines (84 loc) · 2.27 KB
/
mask.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package library
import (
"github.com/nytlabs/streamtools/st/blocks" // blocks
)
// specify those channels we're going to use to communicate with streamtools
type Mask struct {
blocks.Block
queryrule chan chan interface{}
inrule chan interface{}
in chan interface{}
out chan interface{}
quit chan interface{}
}
// a bit of boilerplate for streamtools
func NewMask() blocks.BlockInterface {
return &Mask{}
}
func (b *Mask) Setup() {
b.Kind = "Mask"
b.Desc = "emits a subset of the inbound message by specifying the desired JSON output structure in this block's rule"
b.in = b.InRoute("in")
b.inrule = b.InRoute("rule")
b.queryrule = b.QueryRoute("rule")
b.quit = b.Quit()
b.out = b.Broadcast()
}
func maskJSON(maskMap map[string]interface{}, input map[string]interface{}) map[string]interface{} {
t := make(map[string]interface{})
if len(maskMap) == 0 {
return input
}
for k, _ := range maskMap {
val, ok := input[k]
if ok {
switch v := val.(type) {
case map[string]interface{}:
maskNext, ok := maskMap[k].(map[string]interface{})
if ok {
t[k] = maskJSON(maskNext, v)
} else {
t[k] = v
}
default:
t[k] = val
}
}
}
return t
}
// Mask modifies a JSON stream with an additive key filter. Mask uses the JSON
// object recieved through the rule channel to determine which keys should be
// included in the resulting object. An empty JSON object ({}) is used as the
// notation to include all values for a key.
//
// For instance, if the JSON rule is:
// {"a":{}, "b":{"d":{}},"x":{}}
// And an incoming message looks like:
// {"a":24, "b":{"c":"test", "d":[1,3,4]}, "f":5, "x":{"y":5, "z":10}}
// The resulting object after the application of Mask would be:
// {"a":24, "b":{"d":[1,3,4]}, "x":{"y":5, "z":10}}
func (b *Mask) Run() {
mask := make(map[string]interface{})
for {
select {
case ruleI := <-b.inrule:
rule := ruleI.(map[string]interface{})
if tmp, ok := rule["Mask"].(map[string]interface{}); ok {
mask = tmp
}
case c := <-b.queryrule:
c <- map[string]interface{}{
"Mask": mask,
}
case msg := <-b.in:
msgMap, msgOk := msg.(map[string]interface{})
if msgOk {
b.out <- maskJSON(mask, msgMap)
}
case <-b.quit:
// quit the block
return
}
}
}