test dynfunc package; standardize and refactor api #14

Merged
xdrm-brackets merged 19 commits from test/dynamic into 0.3.0 2020-04-04 10:09:20 +00:00
7 changed files with 29 additions and 47 deletions
Showing only changes of commit b1498e59c1 - Show all commits

View File

@ -1,4 +1,4 @@
package dynamic
package dynfunc
// cerr allows you to create constant "const" error with type boxing.
type cerr string

View File

@ -1,4 +1,4 @@
package dynamic
package dynfunc
import (
"fmt"

View File

@ -1,4 +1,4 @@
package dynamic
package dynfunc
import (
"fmt"

View File

@ -1,4 +1,4 @@
package dynamic
package dynfunc
import (
"errors"

View File

@ -1,4 +1,4 @@
package dynamic
package dynfunc
import "reflect"

View File

@ -1,32 +0,0 @@
package aicra
import (
"fmt"
"strings"
"git.xdrm.io/go/aicra/dynamic"
"git.xdrm.io/go/aicra/internal/config"
)
type handler struct {
Method string
Path string
dynHandler *dynamic.Handler
}
// createHandler builds a handler from its http method and path
// also it checks whether the function signature is valid
func createHandler(method, path string, service config.Service, fn interface{}) (*handler, error) {
method = strings.ToUpper(method)
dynHandler, err := dynamic.Build(fn, service)
if err != nil {
return nil, fmt.Errorf("%s '%s' handler: %w", method, path, err)
}
return &handler{
Path: path,
Method: method,
dynHandler: dynHandler,
}, nil
}

View File

@ -6,13 +6,20 @@ import (
"os"
"git.xdrm.io/go/aicra/datatype"
"git.xdrm.io/go/aicra/dynfunc"
"git.xdrm.io/go/aicra/internal/config"
)
// Server represents an AICRA instance featuring: type checkers, services
type Server struct {
config *config.Server
handlers []*handler
handlers []*apiHandler
}
type apiHandler struct {
Method string
Path string
dynHandler *dynfunc.Handler
}
// New creates a framework instance from a configuration file
@ -48,22 +55,29 @@ func New(configPath string, dtypes ...datatype.T) (*Server, error) {
// Handle sets a new handler for an HTTP method to a path
func (s *Server) Handle(method, path string, fn interface{}) error {
// find associated service
var found *config.Service = nil
for _, service := range s.config.Services {
if method == service.Method && path == service.Pattern {
found = service
var service *config.Service
for _, s := range s.config.Services {
if method == s.Method && path == s.Pattern {
service = s
break
}
}
if found == nil {
return fmt.Errorf("%s '%s': %w", method, path, ErrNoServiceForHandler)
if service == nil {
return fmt.Errorf("%s '%s': %w", method, path, ErrUnknownService)
}
handler, err := createHandler(method, path, *found, fn)
dynHandler, err := dynfunc.Build(fn, *service)
if err != nil {
return err
return fmt.Errorf("%s '%s' handler: %w", method, path, err)
}
s.handlers = append(s.handlers, handler)
s.handlers = append(s.handlers, &apiHandler{
Path: path,
Method: method,
dynHandler: dynHandler,
})
return nil
}