Skip to content

Instantly share code, notes, and snippets.

@Decision2016
Last active June 9, 2024 13:44
Show Gist options
  • Save Decision2016/2fb0c7a1512adefe4c8ddebf810efd65 to your computer and use it in GitHub Desktop.
Save Decision2016/2fb0c7a1512adefe4c8ddebf810efd65 to your computer and use it in GitHub Desktop.
golang plugin example
plugin:
name: "test"
package main
type IPlugin interface {
Load()
PluginName() string
}
// go build
package main
import (
"fmt"
"github.com/gookit/config/v2"
"github.com/gookit/config/v2/yaml"
"github.com/sirupsen/logrus"
"log"
"plugin"
)
func main() {
LoadGlobalConfig("./config.yml")
p, err := plugin.Open("plugin.so")
if err != nil {
log.Fatal(err)
}
symbol, err := p.Lookup("Instance")
if err != nil {
log.Fatal(err)
}
pl := symbol.(IPlugin)
pl.Load()
fmt.Println(pl.PluginName())
}
func LoadGlobalConfig(filepath string) {
config.WithOptions(config.ParseEnv)
config.AddDriver(yaml.Driver)
err := config.LoadFiles(filepath)
if err != nil {
logrus.WithField("error", err).Errorln("Load config file failed.")
}
}
// go build -buildmode=plugin -o plugin.so plugin.go interface.go
package main
import (
"github.com/gookit/config/v2"
)
type Plugin struct {
name string
}
func (p *Plugin) Load() {
// 测试在外界加载的 config,插件加载后是否可读
p.name = config.String("plugin.name")
}
func (p *Plugin) PluginName() string {
return p.name
}
var Instance Plugin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment