Add Redis middleware

This commit is contained in:
Drew DeVault 2020-09-14 11:18:54 -04:00
parent dcb2343d6f
commit 9c4efafa16
2 changed files with 47 additions and 0 deletions

34
redis/middleware.go Normal file
View File

@ -0,0 +1,34 @@
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) {
ctx := context.WithValue(r.Context(), redisCtxKey, client)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
func ForContext(ctx context.Context) *goRedis.Client {
raw, ok := ctx.Value(redisCtxKey).(*goRedis.Client)
if !ok {
panic(errors.New("Invalid redis context"))
}
return raw
}

View File

@ -20,11 +20,13 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/vaughan0/go-ini"
_ "github.com/lib/pq"
goRedis "github.com/go-redis/redis/v8"
"git.sr.ht/~sircmpwn/gql.sr.ht/auth"
"git.sr.ht/~sircmpwn/gql.sr.ht/config"
"git.sr.ht/~sircmpwn/gql.sr.ht/crypto"
"git.sr.ht/~sircmpwn/gql.sr.ht/database"
"git.sr.ht/~sircmpwn/gql.sr.ht/redis"
)
var (
@ -95,6 +97,16 @@ func MakeRouter(service string, conf ini.File, schema graphql.ExecutableSchema,
log.Fatalf("Failed to open a database connection: %v", err)
}
rcs, ok := conf.Get("sr.ht", "redis-host")
if !ok {
rcs = "redis://"
}
ropts, err := goRedis.ParseURL(rcs)
if err != nil {
log.Fatalf("Invalid sr.ht::redis-host in config.ini: %e", err)
}
rc := goRedis.NewClient(ropts)
apiconf := fmt.Sprintf("%s::api", service)
var timeout time.Duration
@ -120,6 +132,7 @@ func MakeRouter(service string, conf ini.File, schema graphql.ExecutableSchema,
})
router.Use(config.Middleware(conf))
router.Use(database.Middleware(db))
router.Use(redis.Middleware(rc))
router.Use(middleware.RealIP)
router.Use(middleware.Logger)
router.Use(middleware.Timeout(timeout))