Golang RPC编码自定义功能

时间:2017-03-26 15:46:48

标签: 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])
    }
}

但是,我总是得到nil ym struct的F字段。这是我在客户端上发送的内容

// 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发送自定义数据类型?

1 个答案:

答案 0 :(得分:0)

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

简单转换:以字节为单位返回结构

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/