问题描述
go1.8及更高版本,go支持创建和加载插件.
go1.8 onwards, go supports to create and load a plugin.
但不支持卸载插件.
插件是在运行时加载的模块,是否可以卸载模块?
a plugin is a module loaded at runtime, is it possible to unload a module?
如果无法卸载模块,那么在应用程序级别上卸载插件/使其无法使用但仍在内存中的最佳方法是什么?
if not possible to unload a module, what is the best that can be done at application level to unload a plugin/make it unusable but still in memory?
推荐答案
awesome.so AwesomePlugin
awesome.soAwesomePlugin
type MyPlugin struct {
Name string
Enable func() error
Disable func() error
}
然后在插件本身中,您将执行以下操作:
Then in the plugin itself you'd do something like this:
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
},
}
}
然后加载,启用和禁用它的代码将类似于:
Then the code to load it, enable it, and disable it would be something like:
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())
}
在运行您可能定义的任何其他功能之前,您将使插件中的代码看起来是否启用了插件.
You'd have the code in the plugin look to see if the plugin is enabled or not before running any other functions you might define.
然后,运行它,我们得到如下输出:
Then, running it, we get output like:
Loaded AwesomePlugin plugin
Enabling AwesomePlugin
Disabling AwesomePlugin
panic()
panic()
这篇关于golang:如何卸载已经加载的"go plugin"1.8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!