74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
|
package otto
|
|||
|
|
|||
|
import (
|
|||
|
"encoding/json"
|
|||
|
"errors"
|
|||
|
"github.com/robertkrimen/otto"
|
|||
|
"rpc_safe_guard_01/pkg/interpreter"
|
|||
|
"rpc_safe_guard_01/pkg/okrpc"
|
|||
|
)
|
|||
|
|
|||
|
const (
|
|||
|
RpcServiceName = "rpcRequest"
|
|||
|
RpcName = "gw"
|
|||
|
ExitName = "exit"
|
|||
|
)
|
|||
|
|
|||
|
var ErrorCodeMap = map[int]string{
|
|||
|
10001: "rpc request error",
|
|||
|
}
|
|||
|
|
|||
|
func InitOtto() {
|
|||
|
// 注册通用方法到otto里
|
|||
|
instance := interpreter.GetInstance()
|
|||
|
err := instance.Set(RpcName, map[string]interface{}{
|
|||
|
RpcServiceName: call,
|
|||
|
ExitName: exit,
|
|||
|
})
|
|||
|
if err != nil {
|
|||
|
panic(err)
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
func call(call otto.FunctionCall) otto.Value {
|
|||
|
if len(call.ArgumentList) != 2 {
|
|||
|
value, _ := otto.ToValue(errors.New("argument invalid"))
|
|||
|
return value
|
|||
|
}
|
|||
|
rpcName := call.Argument(0)
|
|||
|
param := call.Argument(1)
|
|||
|
p, err := param.ToString()
|
|||
|
if err != nil {
|
|||
|
value, _ := otto.ToValue(err)
|
|||
|
return value
|
|||
|
}
|
|||
|
var args []interface{}
|
|||
|
err = json.Unmarshal([]byte(p), &args)
|
|||
|
if err != nil {
|
|||
|
value, _ := otto.ToValue(err)
|
|||
|
return value
|
|||
|
}
|
|||
|
var req okrpc.Request
|
|||
|
req.Class = rpcName.String()
|
|||
|
req.Method = "executeChain"
|
|||
|
req.Args = args
|
|||
|
resp, err := req.SendRpcRequest()
|
|||
|
if err != nil {
|
|||
|
value, _ := otto.ToValue(err)
|
|||
|
return value
|
|||
|
}
|
|||
|
value, _ := otto.ToValue(resp)
|
|||
|
return value
|
|||
|
}
|
|||
|
|
|||
|
func exit(call otto.FunctionCall) otto.Value {
|
|||
|
code, err := call.Argument(0).ToInteger()
|
|||
|
if err != nil {
|
|||
|
value, _ := otto.ToValue(errors.New("the code is not number"))
|
|||
|
return value
|
|||
|
}
|
|||
|
// 此处传入Api Error Code,先用map代替
|
|||
|
value, _ := otto.ToValue(ErrorCodeMap[int(code)])
|
|||
|
return value
|
|||
|
}
|