summaryrefslogtreecommitdiff
path: root/handler.go
diff options
context:
space:
mode:
authortjpcc <tjp@ctrl-c.club>2023-01-17 15:59:29 -0700
committertjpcc <tjp@ctrl-c.club>2023-01-17 15:59:29 -0700
commit2ef530daa47b301a40c1ee93cd43b8f36fc68c0b (patch)
treeb9753719f5f0e5312bb5008d40f40247ce14e15a /handler.go
parent30e21f8513d49661cb6e1583d301e34e898d48a9 (diff)
pull request, response, handlers out of the gemini package
Diffstat (limited to 'handler.go')
-rw-r--r--handler.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/handler.go b/handler.go
new file mode 100644
index 0000000..f940b77
--- /dev/null
+++ b/handler.go
@@ -0,0 +1,52 @@
+package gus
+
+import "context"
+
+// Handler is a function which can turn a request into a response.
+//
+// A Handler can 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
+
+// Middleware is a handler decorator.
+//
+// It returns a handler which may call the passed-in handler or not, or may
+// transform the request or response in some way.
+type Middleware func(Handler) Handler
+
+// FallthroughHandler builds a handler which tries multiple child handlers.
+//
+// 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 {
+ for _, handler := range handlers {
+ if response := handler(ctx, request); response != nil {
+ return response
+ }
+ }
+ return nil
+ }
+}
+
+// Filter builds a middleware which only calls the wrapped under a condition.
+//
+// When the condition function returns false it instead invokes the
+// test-failure handler. The failure handler may also be nil, in which case
+// the final handler will return a nil response whenever the condition fails.
+func Filter(
+ condition func(context.Context, *Request) bool,
+ failure Handler,
+) Middleware {
+ return func(success Handler) Handler {
+ return func(ctx context.Context, request *Request) *Response {
+ if condition(ctx, request) {
+ return success(ctx, request)
+ }
+ if failure == nil {
+ return nil
+ }
+ return failure(ctx, request)
+ }
+ }
+}