Last active
June 9, 2024 13:44
-
-
Save Decision2016/2fb0c7a1512adefe4c8ddebf810efd65 to your computer and use it in GitHub Desktop.
golang plugin example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
plugin: | |
name: "test" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
type IPlugin interface { | |
Load() | |
PluginName() string | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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