Basic plugin system with centralized registry

This commit is contained in:
2020-11-17 09:19:15 +01:00
parent fe90d81b5d
commit ad5c02bd80
13 changed files with 333 additions and 1 deletions

1
example/pluggable/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/bin

View File

@ -0,0 +1,11 @@
build: extension
go build -o ./bin/app ./
extension:
go build -o ./bin/myplugin.so -buildmode=plugin ./myplugin
watch:
modd
run:
./bin/app

View File

@ -0,0 +1,5 @@
package hook
type Initializable interface {
HookInit() error
}

44
example/pluggable/main.go Normal file
View File

@ -0,0 +1,44 @@
package main
import (
"context"
"log"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/example/pluggable/hook"
"gitlab.com/wpetit/goweb/plugin"
)
func main() {
reg := plugin.NewRegistry()
ctx := context.Background()
_, err := reg.LoadAll(ctx, "./bin/*.so")
if err != nil {
log.Fatal(errors.WithStack(err))
}
for _, ext := range reg.Plugins() {
log.Printf("Loaded plugin '%s', version '%s'", ext.PluginName(), ext.PluginVersion())
}
// Iterate over plugins
err = reg.Each(func(p plugin.Plugin) error {
h, ok := p.(hook.Initializable)
if !ok {
// Skip non initializable plugins
return nil
}
// Initialize plugin
if err := h.HookInit(); err != nil {
return errors.WithStack(err)
}
return nil
})
if err != nil {
log.Fatal(errors.WithStack(err))
}
}

View File

@ -0,0 +1,6 @@
**/*.go
modd.conf
Makefile {
prep: make build
prep: make run
}

View File

@ -0,0 +1,11 @@
package main
import (
"context"
"gitlab.com/wpetit/goweb/plugin"
)
func RegisterPlugin(ctx context.Context) (plugin.Plugin, error) {
return &MyPlugin{}, nil
}

View File

@ -0,0 +1,19 @@
package main
import "log"
type MyPlugin struct{}
func (e *MyPlugin) PluginName() string {
return "my.plugin"
}
func (e *MyPlugin) PluginVersion() string {
return "0.0.0"
}
func (e *MyPlugin) HookInit() error {
log.Println("MyPlugin initialized !")
return nil
}