Introduce PluginLoaderFunc

This allows registered plugins to execute code when loaded. This will
also allow the Lua support code to be a plugin.

Closes: https://todo.sr.ht/~sircmpwn/koushin/54
This commit is contained in:
Simon Ser 2020-01-20 21:37:28 +01:00
parent d19c17c6d5
commit 01983eb7b5
No known key found for this signature in database
GPG key ID: 0FDE7BE0E88F5E48
4 changed files with 26 additions and 8 deletions

View file

@ -23,9 +23,13 @@ type Plugin interface {
Close() error Close() error
} }
var plugins []Plugin // PluginLoaderFunc loads plugins for the provided server.
type PluginLoaderFunc func(*Server) ([]Plugin, error)
// RegisterPlugin registers a plugin to be loaded on server startup. var pluginLoaders []PluginLoaderFunc
func RegisterPlugin(p Plugin) {
plugins = append(plugins, p) // RegisterPluginLoader registers a plugin loader. The loader will be called on
// server start-up and reload.
func RegisterPluginLoader(f PluginLoaderFunc) {
pluginLoaders = append(pluginLoaders, f)
} }

View file

@ -132,3 +132,10 @@ func (p *GoPlugin) Inject(name string, f InjectFunc) {
func (p *GoPlugin) Plugin() Plugin { func (p *GoPlugin) Plugin() Plugin {
return &goPlugin{p} return &goPlugin{p}
} }
// Loader returns a loader function for this plugin.
func (p *GoPlugin) Loader() PluginLoaderFunc {
return func(*Server) ([]Plugin, error) {
return []Plugin{p.Plugin()}, nil
}
}

View file

@ -12,5 +12,5 @@ func init() {
p.TemplateFuncs(templateFuncs) p.TemplateFuncs(templateFuncs)
registerRoutes(&p) registerRoutes(&p)
koushin.RegisterPlugin(p.Plugin()) koushin.RegisterPluginLoader(p.Loader())
} }

View file

@ -176,9 +176,16 @@ func (s *Server) parseSMTPUpstream() error {
} }
func (s *Server) load() error { func (s *Server) load() error {
plugins := append([]Plugin(nil), plugins...) var plugins []Plugin
for _, p := range plugins { for _, load := range pluginLoaders {
s.e.Logger.Printf("Registered plugin '%v'", p.Name()) l, err := load(s)
if err != nil {
return fmt.Errorf("failed to load plugins: %v", err)
}
for _, p := range l {
s.e.Logger.Printf("Loaded plugin %q", p.Name())
}
plugins = append(plugins, l...)
} }
luaPlugins, err := loadAllLuaPlugins(s.e.Logger) luaPlugins, err := loadAllLuaPlugins(s.e.Logger)