Source File
rate.go
Belonging Package
github.com/go-redis/redis_rate/v9
package redis_rate
import (
)
const redisPrefix = "rate:"
type rediser interface {
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd
ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd
ScriptLoad(ctx context.Context, script string) *redis.StringCmd
}
type Limit struct {
Rate int
Burst int
Period time.Duration
}
func ( Limit) () string {
return fmt.Sprintf("%d req/%s (burst %d)", .Rate, fmtDur(.Period), .Burst)
}
func ( Limit) () bool {
return == Limit{}
}
func ( time.Duration) string {
switch {
case time.Second:
return "s"
case time.Minute:
return "m"
case time.Hour:
return "h"
}
return .String()
}
func ( int) Limit {
return Limit{
Rate: ,
Period: time.Second,
Burst: ,
}
}
func ( int) Limit {
return Limit{
Rate: ,
Period: time.Minute,
Burst: ,
}
}
func ( int) Limit {
return Limit{
Rate: ,
Period: time.Hour,
Burst: ,
}
}
func ( Limiter) (
context.Context,
string,
Limit,
int,
) (*Result, error) {
:= []interface{}{.Burst, .Rate, .Period.Seconds(), }
, := allowN.Run(, .rdb, []string{redisPrefix + }, ...).Result()
if != nil {
return nil,
}
= .([]interface{})
, := strconv.ParseFloat([2].(string), 64)
if != nil {
return nil,
}
, := strconv.ParseFloat([3].(string), 64)
if != nil {
return nil,
}
:= &Result{
Limit: ,
Allowed: int([0].(int64)),
Remaining: int([1].(int64)),
RetryAfter: dur(),
ResetAfter: dur(),
}
return , nil
}
func ( Limiter) (
context.Context,
string,
Limit,
int,
) (*Result, error) {
:= []interface{}{.Burst, .Rate, .Period.Seconds(), }
, := allowAtMost.Run(, .rdb, []string{redisPrefix + }, ...).Result()
if != nil {
return nil,
}
= .([]interface{})
, := strconv.ParseFloat([2].(string), 64)
if != nil {
return nil,
}
, := strconv.ParseFloat([3].(string), 64)
if != nil {
return nil,
}
:= &Result{
Limit: ,
Allowed: int([0].(int64)),
Remaining: int([1].(int64)),
RetryAfter: dur(),
ResetAfter: dur(),
}
return , nil
}
func ( float64) time.Duration {
if == -1 {
return -1
}
return time.Duration( * float64(time.Second))
}
![]() |
The pages are generated with Golds v0.3.2-preview. (GOOS=darwin GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |