style: 统一代码格式和行尾
This commit is contained in:
@@ -1,139 +1,139 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/auth"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// JWTAuth check jwt token and ensure it matches the currently stored token.
|
||||
func JWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := parts[1]
|
||||
|
||||
claims, err := auth.ParseToken(tokenString)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
|
||||
return
|
||||
}
|
||||
check(c, claims, tokenString, accountRepo, cache)
|
||||
}
|
||||
}
|
||||
|
||||
func SoftJWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := parts[1]
|
||||
|
||||
claims, err := auth.ParseToken(tokenString)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
|
||||
return
|
||||
}
|
||||
|
||||
check(c, claims, tokenString, accountRepo, cache)
|
||||
}
|
||||
}
|
||||
|
||||
func check(c *gin.Context, claims *auth.Claims, tokenString string, accountRepo *account.AccountRepository, cache *rediscache.Client) {
|
||||
key := cache.Key("account:%d", claims.AccountID)
|
||||
|
||||
// 先查 Redis
|
||||
if cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
b, err := cache.GetBytes(cacheCtx, key)
|
||||
if err == nil {
|
||||
if string(b) != tokenString {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
|
||||
return
|
||||
}
|
||||
c.Set("accountID", claims.AccountID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 故障/未启用:查 DB 兜底
|
||||
accountInfo, err := accountRepo.FindByID(c.Request.Context(), claims.AccountID)
|
||||
if err != nil || accountInfo.Token == "" || accountInfo.Token != tokenString {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
|
||||
return
|
||||
}
|
||||
|
||||
if cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
if err := cache.SetBytes(cacheCtx, key, []byte(tokenString), 24*time.Hour); err != nil {
|
||||
log.Printf("failed to set cache: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
c.Set("accountID", claims.AccountID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Next()
|
||||
|
||||
}
|
||||
|
||||
func GetAccountID(c *gin.Context) (uint, error) {
|
||||
uidValue, exists := c.Get("accountID")
|
||||
if !exists {
|
||||
return 0, errors.New("accountID not found")
|
||||
}
|
||||
|
||||
accountID, ok := uidValue.(uint)
|
||||
if !ok {
|
||||
return 0, errors.New("accountID has invalid type")
|
||||
}
|
||||
|
||||
return accountID, nil
|
||||
}
|
||||
|
||||
func GetUsername(c *gin.Context) (string, error) {
|
||||
val, exists := c.Get("username")
|
||||
if !exists {
|
||||
return "", errors.New("username not found")
|
||||
}
|
||||
|
||||
username, ok := val.(string)
|
||||
if !ok {
|
||||
return "", errors.New("username has invalid type")
|
||||
}
|
||||
|
||||
return username, nil
|
||||
}
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/auth"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// JWTAuth check jwt token and ensure it matches the currently stored token.
|
||||
func JWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := parts[1]
|
||||
|
||||
claims, err := auth.ParseToken(tokenString)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
|
||||
return
|
||||
}
|
||||
check(c, claims, tokenString, accountRepo, cache)
|
||||
}
|
||||
}
|
||||
|
||||
func SoftJWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := parts[1]
|
||||
|
||||
claims, err := auth.ParseToken(tokenString)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
|
||||
return
|
||||
}
|
||||
|
||||
check(c, claims, tokenString, accountRepo, cache)
|
||||
}
|
||||
}
|
||||
|
||||
func check(c *gin.Context, claims *auth.Claims, tokenString string, accountRepo *account.AccountRepository, cache *rediscache.Client) {
|
||||
key := cache.Key("account:%d", claims.AccountID)
|
||||
|
||||
// 先查 Redis
|
||||
if cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
b, err := cache.GetBytes(cacheCtx, key)
|
||||
if err == nil {
|
||||
if string(b) != tokenString {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
|
||||
return
|
||||
}
|
||||
c.Set("accountID", claims.AccountID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 故障/未启用:查 DB 兜底
|
||||
accountInfo, err := accountRepo.FindByID(c.Request.Context(), claims.AccountID)
|
||||
if err != nil || accountInfo.Token == "" || accountInfo.Token != tokenString {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
|
||||
return
|
||||
}
|
||||
|
||||
if cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
if err := cache.SetBytes(cacheCtx, key, []byte(tokenString), 24*time.Hour); err != nil {
|
||||
log.Printf("failed to set cache: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
c.Set("accountID", claims.AccountID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Next()
|
||||
|
||||
}
|
||||
|
||||
func GetAccountID(c *gin.Context) (uint, error) {
|
||||
uidValue, exists := c.Get("accountID")
|
||||
if !exists {
|
||||
return 0, errors.New("accountID not found")
|
||||
}
|
||||
|
||||
accountID, ok := uidValue.(uint)
|
||||
if !ok {
|
||||
return 0, errors.New("accountID has invalid type")
|
||||
}
|
||||
|
||||
return accountID, nil
|
||||
}
|
||||
|
||||
func GetUsername(c *gin.Context) (string, error) {
|
||||
val, exists := c.Get("username")
|
||||
if !exists {
|
||||
return "", errors.New("username not found")
|
||||
}
|
||||
|
||||
username, ok := val.(string)
|
||||
if !ok {
|
||||
return "", errors.New("username has invalid type")
|
||||
}
|
||||
|
||||
return username, nil
|
||||
}
|
||||
|
||||
@@ -68,4 +68,3 @@ func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt
|
||||
evt.OccurredAt = time.Now().UTC()
|
||||
return c.PublishJSON(ctx, commentExchange, routingKey, evt)
|
||||
}
|
||||
|
||||
|
||||
@@ -54,4 +54,3 @@ func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64) e
|
||||
}
|
||||
return p.PublishJSON(ctx, popularityExchange, popularityUpdateRK, event)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,123 +1,123 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type RabbitMQ struct {
|
||||
Conn *amqp.Connection
|
||||
Ch *amqp.Channel
|
||||
}
|
||||
|
||||
func NewRabbitMQ(cfg *config.RabbitMQConfig) (*RabbitMQ, error) {
|
||||
if cfg == nil {
|
||||
return nil, errors.New("rabbitmq config is nil")
|
||||
}
|
||||
url := "amqp://" + cfg.Username + ":" + cfg.Password + "@" + cfg.Host + ":" + strconv.Itoa(cfg.Port) + "/"
|
||||
conn, err := amqp.Dial(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ch, err := conn.Channel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RabbitMQ{Conn: conn, Ch: ch}, nil
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) Close() error {
|
||||
if r == nil || r.Ch == nil || r.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if err := r.Ch.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.Conn.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) DeclareTopic(exchange string, queue string, bindingKey string) error {
|
||||
if r == nil || r.Ch == nil {
|
||||
return errors.New("rabbitmq is not initialized")
|
||||
}
|
||||
if exchange == "" || queue == "" || bindingKey == "" {
|
||||
return errors.New("exchange/queue/bindingKey is required")
|
||||
}
|
||||
|
||||
if err := r.Ch.ExchangeDeclare(
|
||||
exchange,
|
||||
"topic",
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
q, err := r.Ch.QueueDeclare(
|
||||
queue,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
amqp.Table{"x-dead-letter-exchange": DLXExchange},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := r.Ch.QueueBind(
|
||||
q.Name,
|
||||
bindingKey,
|
||||
exchange,
|
||||
false,
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DeclareDLX(r.Ch, queue); err != nil {
|
||||
log.Printf("DLX declare failed for %s: %v", queue, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) PublishJSON(ctx context.Context, exchange string, routingKey string, payload any) error {
|
||||
if r == nil || r.Ch == nil {
|
||||
return errors.New("rabbitmq is not initialized")
|
||||
}
|
||||
if exchange == "" || routingKey == "" {
|
||||
return errors.New("exchange and routingKey are required")
|
||||
}
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.Ch.PublishWithContext(ctx, exchange, routingKey, false, false, amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
Timestamp: time.Now(),
|
||||
Body: b,
|
||||
})
|
||||
}
|
||||
|
||||
func newEventID(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type RabbitMQ struct {
|
||||
Conn *amqp.Connection
|
||||
Ch *amqp.Channel
|
||||
}
|
||||
|
||||
func NewRabbitMQ(cfg *config.RabbitMQConfig) (*RabbitMQ, error) {
|
||||
if cfg == nil {
|
||||
return nil, errors.New("rabbitmq config is nil")
|
||||
}
|
||||
url := "amqp://" + cfg.Username + ":" + cfg.Password + "@" + cfg.Host + ":" + strconv.Itoa(cfg.Port) + "/"
|
||||
conn, err := amqp.Dial(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ch, err := conn.Channel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RabbitMQ{Conn: conn, Ch: ch}, nil
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) Close() error {
|
||||
if r == nil || r.Ch == nil || r.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
if err := r.Ch.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.Conn.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) DeclareTopic(exchange string, queue string, bindingKey string) error {
|
||||
if r == nil || r.Ch == nil {
|
||||
return errors.New("rabbitmq is not initialized")
|
||||
}
|
||||
if exchange == "" || queue == "" || bindingKey == "" {
|
||||
return errors.New("exchange/queue/bindingKey is required")
|
||||
}
|
||||
|
||||
if err := r.Ch.ExchangeDeclare(
|
||||
exchange,
|
||||
"topic",
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
q, err := r.Ch.QueueDeclare(
|
||||
queue,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
amqp.Table{"x-dead-letter-exchange": DLXExchange},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := r.Ch.QueueBind(
|
||||
q.Name,
|
||||
bindingKey,
|
||||
exchange,
|
||||
false,
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DeclareDLX(r.Ch, queue); err != nil {
|
||||
log.Printf("DLX declare failed for %s: %v", queue, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) PublishJSON(ctx context.Context, exchange string, routingKey string, payload any) error {
|
||||
if r == nil || r.Ch == nil {
|
||||
return errors.New("rabbitmq is not initialized")
|
||||
}
|
||||
if exchange == "" || routingKey == "" {
|
||||
return errors.New("exchange and routingKey are required")
|
||||
}
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.Ch.PublishWithContext(ctx, exchange, routingKey, false, false, amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
Timestamp: time.Now(),
|
||||
Body: b,
|
||||
})
|
||||
}
|
||||
|
||||
func newEventID(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
jwt "feedsystem_video_go/internal/middleware/jwt"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"strconv"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type KeyFunc func(*gin.Context) (string, bool)
|
||||
@@ -68,4 +68,4 @@ func KeyByAccount(c *gin.Context) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(uint64(accountID), 10), true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,115 +1,115 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
redis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
rdb *redis.Client
|
||||
keyPrefix string
|
||||
}
|
||||
|
||||
const defaultKeyPrefix = "v1:"
|
||||
|
||||
func NewClient(rdb *redis.Client, keyPrefix string) *Client {
|
||||
return &Client{rdb: rdb, keyPrefix: keyPrefix}
|
||||
}
|
||||
|
||||
func NewFromEnv(cfg *config.RedisConfig) (*Client, error) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
return &Client{rdb: rdb, keyPrefix: defaultKeyPrefix}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
return c.rdb.Close()
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
return c.rdb.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func IsMiss(err error) bool {
|
||||
return err == redis.Nil
|
||||
}
|
||||
|
||||
func (c *Client) Key(format string, args ...any) string {
|
||||
prefix := ""
|
||||
if c != nil {
|
||||
prefix = c.keyPrefix
|
||||
}
|
||||
return prefix + fmt.Sprintf(format, args...)
|
||||
}
|
||||
|
||||
func randToken(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func (c *Client) Lock(ctx context.Context, key string, ttl time.Duration) (token string, ok bool, err error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return "", false, nil
|
||||
}
|
||||
token, err = randToken(16)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
ok, err = c.rdb.SetNX(ctx, key, token, ttl).Result()
|
||||
return token, ok, err
|
||||
}
|
||||
|
||||
var unlockScript = redis.NewScript(`
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
`)
|
||||
|
||||
var incrementWithExpireScript = redis.NewScript(`
|
||||
local count = redis.call("INCR", KEYS[1])
|
||||
if count == 1 then
|
||||
redis.call("PEXPIRE", KEYS[1], ARGV[1])
|
||||
end
|
||||
return count
|
||||
`)
|
||||
|
||||
func (c *Client) Unlock(ctx context.Context, key string, token string) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
_, err := unlockScript.Run(ctx, c.rdb, []string{key}, token).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) IncrementWithExpire(ctx context.Context, key string, expire time.Duration) (int64, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return incrementWithExpireScript.Run(
|
||||
ctx,
|
||||
c.rdb,
|
||||
[]string{key},
|
||||
expire.Milliseconds(),
|
||||
).Int64()
|
||||
}
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
redis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
rdb *redis.Client
|
||||
keyPrefix string
|
||||
}
|
||||
|
||||
const defaultKeyPrefix = "v1:"
|
||||
|
||||
func NewClient(rdb *redis.Client, keyPrefix string) *Client {
|
||||
return &Client{rdb: rdb, keyPrefix: keyPrefix}
|
||||
}
|
||||
|
||||
func NewFromEnv(cfg *config.RedisConfig) (*Client, error) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
return &Client{rdb: rdb, keyPrefix: defaultKeyPrefix}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
return c.rdb.Close()
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
return c.rdb.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func IsMiss(err error) bool {
|
||||
return err == redis.Nil
|
||||
}
|
||||
|
||||
func (c *Client) Key(format string, args ...any) string {
|
||||
prefix := ""
|
||||
if c != nil {
|
||||
prefix = c.keyPrefix
|
||||
}
|
||||
return prefix + fmt.Sprintf(format, args...)
|
||||
}
|
||||
|
||||
func randToken(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func (c *Client) Lock(ctx context.Context, key string, ttl time.Duration) (token string, ok bool, err error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return "", false, nil
|
||||
}
|
||||
token, err = randToken(16)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
ok, err = c.rdb.SetNX(ctx, key, token, ttl).Result()
|
||||
return token, ok, err
|
||||
}
|
||||
|
||||
var unlockScript = redis.NewScript(`
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
`)
|
||||
|
||||
var incrementWithExpireScript = redis.NewScript(`
|
||||
local count = redis.call("INCR", KEYS[1])
|
||||
if count == 1 then
|
||||
redis.call("PEXPIRE", KEYS[1], ARGV[1])
|
||||
end
|
||||
return count
|
||||
`)
|
||||
|
||||
func (c *Client) Unlock(ctx context.Context, key string, token string) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
}
|
||||
_, err := unlockScript.Run(ctx, c.rdb, []string{key}, token).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) IncrementWithExpire(ctx context.Context, key string, expire time.Duration) (int64, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return incrementWithExpireScript.Run(
|
||||
ctx,
|
||||
c.rdb,
|
||||
[]string{key},
|
||||
expire.Milliseconds(),
|
||||
).Int64()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user