feat: add builder helpers Get(), Post(), Put(), Delete() that proxies to Bind()

This commit is contained in:
Adrien Marquès 2021-03-28 18:50:04 +02:00
parent 6039fbb41f
commit 334f1fba21
Signed by: xdrm-brackets
GPG Key ID: D75243CA236D825E
1 changed files with 28 additions and 8 deletions

View File

@ -16,7 +16,7 @@ type Builder struct {
handlers []*apiHandler
}
// represents an server handler
// represents an api handler (method-pattern combination)
type apiHandler struct {
Method string
Path string
@ -34,7 +34,7 @@ func (b *Builder) AddType(t datatype.T) {
b.conf.Types = append(b.conf.Types, t)
}
// Setup the builder with its api definition
// Setup the builder with its api definition file
// panics if already setup
func (b *Builder) Setup(r io.Reader) error {
if b.conf == nil {
@ -46,13 +46,13 @@ func (b *Builder) Setup(r io.Reader) error {
return b.conf.Parse(r)
}
// Bind a dynamic handler to a REST service
// Bind a dynamic handler to a REST service (method and pattern)
func (b *Builder) Bind(method, path string, fn interface{}) error {
if b.conf.Services == nil {
return errNotSetup
}
// find associated service
// find associated service from config
var service *config.Service
for _, s := range b.conf.Services {
if method == s.Method && path == s.Pattern {
@ -65,7 +65,7 @@ func (b *Builder) Bind(method, path string, fn interface{}) error {
return fmt.Errorf("%s '%s': %w", method, path, errUnknownService)
}
dyn, err := dynfunc.Build(fn, *service)
var dyn, err = dynfunc.Build(fn, *service)
if err != nil {
return fmt.Errorf("%s '%s' handler: %w", method, path, err)
}
@ -79,18 +79,38 @@ func (b *Builder) Bind(method, path string, fn interface{}) error {
return nil
}
// Get is equivalent to Bind(http.MethodGet)
func (b *Builder) Get(path string, fn interface{}) error {
return b.Bind(http.MethodGet, path, fn)
}
// Post is equivalent to Bind(http.MethodPost)
func (b *Builder) Post(path string, fn interface{}) error {
return b.Bind(http.MethodPost, path, fn)
}
// Put is equivalent to Bind(http.MethodPut)
func (b *Builder) Put(path string, fn interface{}) error {
return b.Bind(http.MethodPut, path, fn)
}
// Delete is equivalent to Bind(http.MethodDelete)
func (b *Builder) Delete(path string, fn interface{}) error {
return b.Bind(http.MethodDelete, path, fn)
}
// Build a fully-featured HTTP server
func (b Builder) Build() (http.Handler, error) {
for _, service := range b.conf.Services {
var hasAssociatedHandler bool
var isHandled bool
for _, handler := range b.handlers {
if handler.Method == service.Method && handler.Path == service.Pattern {
hasAssociatedHandler = true
isHandled = true
break
}
}
if !hasAssociatedHandler {
if !isHandled {
return nil, fmt.Errorf("%s '%s': %w", service.Method, service.Pattern, errMissingHandler)
}
}