From 46ad450327111b9d28b592658d75ef57da498298 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Wed, 15 Feb 2023 16:44:29 -0700 Subject: Switch Handler to an interface. HandlerFunc is much better as a function returning a Handler, rather than a newtype for the function type itself. This way there is no confusion creating a type-inferenced variable with HandlerFunc(func(... and then using a HandlerFunc where a Handler is expected. Much better to only have one public type. --- handler.go | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) (limited to 'handler.go') diff --git a/handler.go b/handler.go index a04cd33..7b784ed 100644 --- a/handler.go +++ b/handler.go @@ -2,11 +2,25 @@ package gus import "context" -// Handler is a function which can turn a request into a response. +// Handler is a type which can turn a request into a response. // -// A Handler can return a nil response, in which case the Server is expected +// Handle may return a nil response, in which case the Server is expected // to build the protocol-appropriate "Not Found" response. -type Handler func(context.Context, *Request) *Response +type Handler interface { + Handle(context.Context, *Request) *Response +} + +type handlerFunc func(context.Context, *Request) *Response + +// HandlerFunc is a wrapper to allow using a function as a Handler. +func HandlerFunc(f func(context.Context, *Request) *Response) Handler { + return handlerFunc(f) +} + +// Handle implements Handler. +func (f handlerFunc) Handle(ctx context.Context, request *Request) *Response { + return f(ctx, request) +} // Middleware is a handler decorator. // @@ -19,14 +33,14 @@ type Middleware func(Handler) Handler // The returned handler will invoke each of the passed-in handlers in order, // stopping when it receives a non-nil response. func FallthroughHandler(handlers ...Handler) Handler { - return func(ctx context.Context, request *Request) *Response { + return HandlerFunc(func(ctx context.Context, request *Request) *Response { for _, handler := range handlers { - if response := handler(ctx, request); response != nil { + if response := handler.Handle(ctx, request); response != nil { return response } } return nil - } + }) } // Filter builds a middleware which only calls the wrapped Handler under a condition. @@ -39,14 +53,14 @@ func Filter( failure Handler, ) Middleware { return func(success Handler) Handler { - return func(ctx context.Context, request *Request) *Response { + return HandlerFunc(func(ctx context.Context, request *Request) *Response { if condition(ctx, request) { - return success(ctx, request) + return success.Handle(ctx, request) } if failure == nil { return nil } - return failure(ctx, request) - } + return failure.Handle(ctx, request) + }) } } -- cgit v1.2.3