Pingo是一个用来为Go程序编写插件的简单独立库,因为Go本身是静态链接的,因此所有插件都以外部进程方式存在。Pingo旨在简化标准RPC包,支持TCP和Unix套接字作为通讯协议。当前还不支持远程插件,如果有需要,远程插件很快会提供。
使用Pingo创建一个插件非常简单,首先新建目录,如"plugins/hello-world",然后在该目录下编写main.go:
// Always create a new binarypackage mainimport "github.com/dullgiulio/pingo"// Create an object to be exportedtype MyPlugin struct{}// Exported method, with a RPC signaturefunc (p *MyPlugin) SayHello(name string, msg *string) error { *msg = "Hello, " + name return nil}func main() { plugin := &MyPlugin{} // Register the objects to be exported pingo.Register(plugin) // Run the main events handler pingo.Run()}编译:
$ cd plugins/hello-world$ go build接下来就可以调用该插件:
package mainimport ( "log" "github.com/dullgiulio/pingo")func main() { // Make a new plugin from the executable we created. Connect to it via TCP p := pingo.NewPlugin("tcp", "plugins/hello-world/hello-world") // Actually start the plugin p.Start() // Remember to stop the plugin when done using it defer p.Stop() var resp string // 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) }}
评论