github.com/anuvu/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/coprocess_events.go (about)

     1  // +build coprocess
     2  
     3  package gateway
     4  
     5  import (
     6  	"encoding/json"
     7  	"fmt"
     8  
     9  	"github.com/TykTechnologies/tyk/apidef"
    10  	"github.com/TykTechnologies/tyk/config"
    11  )
    12  
    13  // Constant for event system.
    14  const EH_CoProcessHandler apidef.TykEventHandlerName = "cp_dynamic_handler"
    15  
    16  type CoProcessEventHandler struct {
    17  	methodName string
    18  	Spec       *APISpec
    19  	SpecJSON   json.RawMessage
    20  }
    21  
    22  type CoProcessEventWrapper struct {
    23  	Event    config.EventMessage `json:"message"`
    24  	Handler  string              `json:"handler_name"`
    25  	SpecJSON *json.RawMessage    `json:"spec"`
    26  }
    27  
    28  func (l *CoProcessEventHandler) Init(handlerConf interface{}) error {
    29  	l.methodName = handlerConf.(map[string]interface{})["name"].(string)
    30  
    31  	// Set the VM globals
    32  	globalVals := JSVMContextGlobal{
    33  		APIID: l.Spec.APIID,
    34  		OrgID: l.Spec.OrgID,
    35  	}
    36  
    37  	gValAsJSON, err := json.Marshal(globalVals)
    38  	if err != nil {
    39  		return fmt.Errorf("failed to marshal globals: %v", err)
    40  	}
    41  
    42  	l.SpecJSON = json.RawMessage(gValAsJSON)
    43  	return nil
    44  }
    45  
    46  func (l *CoProcessEventHandler) HandleEvent(em config.EventMessage) {
    47  	if GlobalDispatcher == nil {
    48  		return
    49  	}
    50  	eventWrapper := CoProcessEventWrapper{
    51  		Event:    em,
    52  		Handler:  l.methodName,
    53  		SpecJSON: &l.SpecJSON,
    54  	}
    55  
    56  	// JSON-encode the event data object
    57  	msgAsJSON, err := json.Marshal(eventWrapper)
    58  	if err != nil {
    59  		log.Error("Failed to encode event data: ", err)
    60  		return
    61  	}
    62  	GlobalDispatcher.DispatchEvent(msgAsJSON)
    63  }