2018-07-07 20:10:56 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2018-09-28 08:54:13 +00:00
|
|
|
"git.xdrm.io/go/aicra/driver"
|
2018-07-07 20:10:56 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2018-09-28 08:54:13 +00:00
|
|
|
"path"
|
2018-07-07 20:10:56 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// CreateRegistry creates an empty middleware registry
|
2018-09-28 13:58:30 +00:00
|
|
|
func CreateRegistry(_driver driver.Driver, _folder string) *Registry {
|
2018-07-07 20:10:56 +00:00
|
|
|
|
|
|
|
/* (1) Create registry */
|
2018-07-08 23:34:21 +00:00
|
|
|
reg := &Registry{
|
2018-09-28 08:54:13 +00:00
|
|
|
Middlewares: make([]*Wrapper, 0),
|
2018-07-07 20:10:56 +00:00
|
|
|
}
|
|
|
|
|
2018-09-28 13:58:30 +00:00
|
|
|
/* (2) List middleware files */
|
|
|
|
files, err := ioutil.ReadDir(_folder)
|
2018-07-07 20:10:56 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2018-09-28 13:58:30 +00:00
|
|
|
/* (3) Else try to load each given default */
|
2018-09-28 08:54:13 +00:00
|
|
|
for _, file := range files {
|
2018-07-07 20:10:56 +00:00
|
|
|
|
2018-09-28 13:58:30 +00:00
|
|
|
mwFunc, err := _driver.LoadMiddleware(path.Join(_folder, file.Name()))
|
2018-07-07 20:10:56 +00:00
|
|
|
if err != nil {
|
2018-09-28 13:58:30 +00:00
|
|
|
log.Printf("cannot load middleware '%s' | %s", file.Name(), err)
|
2018-07-07 20:10:56 +00:00
|
|
|
}
|
2018-09-28 08:54:13 +00:00
|
|
|
reg.Middlewares = append(reg.Middlewares, &Wrapper{Inspect: mwFunc})
|
2018-07-07 20:10:56 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return reg
|
|
|
|
}
|
|
|
|
|
2018-07-08 23:34:21 +00:00
|
|
|
// Run executes all middlewares (default browse order)
|
2018-09-28 08:54:13 +00:00
|
|
|
func (reg Registry) Run(req http.Request) []string {
|
2018-07-07 20:10:56 +00:00
|
|
|
|
|
|
|
/* (1) Initialise scope */
|
2018-09-28 08:54:13 +00:00
|
|
|
scope := make([]string, 0)
|
2018-07-07 20:10:56 +00:00
|
|
|
|
|
|
|
/* (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)
|
2018-07-07 20:10:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return scope
|
|
|
|
|
|
|
|
}
|