Go 的插件化開發:Pingo
Pingo 是一個用來為 Go 程序編寫插件的簡單獨立庫,因為 Go 本身是靜態鏈接的,因此所有插件都以外部進程方式存在。Pingo 旨在簡化標準 RPC 包,支持 TCP 和 Unix 套接字作為通訊協議。當前還不支持遠程插件,如果有需要,遠程插件很快會提供。
使用 Pingo 創建一個插件非常簡單,首先新建目錄,如 "plugins/hello-world" ,然后在該目錄下編寫 main.go:
// Always create a new binary package main import "github.com/dullgiulio/pingo" // Create an object to be exported type MyPlugin struct{} // Exported method, with a RPC signature func (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 main import ( "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) } }
本文由用戶 n342 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!