package http import ( "context" "fmt" "github.com/labstack/echo/v4" "github.com/redis/go-redis/v9" "os" "strconv" ) type CustomContext struct { echo.Context redis *redis.Client } func GetCustomContext(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { redisUrl := os.Getenv("REDIS_URL") if redisUrl == "" { c.Logger().Warn("REDIS_URL not set, skipping redis connection. Use REDIS_URL to cache the image") return next(&CustomContext{c, nil}) } redisPort := os.Getenv("REDIS_PORT") if redisPort == "" { redisPort = "6379" } redisDb := os.Getenv("REDIS_DB") if redisDb == "" { redisDb = "0" } redisDbInt, err := strconv.ParseInt(redisDb, 10, 64) if err != nil { c.Logger().Warn("REDIS_DB is not a valid integer, skipping redis connection. Use REDIS_DB to cache the image") return next(&CustomContext{}) } cc := &CustomContext{c, redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%s", redisUrl, redisPort), Password: os.Getenv("REDIS_PASSWORD"), DB: int(redisDbInt), })} cmd := cc.redis.Ping(context.Background()) if cmd.Err() != nil { c.Logger().Warn("could not connect to redis") cc.redis = nil } return next(cc) } }