forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoprocess_native.go
67 lines (48 loc) · 1.52 KB
/
coprocess_native.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
// +build coprocess
// +build !grpc
package main
/*
#cgo python CFLAGS: -DENABLE_PYTHON
#include <stdio.h>
#include <stdlib.h>
#include "coprocess/api.h"
#ifdef ENABLE_PYTHON
#include "coprocess/python/dispatcher.h"
#include "coprocess/python/binding.h"
#endif
*/
import "C"
import (
"github.com/golang/protobuf/proto"
"github.com/TykTechnologies/tyk/coprocess"
"encoding/json"
"unsafe"
)
// Dispatch prepares a CoProcessMessage, sends it to the GlobalDispatcher and gets a reply.
func (c *CoProcessor) Dispatch(object *coprocess.Object) (*coprocess.Object, error) {
var objectMsg []byte
switch MessageType {
case coprocess.ProtobufMessage:
objectMsg, _ = proto.Marshal(object)
case coprocess.JsonMessage:
objectMsg, _ = json.Marshal(object)
}
objectMsgStr := string(objectMsg)
CObjectStr := C.CString(objectMsgStr)
objectPtr := (*C.struct_CoProcessMessage)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_CoProcessMessage{}))))
objectPtr.p_data = unsafe.Pointer(CObjectStr)
objectPtr.length = C.int(len(objectMsg))
newObjectPtr := (*C.struct_CoProcessMessage)(GlobalDispatcher.Dispatch(unsafe.Pointer(objectPtr)))
newObjectBytes := C.GoBytes(newObjectPtr.p_data, newObjectPtr.length)
newObject := &coprocess.Object{}
switch MessageType {
case coprocess.ProtobufMessage:
proto.Unmarshal(newObjectBytes, newObject)
case coprocess.JsonMessage:
json.Unmarshal(newObjectBytes, newObject)
}
C.free(unsafe.Pointer(CObjectStr))
C.free(unsafe.Pointer(objectPtr))
C.free(unsafe.Pointer(newObjectPtr))
return newObject, nil
}