|
@@ -0,0 +1,60 @@
|
|
|
|
+package repository
|
|
|
|
+
|
|
|
|
+import (
|
|
|
|
+ "context"
|
|
|
|
+ "github.com/go-nunu/nunu-layout-advanced/internal/model"
|
|
|
|
+ "github.com/redis/go-redis/v9"
|
|
|
|
+ "time"
|
|
|
|
+)
|
|
|
|
+
|
|
|
|
+type CdnRepository interface {
|
|
|
|
+ GetCdn(ctx context.Context, id int64) (*model.Cdn, error)
|
|
|
|
+ PutToken(ctx context.Context, token string) error
|
|
|
|
+ GetToken(ctx context.Context) (string, error)
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func NewCdnRepository(
|
|
|
|
+ repository *Repository,
|
|
|
|
+) CdnRepository {
|
|
|
|
+ return &cdnRepository{
|
|
|
|
+ Repository: repository,
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+type cdnRepository struct {
|
|
|
|
+ *Repository
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func (r *cdnRepository) GetCdn(ctx context.Context, id int64) (*model.Cdn, error) {
|
|
|
|
+ var cdn model.Cdn
|
|
|
|
+
|
|
|
|
+ return &cdn, nil
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+const cdnTokenKey = "cdn:token"
|
|
|
|
+
|
|
|
|
+func (r *cdnRepository) PutToken(ctx context.Context, token string) error {
|
|
|
|
+ // 设置 token 的过期时间,例如 2 小时
|
|
|
|
+ const expiration = 2 * time.Hour
|
|
|
|
+
|
|
|
|
+ // 使用 Set 方法将 token 存入 Redis
|
|
|
|
+ err := r.rdb.Set(ctx, cdnTokenKey, token, expiration).Err()
|
|
|
|
+ if err != nil {
|
|
|
|
+ return err
|
|
|
|
+ }
|
|
|
|
+ return nil
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+// GetToken 从 Redis 中获取 CDN token
|
|
|
|
+func (r *cdnRepository) GetToken(ctx context.Context) (string, error) {
|
|
|
|
+ token, err := r.rdb.Get(ctx, cdnTokenKey).Result()
|
|
|
|
+ if err != nil {
|
|
|
|
+ // 如果 token 不存在,redis.Nil 会被返回
|
|
|
|
+ if err == redis.Nil {
|
|
|
|
+ return "", nil // 或者返回一个特定的错误表示 token 不存在
|
|
|
|
+ }
|
|
|
|
+ return "", err
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ return token, nil
|
|
|
|
+}
|