gpt4 book ai didi

go - golang.org/x/time/rate api 请求的速率限制

转载 作者:行者123 更新时间:2023-12-01 22:07:14 29 4
gpt4 key购买 nike

我已经在 1 天内为 api 登录创建了限制 50 个请求的函数

无功限制 = 50

package middleware

import (
"log"
"net"
"net/http"
"sync"
"time"

"golang.org/x/time/rate"
)

// Create a custom request struct which holds the rate limiter for each
// visitor and the last time that the request was seen.
type request struct {
limiter *rate.Limiter
lastSeen time.Time
}

// Change the the map to hold values of the type request.
// defaultTime using 3 minutes
var requests = make(map[string]*request)
var mu sync.Mutex

func getRequest(ip string, limit int) *rate.Limiter {
mu.Lock()
defer mu.Unlock()

v, exists := requests[ip]
if !exists {
limiter := rate.NewLimiter(1, limit)
requests[ip] = &request{limiter, time.Now()}
return limiter
}
// Update the last seen time for the visitor.
v.lastSeen = time.Now()
return v.limiter
}

func throttle(next http.Handler, limit int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Println(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
limiter := getRequest(ip, limit)
fmt.Println(limiter.Allow())
if limiter.Allow() == false {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}

这是正确的 ?

因为我试了一下还是通过,功能限制不起作用

我怀疑 NewLimiter()
 limiter := rate.NewLimiter(1, limit)

这意味着 1 个用户只能请求登录 50 个请求/天? (我已经读过 doc 但我不明白)

最佳答案

来自 rate docs :

func NewLimiter(r Limit, b int) *Limiter

NewLimiter returns a new Limiter that allows events up to rate r and permits bursts of at most b tokens.



所以第一个参数是速率限制,而不是第二个。 Burst 是您希望允许的比速率限制更快的请求数量 - 通常使用值 1为了禁止爆发,任何更高的请求都会在常规速率限制开始之前允许这个数量的请求。无论如何......

创建 rate.Limit根据您的需要,您可以使用辅助函数 rate.Every() :
rt := rate.Every(24*time.Hour / 50)

limiter := rate.NewLimiter(rt, 1)

关于go - golang.org/x/time/rate api 请求的速率限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60816614/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com