summaryrefslogtreecommitdiff
path: root/gemini/handler.go
diff options
context:
space:
mode:
authortjpcc <tjp@ctrl-c.club>2023-01-11 10:36:56 -0700
committertjpcc <tjp@ctrl-c.club>2023-01-11 10:36:56 -0700
commite183f9cd23380a81071c32f64c91e60f46a7d8cb (patch)
treed78b0a4936dee3e3201d97668bfb5de4492b3593 /gemini/handler.go
parent197d8e4cb0170356dd20755efcf1d336c4c38583 (diff)
lots more documentation comments
Diffstat (limited to 'gemini/handler.go')
-rw-r--r--gemini/handler.go29
1 files changed, 27 insertions, 2 deletions
diff --git a/gemini/handler.go b/gemini/handler.go
index ded77a5..0f48e62 100644
--- a/gemini/handler.go
+++ b/gemini/handler.go
@@ -6,7 +6,7 @@ import "context"
//
// A Handler MUST NOT return a nil response. Errors should be returned in the form
// of error responses (4x, 5x, 6x response status). If the Handler should not be
-// responsible for the requested resource it can return a "51 Not Found" response.
+// responsible for the requested resource it can return a 51 response.
type Handler func(context.Context, *Request) *Response
// Middleware is a handle decorator.
@@ -15,7 +15,11 @@ type Handler func(context.Context, *Request) *Response
// transform the request or response in some way.
type Middleware func(Handler) Handler
-func Fallthrough(handlers ...Handler) Handler {
+// FallthroughHandler builds a handler which tries multiple child handlers.
+//
+// The returned handler will invoke each of the passed child handlers in order,
+// stopping when it receives a response with status other than 51.
+func FallthroughHandler(handlers ...Handler) Handler {
return func(ctx context.Context, req *Request) *Response {
for _, handler := range handlers {
response := handler(ctx, req)
@@ -27,3 +31,24 @@ func Fallthrough(handlers ...Handler) Handler {
return NotFound("Resource does not exist.")
}
}
+
+// Filter wraps a handler with a predicate which determines whether to run the handler.
+//
+// When the predicate function returns false, the Filter returns the provided failure
+// response. The failure argument may be nil, in which case a "51 Resource does not exist."
+// response will be used.
+func Filter(
+ predicate func(context.Context, *Request) bool,
+ handler Handler,
+ failure *Response,
+) Handler {
+ if failure == nil {
+ failure = NotFound("Resource does not exist.")
+ }
+ return func(ctx context.Context, req *Request) *Response {
+ if !predicate(ctx, req) {
+ return failure
+ }
+ return handler(ctx, req)
+ }
+}