This is a creation in Article, where the information may have evolved or changed.
Environment
System: Linux (Don't ask why, because Windows Golang does not support dynamic libraries)
Golang Version: 1.5 support dynamic library, more than 1.8 support plugin
Plug-in code
The plugin code is no different from the normal Golang module code, mainly the package must be main. Here is a simple plug-in code
//testplugin.gopackage mainimport ( "fmt")func init() { fmt.Println("world") //我们还可以做其他更高阶的事情,比如 platform.RegisterPlugin({"func": Hello}) 之类的,向插件平台自动注册该插件的函数}func Hello() { fmt.Println("hello")}
The purpose of the INIT function is to automate some of the things we do when the plug-in module is loaded, such as automatically registering methods and types with the plugin platform, output plugin information, and so on.
The Hello function is the symbol we need to find in the call callers
Compile command
go build -buildmode=plugin testplugin.go
After compiling we can see that there is a testplugin.so file in the current directory
We can also generate different versions of plugins by using a command similar to the following
go build -o testplugin_v1.so -buildmode=plugin testplugin.go
If you want to better control the version of the plug-in, want to do more cool things, such as: Hot update plug-in. Then you can use the automatic registration method, the new version of the plug-in loading, automatically register the plug-in version number, plug-in platform priority to use the new version of the approach.
Use
The user needs to introduce plugin this package
//main.gopackage mainimport ( "plugin")func main() { p, err := plugin.Open("testplugin.so") ifnil { panic(err) } f, err := p.Lookup("Hello") ifnil { panic(err) } f.(func())()}
Output
go run main.go worldhello
We can see that we only explicitly invoke the Hello method in the plugin, print the Hello string, but before calling Hello, we have already exported the world, which is exactly what the plugin init function does.
Summarize
The Golang support plug-in allows the extensibility of the Golang program to go up to another level, which can be used to do something cooler, such as hot updates that use plugins to do the service