Pingo —— Go 语言的插件化开发包

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)
    }
}

文章转载自 开源中国社区 [http://www.oschina.net]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值