summaryrefslogtreecommitdiff
path: root/handler.go
diff options
context:
space:
mode:
authortjpcc <tjp@ctrl-c.club>2023-02-15 16:44:29 -0700
committertjpcc <tjp@ctrl-c.club>2023-02-15 16:44:29 -0700
commit46ad450327111b9d28b592658d75ef57da498298 (patch)
tree2b837bac9ae36d5a34dda06ba745850da216257d /handler.go
parentbc96af40db6104580c22086c8db7c8119a404257 (diff)
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.
Diffstat (limited to 'handler.go')
-rw-r--r--handler.go34
1 files changed, 24 insertions, 10 deletions
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)
+ })
}
}