package signature import ( "context" "github.com/zeromicro/go-zero/core/stores/redis" ) // NonceStore 防重放存储接口 type NonceStore interface { // SetIfNotExists 返回 (true, nil) 表示 key 已存在(重放攻击) SetIfNotExists(ctx context.Context, appId, nonce string, ttlSeconds int64) (bool, error) } type RedisNonceStore struct { client *redis.Redis } func NewRedisNonceStore(client *redis.Redis) *RedisNonceStore { return &RedisNonceStore{client: client} } func (s *RedisNonceStore) SetIfNotExists(_ context.Context, appId, nonce string, ttlSeconds int64) (bool, error) { key := "sig:nonce:" + appId + ":" + nonce // go-zero redis.Redis.SetNX 返回 true 表示设置成功(首次) ok, err := s.client.SetnxEx(key, "1", int(ttlSeconds)) if err != nil { return false, err } // SetnxEx ok=true 首次,ok=false 已存在(重放) return !ok, nil }