~bigbes/core-go

ref: 7f734c73acb2c577b047bcd0d9f0e5a453da91ab core-go/webhooks/middleware.go -rw-r--r-- 1.1 KiB
7f734c73 — Conrad Hoffmann errors: fix comparison in errors.Is() 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package webhooks

import (
	"context"
	"fmt"
	"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(fmt.Errorf("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(fmt.Errorf("no legacy webhook queue for this context"))
	}
	return queue
}