~bigbes/core-go

ref: 3c6ab9bd770d303ea2166cc2b905dd36622f2088 core-go/redis/middleware.go -rw-r--r-- 773 bytes
3c6ab9bd — Drew DeVault auth: improve error response format 4 years 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
package redis

import (
	"context"
	"errors"
	"net/http"

	goRedis "github.com/go-redis/redis/v8"
)

var redisCtxKey = &contextKey{"redis"}

type contextKey struct {
	name string
}

func Middleware(client *goRedis.Client) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			r = r.WithContext(Context(r.Context(), client))
			next.ServeHTTP(w, r)
		})
	}
}

func Context(ctx context.Context, client *goRedis.Client) context.Context {
	return context.WithValue(ctx, redisCtxKey, client)
}

func ForContext(ctx context.Context) *goRedis.Client {
	raw, ok := ctx.Value(redisCtxKey).(*goRedis.Client)
	if !ok {
		panic(errors.New("Invalid redis context"))
	}
	return raw
}