From 334f1fba2177d6af8b324c14d17418eec3b08f86 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Sun, 28 Mar 2021 18:50:04 +0200 Subject: [PATCH] feat: add builder helpers Get(), Post(), Put(), Delete() that proxies to Bind() --- builder.go | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/builder.go b/builder.go index 4e38818..a39c447 100644 --- a/builder.go +++ b/builder.go @@ -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) } }