57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
|
|
package sms
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"fmt"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/redis/go-redis/v9"
|
||
|
|
)
|
||
|
|
|
||
|
|
// RedisStore implementerar VerificationStore med Redis
|
||
|
|
type RedisStore struct {
|
||
|
|
client *redis.Client
|
||
|
|
ctx context.Context
|
||
|
|
}
|
||
|
|
|
||
|
|
// NewRedisStore skapar ny Redis-baserad store
|
||
|
|
func NewRedisStore(addr string) *RedisStore {
|
||
|
|
client := redis.NewClient(&redis.Options{
|
||
|
|
Addr: addr,
|
||
|
|
Password: "",
|
||
|
|
DB: 0,
|
||
|
|
})
|
||
|
|
|
||
|
|
return &RedisStore{
|
||
|
|
client: client,
|
||
|
|
ctx: context.Background(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Set sparar värde med TTL
|
||
|
|
func (r *RedisStore) Set(key string, value string, ttl time.Duration) error {
|
||
|
|
return r.client.Set(r.ctx, key, value, ttl).Err()
|
||
|
|
}
|
||
|
|
|
||
|
|
// Get hämtar värde
|
||
|
|
func (r *RedisStore) Get(key string) (string, error) {
|
||
|
|
val, err := r.client.Get(r.ctx, key).Result()
|
||
|
|
if err == redis.Nil {
|
||
|
|
return "", fmt.Errorf("key not found")
|
||
|
|
}
|
||
|
|
if err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
return val, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// Delete raderar nyckel
|
||
|
|
func (r *RedisStore) Delete(key string) error {
|
||
|
|
return r.client.Del(r.ctx, key).Err()
|
||
|
|
}
|
||
|
|
|
||
|
|
// Ping kontrollerar anslutning
|
||
|
|
func (r *RedisStore) Ping() error {
|
||
|
|
return r.client.Ping(r.ctx).Err()
|
||
|
|
}
|