You've already forked email-api-client
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 21s
74 lines
1.8 KiB
Go
Executable File
74 lines
1.8 KiB
Go
Executable File
package redis
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"gitea.siteworxpro.com/golang-packages/utilities/Env"
|
|
"github.com/go-redis/redis"
|
|
"strconv"
|
|
)
|
|
|
|
const (
|
|
redisHost Env.EnvironmentVariable = "REDIS_HOST"
|
|
redisHPassword Env.EnvironmentVariable = "REDIS_PASSWORD"
|
|
redisDb Env.EnvironmentVariable = "REDIS_DB"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const redisContextKey contextKey = "redisClient"
|
|
|
|
func NewRedis() (*redis.Client, error) {
|
|
|
|
if redisHost.GetEnvString("") == "" {
|
|
return nil, nil // Redis host not set, return nil
|
|
}
|
|
|
|
db, err := strconv.ParseInt(redisDb.GetEnvString("0"), 10, 64)
|
|
|
|
if err != nil {
|
|
return nil, errors.New("invalid REDIS_DB value: " + err.Error())
|
|
}
|
|
|
|
rdb := redis.NewClient(&redis.Options{
|
|
Addr: redisHost.GetEnvString("localhost:6379"),
|
|
Password: redisHPassword.GetEnvString(""),
|
|
DB: int(db),
|
|
})
|
|
|
|
cmd := rdb.Ping() // Ensure the connection is established
|
|
|
|
if cmd.Err() != nil {
|
|
return nil, errors.New("failed to connect to Redis: " + cmd.Err().Error())
|
|
}
|
|
|
|
return rdb, nil
|
|
}
|
|
|
|
func FromContext(ctx context.Context) (*redis.Client, error) {
|
|
client := ctx.Value(redisContextKey)
|
|
if client == nil {
|
|
return nil, errors.New("no Redis client found in context")
|
|
}
|
|
|
|
if rdb, ok := client.(*redis.Client); ok {
|
|
return rdb, nil
|
|
}
|
|
|
|
return nil, errors.New("invalid Redis client type in context")
|
|
}
|
|
|
|
func NewWithContext(ctx context.Context) (context.Context, error) {
|
|
rdb, err := NewRedis()
|
|
if err != nil {
|
|
return nil, errors.New("failed to create Redis client: " + err.Error())
|
|
}
|
|
|
|
ctx = context.WithValue(ctx, redisContextKey, rdb)
|
|
if c, ok := ctx.Value(redisContextKey).(*redis.Client); ok {
|
|
return context.WithValue(ctx, redisContextKey, c), nil
|
|
} else {
|
|
return nil, errors.New("failed to set Redis client in context")
|
|
}
|
|
}
|