add 'driver.Driver.Name() string' and use it to select the default type/middleware folder (.build/middleware or middleware) | fix driver.Generic.LoadMiddleware() | remove variadic arguments for middleware.CreateRegistry() and checker.CreateRegistry()

This commit is contained in:
Adrien Marquès 2018-09-28 15:58:30 +02:00
parent b957d82a64
commit 9c9079f06b
7 changed files with 55 additions and 51 deletions

View File

@ -10,6 +10,8 @@ import (
"strings"
)
func (d *Generic) Name() string { return "generic" }
// RunController implements the Driver interface
func (d *Generic) RunController(_path []string, _method string) (func(response.Arguments) response.Response, e.Error) {
@ -114,24 +116,23 @@ func (d *Generic) LoadMiddleware(_path string) (func(http.Request, *[]string), e
return
}
output, ok := outputI.(map[string]interface{})
/* (4) Get as []string */
scope, ok := outputI.([]interface{})
if !ok {
fmt.Printf("3\n")
return
}
// extract 'scope' (empty by default or error)
scopeOut, ok := output["scope"]
if !ok {
return
/* (5) Try to add each value to the scope */
for _, v := range scope {
stringScope, ok := v.(string)
if !ok {
fmt.Printf("4\n")
continue
}
*_scope = append(*_scope, stringScope)
}
scope, ok := scopeOut.([]string)
if !ok {
return
}
*_scope = append(*_scope, scope...)
}, nil
}

View File

