Files
goimgApi/configs/redis.go
Beyhan Oğur e6f3268c28 first commit
2026-04-26 21:48:15 +03:00

48 lines
925 B
Go

package configs
import (
"context"
"fmt"
"os"
"github.com/redis/go-redis/v9"
)
var RedisClient *redis.Client
var Ctx = context.Background()
// ConnectRedis initializes the Redis connection
func ConnectRedis() error {
redisURL := os.Getenv("REDIS_URL")
if redisURL != "" {
opt, err := redis.ParseURL(redisURL)
if err != nil {
return fmt.Errorf("failed to parse redis url: %w", err)
}
RedisClient = redis.NewClient(opt)
} else {
host := os.Getenv("REDIS_HOST")
if host == "" {
host = "localhost"
}
port := os.Getenv("REDIS_PORT")
if port == "" {
port = "6379"
}
pass := os.Getenv("REDIS_PASSWORD")
RedisClient = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", host, port),
Password: pass,
DB: 0, // Default DB
})
}
_, err := RedisClient.Ping(Ctx).Result()
if err != nil {
return fmt.Errorf("redis connection failed: %w", err)
}
return nil
}