Golang RPC 编码自定义函数

标签 go rpc gob

我正在尝试使用 github.com/dullgiulio/pingo 并发送我的自定义结构

type LuaPlugin struct {
    Name string
    List []PluginTable
}

type PluginTable struct {
    Name string
    F lua.LGFunction
}

// LoadPlugins walks over the plugin directory loading all exported plugins
func LoadPlugins() {
    //
    p := pingo.NewPlugin("tcp", "plugins/test")
    // Actually start the plugin
    p.Start()
    // Remember to stop the plugin when done using it
    defer p.Stop()

    gob.Register(&LuaPlugin{})
    gob.Register(&PluginTable{})

    var resp *LuaPlugin

    // Call a function from the object we created previously
    if err := p.Call("MyPlugin.SayHello", "Go developer", &resp); err != nil {
        log.Print(err)
    } else {
        log.Print(resp.List[0])
    }
}

但是,对于 ym 结构的 F 字段,我总是得到 nil。这是我在客户端发送的内容

// Create an object to be exported
type MyPlugin struct{}

// Exported method, with a RPC signature
func (p *MyPlugin) SayHello(name string, msg *util.LuaPlugin) error {
    //

    //
    *msg = util.LuaPlugin{
        Name: "test",
        List: []util.PluginTable{
            {
                Name: "hey",
                F: func(L *lua.LState) int {
                    log.Println(L.ToString(2))
                    return 0
                },
            },
        },
    }
    return nil
}

是否无法通过 RPC 发送自定义数据类型?

最佳答案

不过我不熟悉该库,您可以尝试在传输之前将结构转换为字节 slice 。迟到的回复,可能会对其他人有所帮助....

简单转换:以字节形式返回一个结构

func StructToBytes(s interface{}) (converted []byte, err error) {
    var buff bytes.Buffer
    encoder := gob.NewEncoder(&buff)
    if err = encoder.Encode(s); err != nil {
        return
    }
    converted = buff.Bytes()
    return
}

解码器:返回一个包装器来将字节解码成

func Decoder(rawBytes []byte) (decoder *gob.Decoder) {
    reader := bytes.NewReader(rawBytes)
    decoder = gob.NewDecoder(reader)
    return
}

例子:

type MyStruct struct {
    Name string
}

toEncode := MyStruct{"John Doe"}

// convert the struct to bytes
structBytes, err := StructToBytes(toEncode)
if err != nil {
    panic(err)
}

//-----------
// send over RPC and decode on other side
//-----------

// create a new struct to decode into
var DecodeInto MyStruct

// pass the bytes to the decoder
decoder := Decoder(structBytes)

// Decode into the struct
decoder.Decode(&DecodeInto)

fmt.Println(DecodeInto.Name) // John Doe

由于使用了 gob 包,您可以在一定程度上交换类型和类型转换。

有关更多信息,请参阅:https://golang.org/pkg/encoding/gob/

关于Golang RPC 编码自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030874/

相关文章:

java - protobuf RPC结构(嵌入式ARM)

file - 去。将 []byte 写入文件导致零字节文件

performance - 直接在源码中使用gobs,可以吗?

templates - GoLang 在模板索引中挂起

使用 JSON-RPC 编码数据时出错 - 我是不是很笨?

optimization - 函数调用导致性能下降

Wordpress XML-RPC 和特色图像

bash - 在golang中一起执行bash echo和nc

java - 如何在 Java 中对 Hive 进行异步调用?

go - 如何将 []byte 转换为 *bytes.Buffer