-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdumbcollector.go
54 lines (46 loc) · 1.09 KB
/
dumbcollector.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
package libphonelabgo
import (
"encoding/json"
"fmt"
phonelab "github.com/shaseley/phonelab-go"
"io/ioutil"
"os"
"sync"
)
type DumbCollector struct {
Data []interface{}
CheckFunc func(interface{}) bool
PersistOnFinish bool
Filename string
sync.Mutex
}
func NewDumbCollector() *DumbCollector {
return &DumbCollector{
Data: make([]interface{}, 0),
}
}
func (dc *DumbCollector) OnData(data interface{}, info phonelab.PipelineSourceInfo) {
dc.Lock()
defer dc.Unlock()
if dc.CheckFunc == nil || dc.CheckFunc(data) {
dc.Data = append(dc.Data, data)
}
}
func (dc *DumbCollector) Finish() {
if dc.PersistOnFinish {
if err := dc.DumpJson(dc.Filename); err != nil {
fmt.Fprintf(os.Stderr, "Error persisting data: %v\n", err)
}
}
}
func (dc *DumbCollector) DumpJson(outFile string) error {
outputBytes, err := json.MarshalIndent(dc.Data, "", "\t")
if err != nil {
return fmt.Errorf("Error marshalling data: %v", err)
} else if len(outFile) == 0 {
fmt.Println(string(outputBytes))
} else {
return ioutil.WriteFile(outFile, outputBytes, 0644)
}
return nil
}