@ -9,6 +9,8 @@ import (
"strings"
)
func (d *Plugin) Name() string { return "plugin" }
// RunController implements the Driver interface
func (d *Plugin) RunController(_path []string, _method string) (func(response.Arguments) response.Response, err.Error) {

View File

@ -8,6 +8,7 @@ import (
// Driver defines the driver interface to load controller/middleware implementation or executables
type Driver interface {
Name() string
RunController(_path []string, _method string) (func(response.Arguments) response.Response, err.Error)
LoadMiddleware(_path string) (func(http.Request, *[]string), error)
}

View File

@ -1,6 +1,7 @@
package checker
import (
"errors"
"fmt"
"io/ioutil"
"log"
@ -8,29 +9,26 @@ import (
"strings"
)
var ErrNoMatchingType = errors.New("no matching type")
var ErrDoesNotMatch = errors.New("does not match")
var ErrEmptyTypeName = errors.New("type name must not be empty")
// CreateRegistry creates an empty type registry
// - if loadDir is True if will load all available types
// inside the local ./types folder
func CreateRegistry(loadDir ...string) *Registry {
func CreateRegistry(_folder string) *Registry {
/* (1) Create registry */
reg := &Registry{
Types: make([]Type, 0),
}
/* (2) If no default to use -> empty registry */
if len(loadDir) < 1 {
return reg
}
/* (3) List types */
plugins, err := ioutil.ReadDir(loadDir[0])
/* (2) List types */
files, err := ioutil.ReadDir(_folder)
if err != nil {
log.Fatal(err)
}
/* (4) Else try to load each given default */
for _, file := range plugins {
/* (3) Else try to load each given default */
for _, file := range files {
// ignore non .so files
if !strings.HasSuffix(file.Name(), ".so") {
@ -39,7 +37,7 @@ func CreateRegistry(loadDir ...string) *Registry {
err := reg.add(file.Name())
if err != nil {
log.Fatalf("Cannot load plugin '%s'", file.Name())
log.Printf("cannot load plugin '%s'", file.Name())
}
}
@ -54,7 +52,7 @@ func (reg *Registry) add(pluginName string) error {
/* (1) Check plugin name */
if len(pluginName) < 1 {
return fmt.Errorf("Plugin name must not be empty")
return ErrEmptyTypeName
}
/* (2) Check if valid plugin name */
@ -123,12 +121,12 @@ func (reg Registry) Run(typeName string, value interface{}) error {
/* (2) Abort if no matching type */
if T == nil {
return fmt.Errorf("No matching type")
return ErrNoMatchingType
}
/* (3) Check */
if !T.Check(value) {
return fmt.Errorf("Does not match")
return ErrDoesNotMatch
}
return nil

View File

@ -92,9 +92,9 @@ func FetchFormData(req *http.Request) map[string]interface{} {
return res
}
// LoadController tries to load a controller from its uri
// RunController tries to load a controller from its uri
// checks for its given method ('Get', 'Post', 'Put', or 'Delete')
func (i *Request) LoadController(_method string, _driver driver.Driver) (func(response.Arguments) response.Response, err.Error) {
func (i *Request) RunController(_method string, _driver driver.Driver) (func(response.Arguments) response.Response, err.Error) {
return _driver.RunController(i.Path, _method)

View File

@ -9,32 +9,25 @@ import (
)
// CreateRegistry creates an empty middleware registry
// - if loadDir is set -> load all available middlewares
// inside the local ./middleware folder
func CreateRegistry(_driver driver.Driver, loadDir ...string) *Registry {
func CreateRegistry(_driver driver.Driver, _folder string) *Registry {
/* (1) Create registry */
reg := &Registry{
Middlewares: make([]*Wrapper, 0),
}
/* (2) If no default to use -> empty registry */
if len(loadDir) < 1 {
return reg
}
/* (3) List middleware files */
files, err := ioutil.ReadDir(loadDir[0])
/* (2) List middleware files */
files, err := ioutil.ReadDir(_folder)
if err != nil {
log.Fatal(err)
}
/* (4) Else try to load each given default */
/* (3) Else try to load each given default */
for _, file := range files {
mwFunc, err := _driver.LoadMiddleware(path.Join(loadDir[0], file.Name()))
mwFunc, err := _driver.LoadMiddleware(path.Join(_folder, file.Name()))
if err != nil {
log.Printf("Cannot load middleware '%s' | %s", file.Name(), err)
log.Printf("cannot load middleware '%s' | %s", file.Name(), err)
}
reg.Middlewares = append(reg.Middlewares, &Wrapper{Inspect: mwFunc})

View File

@ -1,7 +1,6 @@
package aicra
import (
"errors"
"git.xdrm.io/go/aicra/driver"
e "git.xdrm.io/go/aicra/err"
"git.xdrm.io/go/aicra/internal/checker"
@ -23,14 +22,24 @@ type Server struct {
driver driver.Driver
}
// ErrNilDriver is raised when a NULL driver is given to the constructor
var ErrNilDriver = errors.New("the driver is <nil>")
// New creates a framework instance from a configuration file
// _path is the json configuration path
// _driver is used to load/run the controllers and middlewares (default: )
//
func New(_path string, _driver driver.Driver) (*Server, error) {
/* (1) Default driver : Plugin */
if _driver == nil {
return nil, ErrNilDriver
_driver = &driver.Plugin{}
}
/* (2) Default folders according to drivers */
_folders := make([]string, 0, 2)
_folders = append(_folders, ".build/type")
if _driver.Name() == "plugin" { // plugin
_folders = append(_folders, ".build/middleware")
} else { // generic
_folders = append(_folders, "middleware")
}
/* (1) Init instance */
@ -47,10 +56,10 @@ func New(_path string, _driver driver.Driver) (*Server, error) {
}
/* (3) Default type registry */
i.checker = checker.CreateRegistry(".build/type")
i.checker = checker.CreateRegistry(_folders[0])
/* (4) Default middleware registry */
i.middleware = middleware.CreateRegistry(_driver, ".build/middleware")
i.middleware = middleware.CreateRegistry(_driver, _folders[1])
return i, nil
@ -100,7 +109,7 @@ func (s *Server) ServeHTTP(res http.ResponseWriter, req *http.Request) {
/* (5) Load controller
---------------------------------------------------------*/
controllerImplementation, callErr := apiRequest.LoadController(req.Method, s.driver)
controllerImplementation, callErr := apiRequest.RunController(req.Method, s.driver)
if callErr.Code != e.Success.Code {
httpError(res, callErr)
log.Printf("[err] %s\n", err)