-
Notifications
You must be signed in to change notification settings - Fork 3
/
filter.go
57 lines (52 loc) · 1.48 KB
/
filter.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
package logfrog
import (
"encoding/json"
"errors"
"os"
"github.com/robertkrimen/otto"
)
// Filter func for logEntries
type Filter func(service string, ld *LogData) error
// GetFilter get a filter function with a js file, it has to contain a function filter(service, logData) { }
func GetFilter(file string) (filterFunc Filter, err error) {
fileBytes, errRead := os.ReadFile(file)
if errRead != nil {
err = errRead
return
}
vm := otto.New()
_, errRunFile := vm.Run(string(fileBytes))
if errRunFile != nil {
err = errRunFile
return
}
filterFunc = func(service string, ld *LogData) error {
jsonLogData, errMarshal := json.Marshal(ld)
if errMarshal != nil {
return errMarshal
}
errSetLogData := vm.Set("logData", string(jsonLogData))
if errSetLogData != nil {
return errors.New("could not set logData in filter vm:" + errSetLogData.Error())
}
errSetService := vm.Set("service", service)
if errSetService != nil {
return errors.New("could not set service in filter vm:" + errSetService.Error())
}
res, errRun := vm.Run(`JSON.stringify(filter(JSON.parse(logData), service));`)
if errRun != nil {
return errRun
}
if res.IsString() {
filteredLD := LogData{}
errUnmarshal := json.Unmarshal([]byte(res.String()), &filteredLD)
if errUnmarshal != nil {
return errors.New("could not unmarshal result: " + errUnmarshal.Error())
}
*ld = filteredLD
return nil
}
return errors.New("missing string in filter vm:" + res.String())
}
return
}