dinheiro

commit d32d7258b1cb4f3c69c73450f5fc552574f48b43

Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>

redis: rig up redis middleware

 redis/middleware.go | 38 ++++++++++++++++++++++++++++++++++++++


diff --git a/redis/middleware.go b/redis/middleware.go
new file mode 100644
index 0000000000000000000000000000000000000000..ab9b0578c2f5ca7994f6840efa44d60c0a681530
--- /dev/null
+++ b/redis/middleware.go
@@ -0,0 +1,38 @@
+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
+}