-
Notifications
You must be signed in to change notification settings - Fork 1
/
coprocess_events.go
63 lines (51 loc) · 1.38 KB
/
coprocess_events.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
// +build coprocess
package main
import (
"encoding/json"
"fmt"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/config"
)
// Constant for event system.
const EH_CoProcessHandler apidef.TykEventHandlerName = "cp_dynamic_handler"
type CoProcessEventHandler struct {
methodName string
Spec *APISpec
SpecJSON json.RawMessage
}
type CoProcessEventWrapper struct {
Event config.EventMessage `json:"message"`
Handler string `json:"handler_name"`
SpecJSON *json.RawMessage `json:"spec"`
}
func (l *CoProcessEventHandler) Init(handlerConf interface{}) error {
l.methodName = handlerConf.(map[string]interface{})["name"].(string)
// Set the VM globals
globalVals := JSVMContextGlobal{
APIID: l.Spec.APIID,
OrgID: l.Spec.OrgID,
}
gValAsJSON, err := json.Marshal(globalVals)
if err != nil {
return fmt.Errorf("failed to marshal globals: %v", err)
}
l.SpecJSON = json.RawMessage(gValAsJSON)
return nil
}
func (l *CoProcessEventHandler) HandleEvent(em config.EventMessage) {
if GlobalDispatcher == nil {
return
}
eventWrapper := CoProcessEventWrapper{
Event: em,
Handler: l.methodName,
SpecJSON: &l.SpecJSON,
}
// JSON-encode the event data object
msgAsJSON, err := json.Marshal(eventWrapper)
if err != nil {
log.Error("Failed to encode event data: ", err)
return
}
GlobalDispatcher.DispatchEvent(msgAsJSON)
}