cdn.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package repository
  2. import (
  3. "context"
  4. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  5. "github.com/redis/go-redis/v9"
  6. "time"
  7. )
  8. type CdnRepository interface {
  9. GetCdn(ctx context.Context, id int64) (*model.Cdn, error)
  10. PutToken(ctx context.Context, token string) error
  11. GetToken(ctx context.Context) (string, error)
  12. }
  13. func NewCdnRepository(
  14. repository *Repository,
  15. ) CdnRepository {
  16. return &cdnRepository{
  17. Repository: repository,
  18. }
  19. }
  20. type cdnRepository struct {
  21. *Repository
  22. }
  23. func (r *cdnRepository) GetCdn(ctx context.Context, id int64) (*model.Cdn, error) {
  24. var cdn model.Cdn
  25. return &cdn, nil
  26. }
  27. const cdnTokenKey = "cdn:token"
  28. func (r *cdnRepository) PutToken(ctx context.Context, token string) error {
  29. // 设置 token 的过期时间,例如 2 小时
  30. const expiration = 2 * time.Hour
  31. // 使用 Set 方法将 token 存入 Redis
  32. err := r.rdb.Set(ctx, cdnTokenKey, token, expiration).Err()
  33. if err != nil {
  34. return err
  35. }
  36. return nil
  37. }
  38. // GetToken 从 Redis 中获取 CDN token
  39. func (r *cdnRepository) GetToken(ctx context.Context) (string, error) {
  40. token, err := r.rdb.Get(ctx, cdnTokenKey).Result()
  41. if err != nil {
  42. // 如果 token 不存在,redis.Nil 会被返回
  43. if err == redis.Nil {
  44. return "", nil // 或者返回一个特定的错误表示 token 不存在
  45. }
  46. return "", err
  47. }
  48. return token, nil
  49. }