-
Notifications
You must be signed in to change notification settings - Fork 5
/
handler.go
79 lines (67 loc) · 1.99 KB
/
handler.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
package floop
import (
"github.com/d3sw/floop/types"
"github.com/persephony/shml"
)
// Handler represents the event handler interface.
type Handler interface {
// raw event and config after interpolation
Handle(event *types.Event, conf *types.HandlerConfig) (map[string]interface{}, error)
Init(conf *types.HandlerConfig) error
CloseConnection() error
}
// phaseHandler is the internal handler wrapping the config and handler interfaces
type phaseHandler struct {
conf *types.HandlerConfig
Handler
}
func (handler *phaseHandler) buildConfig(event *types.Event) (*types.HandlerConfig, error) {
// Clone existing config
conf := handler.conf.Clone()
// Interpolate Body
bodyTmpl := shml.New()
bodyTmpl.Parse([]byte(conf.Body))
out, err := bodyTmpl.Execute(event)
if err != nil {
return nil, err
}
conf.Body = string(out)
// Interpolate URI
if handler.conf.URI == "" {
return conf, nil
}
uriTmpl := shml.New()
uriTmpl.Parse([]byte(handler.conf.URI))
if out, err = uriTmpl.Execute(event); err != nil {
return nil, err
}
conf.URI = string(out)
return conf, nil
}
func (handler *phaseHandler) Handle(event *types.Event) (map[string]interface{}, error) {
// Apply transform to the event data before calling the handler. It is only applied if the
// data is a byte slice.
if len(handler.conf.Transform) > 0 {
if data, ok := event.Data.([]byte); ok {
if _, err := Transform(handler.conf.Transform, data, event); err != nil {
return nil, err
}
} else if data, ok := event.Data.(*types.ChildResult); ok {
if len(data.Stderr) > 0 || len(data.Stdout) > 0 {
if _, err := TransformResult(handler.conf.Transform, data, event); err != nil {
return nil, err
}
}
}
}
// Build a normalized config to pass to the handler
conf, err := handler.buildConfig(event)
if err != nil {
return nil, err
}
// Call user defined handler
return handler.Handler.Handle(event, conf)
}
func (handler *phaseHandler) CloseConnection() error {
return handler.Handler.CloseConnection()
}