Files
Authentication/helper/redis_json.go
T
2025-11-25 15:12:31 +08:00

58 lines
1.4 KiB
Go

package helper
import (
"authentication/redisclient"
"context"
"encoding/json"
"errors"
"time"
)
const defaultRedisTTLSeconds = 60
func SetJSON(ctx context.Context, key string, value interface{}, ttlSeconds *int) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
ttl := time.Duration(defaultRedisTTLSeconds) * time.Second
if ttlSeconds != nil {
ttl = time.Duration(*ttlSeconds) * time.Second
}
return redisclient.RDB.Set(ctx, key, data, ttl).Err()
}
func SlotSetJSON(ctx context.Context, key string, value interface{}, ttlSeconds *int) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
ttl := time.Duration(0)
if ttlSeconds != nil {
ttl = time.Duration(*ttlSeconds) * time.Second
}
return redisclient.RDB.Set(ctx, key, data, ttl).Err()
}
func GetJSON(ctx context.Context, key string, dest interface{}) error {
val, err := redisclient.RDB.Get(ctx, key).Result()
if err != nil {
return err
}
return json.Unmarshal([]byte(val), dest)
}
func SetTTL(ctx context.Context, key string, ttlSeconds *int) error {
ttl := time.Duration(defaultRedisTTLSeconds) * time.Second
if ttlSeconds != nil {
ttl = time.Duration(*ttlSeconds) * time.Second
}
res, err := redisclient.RDB.Expire(ctx, key, ttl).Result()
if err != nil {
return err
}
if !res {
return errors.New("failed to set TTL: key does not exist")
}
return nil
}