background
When I was doing C language development, in order to make the program have better expansibility, I usually chose to implement the functions to be expanded as plug-ins and import the functions in plug-ins by loading so files. When I was learning Golang, I wished there was a plugin like this. Finally, Golang has plug-in support in version 1.8. I wrote an open source library to support hot update plugins. The code address is at the end of the article.
The environment
System: Linux (don’t ask why, because under Windows Golang does not support dynamic library) Golang version: 1.5 support dynamic library, 1.8 support plugin
The plug-in code
The plugin code is no different from regular Golang module code, except that the package must be main. Here is a simple plug-in code
//testplugin.go
package main
import (
"fmt"
)
func init(a) {
fmt.Println("world")
// We can also do higher-level things like platform.registerPlugin ({"func": Hello}), which automatically registers the plugin's functions with the plugin platform
}
func Hello(a) {
fmt.Println("hello")}Copy the code
The purpose of the init function is to automatically do some of the things we need to do when the plug-in module is loaded, such as automatically registering methods and types with the plug-in platform, output plug-in information, and so on.
The Hello function is the symbol we need to look up explicitly on the caller
Compile command
go build -buildmode=plugin testplugin.go
Copy the code
After compiling, we can see that there is a testplugin.so file in the current directory. We can also generate different versions of the plug-in by using commands like the following
go build -o testplugin_v1.so -buildmode=plugin testplugin.go
Copy the code
If you want more control over the version of your plugin, you want to do something cool, like hot update your plugin. So you can use the way of automatic registration, the new version of plug-in loading, automatic registration of plug-in version number, plug-in platform in the use of the new version of the method.
use
Users need to import the plugin package
//main.go
package main
import (
"plugin"
)
func main(a) {
p, err := plugin.Open("testplugin.so")
iferr ! =nil {
panic(err)
}
f, err := p.Lookup("Hello")
iferr ! =nil {
panic(err)
}
f.(func(a))(a)
}
Copy the code
The output
$ go run main.go
world
hello
Copy the code
As you can see, we just explicitly called the Hello method in the plug-in, printing the string Hello, but before calling Hello, we already printed the world, which is exactly what the plug-in init function does.
conclusion
Golang support for plug-ins takes the extensibility of Golang applications to the next level and can be used to do cool things like hot updates to services using plug-ins
Code: github.com/letiantech/…
Recommend the article
How to use Go to create a ten-million-level flow second kill system