aicra/middleware/public.go

111 lines
2.3 KiB
Go
Raw Permalink Normal View History

package middleware
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"plugin"
"strings"
)
// CreateRegistry creates an empty middleware registry
// - if loadDir is set -> load all available middlewares
// inside the local ./middleware folder
2018-07-08 23:34:21 +00:00
func CreateRegistry(loadDir ...string) *Registry {
/* (1) Create registry */
2018-07-08 23:34:21 +00:00
reg := &Registry{
Middlewares: make([]MiddleWare, 0),
}
/* (2) If no default to use -> empty registry */
if len(loadDir) < 1 {
return reg
}
/* (3) List types */
plugins, err := ioutil.ReadDir(loadDir[0])
if err != nil {
log.Fatal(err)
}
/* (4) Else try to load each given default */
for _, file := range plugins {
// ignore non .so files
if !strings.HasSuffix(file.Name(), ".so") {
continue
}
err := reg.add(file.Name())
if err != nil {
log.Fatalf("Cannot load plugin '%s'", file.Name())
}
}
return reg
}
// add adds a middleware to the registry; it must be a
// valid and existing plugin name with or without the .so extension
// it must be located in the relative directory .build/middleware
func (reg *Registry) add(pluginName string) error {
/* (1) Check plugin name */
if len(pluginName) < 1 {
return fmt.Errorf("Plugin name must not be empty")
}
/* (2) Check if valid plugin name */
if strings.ContainsAny(pluginName, "/") {
return fmt.Errorf("'%s' can only be a name, not a path", pluginName)
}
/* (3) Check plugin extension */
if !strings.HasSuffix(pluginName, ".so") {
pluginName = fmt.Sprintf("%s.so", pluginName)
}
/* (4) Try to load the plugin */
p, err := plugin.Open(fmt.Sprintf(".build/middleware/%s", pluginName))
if err != nil {
return err
}
/* (5) Export wanted properties */
inspect, err := p.Lookup("Inspect")
if err != nil {
return fmt.Errorf("Missing method 'Inspect()'; %s", err)
}
/* (6) Cast Inspect */
2018-07-07 21:15:42 +00:00
inspectCast, ok := inspect.(func(http.Request, *Scope))
if !ok {
return fmt.Errorf("Inspect() is malformed")
}
/* (7) Add type to registry */
2018-07-08 23:34:21 +00:00
reg.Middlewares = append(reg.Middlewares, MiddleWare{
Inspect: inspectCast,
})
return nil
}
2018-07-08 23:34:21 +00:00
// Run executes all middlewares (default browse order)
func (reg Registry) Run(req http.Request) Scope {
/* (1) Initialise scope */
scope := Scope{}
/* (2) Execute each middleware */
2018-07-08 23:34:21 +00:00
for _, m := range reg.Middlewares {
2018-07-07 21:15:42 +00:00
m.Inspect(req, &scope)
}
return scope
}