47 lines
1.4 KiB
Go
47 lines
1.4 KiB
Go
// Package middleware contains a simple plugin system for Fiber middleware.
|
|
// Register plugins by name and factory, then main.go will load them automatically.
|
|
package middleware
|
|
|
|
import (
|
|
"path/filepath"
|
|
|
|
"github.com/BurntSushi/toml"
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
// Plugin holds a plugin's name and a function that makes its handler.
|
|
type Plugin struct {
|
|
Name string
|
|
Factory func() fiber.Handler
|
|
}
|
|
|
|
// registry stores every plugin we've registered.
|
|
var registry []Plugin
|
|
|
|
// RegisterPlugin tags a plugin with a name and a factory so we can use it in the app.
|
|
func RegisterPlugin(name string, factory func() fiber.Handler) {
|
|
registry = append(registry, Plugin{Name: name, Factory: factory})
|
|
}
|
|
|
|
// LoadPlugins returns the handler functions for each plugin.
|
|
// If skipCheckpoint is true, it skips the plugin named "checkpoint".
|
|
func LoadPlugins(skipCheckpoint bool) []fiber.Handler {
|
|
var handlers []fiber.Handler
|
|
for _, p := range registry {
|
|
if skipCheckpoint && p.Name == "checkpoint" {
|
|
continue
|
|
}
|
|
handlers = append(handlers, p.Factory())
|
|
}
|
|
return handlers
|
|
}
|
|
|
|
// LoadConfig loads the TOML file at middleware/config/[name].toml
|
|
// and decodes it into the struct you provide.
|
|
func LoadConfig(name string, v interface{}) error {
|
|
path := filepath.Join("middleware", "config", name+".toml")
|
|
if _, err := toml.DecodeFile(path, v); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|