diff options
Diffstat (limited to 'handler.go')
-rw-r--r-- | handler.go | 34 |
1 files changed, 24 insertions, 10 deletions
@@ -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) + }) } } |