~bigbes/core-go

ref: 3dc39b678422dbb6aa9f49daca8538415d187c71 core-go/redis/middleware.go -rw-r--r-- 800 bytes
3dc39b67 — Simon Martin server: support setting build version and date information 8 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
package redis

import (
	"context"
	"fmt"
	"net/http"

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

var redisCtxKey = &contextKey{"redis"}

type contextKey struct {
	name string
}

func Middleware(client redis.UniversalClient) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := Context(r.Context(), client)
			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)
		})
	}
}

func Context(ctx context.Context, client redis.UniversalClient) context.Context {
	return context.WithValue(ctx, redisCtxKey, client)
}

func ForContext(ctx context.Context) redis.UniversalClient {
	raw, ok := ctx.Value(redisCtxKey).(redis.UniversalClient)
	if !ok {
		panic(fmt.Errorf("invalid redis context"))
	}
	return raw
}