From ebf93be7318f77767cc3315d2db565749c2bc770 Mon Sep 17 00:00:00 2001 From: Adnan Maolood Date: Tue, 15 Feb 2022 12:44:17 -0500 Subject: [PATCH] webhooks: Add middleware --- webhooks/middleware.go | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 webhooks/middleware.go diff --git a/webhooks/middleware.go b/webhooks/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..d59508b73aab90c756b0f04bd59d5a3dd7a4aad5 --- /dev/null +++ b/webhooks/middleware.go @@ -0,0 +1,46 @@ +package webhooks + +import ( + "context" + "net/http" +) + +var ctxKey = &contextKey{"webhooks"} + +func Middleware(queue *WebhookQueue) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := context.WithValue(r.Context(), ctxKey, queue) + r = r.WithContext(ctx) + next.ServeHTTP(w, r) + }) + } +} + +func ForContext(ctx context.Context) *WebhookQueue { + queue, ok := ctx.Value(ctxKey).(*WebhookQueue) + if !ok { + panic("No webhook queue for this context") + } + return queue +} + +var legacyCtxKey = &contextKey{"legacy"} + +func LegacyMiddleware(queue *LegacyQueue) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := context.WithValue(r.Context(), legacyCtxKey, queue) + r = r.WithContext(ctx) + next.ServeHTTP(w, r) + }) + } +} + +func LegacyForContext(ctx context.Context) *LegacyQueue { + queue, ok := ctx.Value(legacyCtxKey).(*LegacyQueue) + if !ok { + panic("No legacy webhook queue for this context") + } + return queue +}