|
| 1 | +package session |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/redis/go-redis/v9" |
| 9 | +) |
| 10 | + |
| 11 | +/* defines the methods to expose (for dependency injection) */ |
| 12 | +type RedisClient interface { |
| 13 | + Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error |
| 14 | + Get(ctx context.Context, key string) (string, error) |
| 15 | + HMSet(ctx context.Context, key string, values map[string]interface{}) error |
| 16 | +} |
| 17 | + |
| 18 | +/* redisClient implementation */ |
| 19 | +type redisClient struct { |
| 20 | + client *redis.Client |
| 21 | +} |
| 22 | + |
| 23 | +/* for creating a new redis client */ |
| 24 | +func NewRedisClient(address, password string, db int) (RedisClient, error) { |
| 25 | + rdb := redis.NewClient(&redis.Options{ |
| 26 | + Addr: address, |
| 27 | + Password: password, |
| 28 | + DB: db, |
| 29 | + }) |
| 30 | + |
| 31 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 32 | + defer cancel() |
| 33 | + |
| 34 | + if err := rdb.Ping(ctx).Err(); err != nil { |
| 35 | + return nil, fmt.Errorf("could not connect to Redis: %w", err) |
| 36 | + } |
| 37 | + |
| 38 | + return &redisClient{client: rdb}, nil |
| 39 | +} |
| 40 | + |
| 41 | +/* Set sets a key-value pair in Redis */ |
| 42 | +func (r *redisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error { |
| 43 | + return r.client.Set(ctx, key, value, expiration).Err() |
| 44 | +} |
| 45 | + |
| 46 | +/* retrieves a value by key from Redis */ |
| 47 | +func (r *redisClient) Get(ctx context.Context, key string) (string, error) { |
| 48 | + return r.client.Get(ctx, key).Result() |
| 49 | +} |
| 50 | + |
| 51 | +/* avoid unsafe casting */ |
| 52 | +func (r *redisClient) HMSet(ctx context.Context, key string, values map[string]interface{}) error { |
| 53 | + return r.client.HSet(ctx, key, values).Err() |
| 54 | +} |
0 commit comments