awesome.soAwesomePlugin
type MyPlugin struct {
Name string
Enable func() error
Disable func() error
}
然后在插件本身你会做这样的事情:
var (
awesomeEnabled bool
)
func AwesomePlugin() *myplugin.MyPlugin {
return &myplugin.MyPlugin{
Name: "AwesomePlugin",
Enable: func() error {
println("Enabling AwesomePlugin")
awesomeEnabled = true
return nil // or do something more complex that could error
},
Disable: func() error {
println("Disabling AwesomePlugin")
awesomeEnabled = false
return nil // or do something more complex that could error
},
}
}
然后代码加载它,打开它,并禁用它会是这样像:
awesomePlugin, err := plugin.Open("awesome.so")
if err != nil {
panic("Can't load plugin: " + err.Error())
}
sym, err := awesomePlugin.Lookup("AwesomePlugin")
if err != nil {
panic("Can't find symbol: " + err.Error())
}
awesomeFactory := sym.(func() *myplugin.MyPlugin)
awesome := awesomeFactory()
println("Loaded " + awesome.Name + " plugin")
err = awesome.Enable()
if err != nil {
panic("Can't enable plugin: " + err.Error())
}
// Do some stuff
err = awesome.Disable()
if err != nil {
panic("Can't enable plugin: " + err.Error())
}
你必须在插件看看代码,看看是否已启用插件或不运行可以定义任何其他功能之前。
然后运行它,我们得到这样的输出:
Loaded AwesomePlugin plugin
Enabling AwesomePlugin
Disabling AwesomePlugin
panic()