forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coprocess_events.go
70 lines (56 loc) · 1.56 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
64
65
66
67
68
69
70
// +build coprocess
package main
import (
"github.com/TykTechnologies/tykcommon"
// "fmt"
"encoding/json"
)
// Constant for event system.
const (
EH_CoProcessHandler tykcommon.TykEventHandlerName = "cp_dynamic_handler"
)
type CoProcessEventHandler struct {
conf map[string]interface{}
Spec *APISpec
SpecJSON json.RawMessage
}
type CoProcessEventWrapper struct {
Event EventMessage `json:"message"`
Handler string `json:"handler_name"`
SpecJSON *json.RawMessage `json:"spec"`
}
func (l CoProcessEventHandler) New(handlerConf interface{}) (TykEventHandler, error) {
thisHandler := CoProcessEventHandler{}
thisHandler.Spec = l.Spec
thisHandler.conf = handlerConf.(map[string]interface{})
// Set the VM globals
globalVals := JSVMContextGlobal{
APIID: l.Spec.APIID,
OrgID: l.Spec.OrgID,
}
gValAsJSON, gErr := json.Marshal(globalVals)
if gErr != nil {
log.Error("Failed to marshal globals! ", gErr)
}
// thisHandler.SpecJSON = string(gValAsJSON)
thisHandler.SpecJSON = json.RawMessage(gValAsJSON)
return thisHandler, nil
}
func (l CoProcessEventHandler) HandleEvent(em EventMessage) {
// 1. Get the methodName for the Event Handler
methodName := l.conf["name"].(string)
eventWrapper := CoProcessEventWrapper{
Event: em,
Handler: methodName,
SpecJSON: &l.SpecJSON,
}
// 2. JSON-encode the event data object
msgAsJSON, encErr := json.Marshal(eventWrapper)
if encErr != nil {
log.Error("Failed to encode event data: ", encErr)
return
}
if GlobalDispatcher != nil {
GlobalDispatcher.DispatchEvent(msgAsJSON)
}
}