From b957d82a6469cb357511bb97967f8c5a7d54d0c9 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Fri, 28 Sep 2018 11:08:44 +0200 Subject: [PATCH] implement driver.Generic.LoadMiddleware() [TODO] test it --- driver/generic.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++ driver/plugin.go | 5 ++--- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/driver/generic.go b/driver/generic.go index bbb8b6c..0b31100 100644 --- a/driver/generic.go +++ b/driver/generic.go @@ -5,6 +5,7 @@ import ( "fmt" e "git.xdrm.io/go/aicra/err" "git.xdrm.io/go/aicra/response" + "net/http" "os/exec" "strings" ) @@ -79,3 +80,58 @@ func (d *Generic) RunController(_path []string, _method string) (func(response.A }, e.Success } + +// LoadMiddleware returns a new middleware function; it must be a +// valid and existing folder/filename file +func (d *Generic) LoadMiddleware(_path string) (func(http.Request, *[]string), error) { + + /* (1) Check plugin name */ + if len(_path) < 1 { + return nil, fmt.Errorf("Middleware name must not be empty") + } + + /* (2) Create method + error */ + return func(_req http.Request, _scope *[]string) { + + /* (1) Prepare stdin data */ + stdin, err := json.Marshal(_scope) + if err != nil { + return + } + + /* (2) Try to load command with -> stdout */ + cmd := exec.Command(_path, string(stdin)) + + stdout, err := cmd.Output() + if err != nil { + return + } + + /* (3) Get output json */ + var outputI interface{} + err = json.Unmarshal(stdout, &outputI) + if err != nil { + return + } + + output, ok := outputI.(map[string]interface{}) + if !ok { + return + } + + // extract 'scope' (empty by default or error) + scopeOut, ok := output["scope"] + if !ok { + return + } + + scope, ok := scopeOut.([]string) + if !ok { + return + } + + *_scope = append(*_scope, scope...) + + }, nil + +} diff --git a/driver/plugin.go b/driver/plugin.go index 37d4967..1d0a5c3 100644 --- a/driver/plugin.go +++ b/driver/plugin.go @@ -47,8 +47,7 @@ func (d *Plugin) RunController(_path []string, _method string) (func(response.Ar } // LoadMiddleware returns a new middleware function; it must be a -// valid and existing folder/filename file with or without the .so extension -// it must be located in the relative directory .build/middleware +// valid and existing folder/filename file with the .so extension func (d *Plugin) LoadMiddleware(_path string) (func(http.Request, *[]string), error) { // ignore non .so files @@ -58,7 +57,7 @@ func (d *Plugin) LoadMiddleware(_path string) (func(http.Request, *[]string), er /* (1) Check plugin name */ if len(_path) < 1 { - return nil, fmt.Errorf("Plugin name must not be empty") + return nil, fmt.Errorf("Middleware name must not be empty") } /* (2) Check plugin extension */