1

我正在尝试使用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])
    }
}

但是我总是在nilym Fstruct 领域。这是我在客户端发送的

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

4

1 回答 1

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/

于 2018-11-01T12:05:29.797 回答