github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/health/checks/redis.go (about) 1 package checks 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 redis "github.com/go-redis/redis" 9 ) 10 11 // Config is the Redis checker configuration settings container. 12 type RedisCheck struct { 13 Ctx context.Context 14 ConnectionString string 15 Error error 16 } 17 18 func NewRedisCheck(ctx context.Context, connectionString string) RedisCheck { 19 return RedisCheck{ 20 Ctx: ctx, 21 ConnectionString: connectionString, 22 Error: nil, 23 } 24 } 25 26 func CheckRedisStatus(ctx context.Context, connectionString string) error { 27 check := NewRedisCheck(ctx, connectionString) 28 return check.CheckStatus() 29 } 30 31 func (check RedisCheck) CheckStatus() error { 32 // support all DSN formats (for backward compatibility) - with and w/out schema and path part: 33 // - redis://localhost:1234/ 34 // - rediss://localhost:1234/ 35 // - localhost:1234 36 redisDSN := check.ConnectionString 37 if !strings.HasPrefix(redisDSN, "redis://") && !strings.HasPrefix(redisDSN, "rediss://") { 38 redisDSN = fmt.Sprintf("redis://%s", redisDSN) 39 } 40 redisOptions, _ := redis.ParseURL(redisDSN) 41 //ctx := check.Ctx 42 43 rdb := redis.NewClient(redisOptions) 44 defer rdb.Close() 45 46 pong, err := rdb.Ping().Result() 47 if err != nil { 48 check.Error = fmt.Errorf("redis ping failed: %w", err) 49 return check.Error 50 } 51 52 if pong != "PONG" { 53 check.Error = fmt.Errorf("unexpected response for redis ping: %q", pong) 54 return check.Error 55 } 56 57 return nil 58 }