通过 golang.org/x/time/rate 包并结合 gin 中间件来实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package middleware
import ( "github.com/gin-gonic/gin" "golang.org/x/time/rate" "net/http" )
var limiter *rate.Limiter
func init() {
limiter = rate.NewLimiter(1, 2) }
func RateLimit(c *gin.Context) { if limiter.Allow() { c.Next() }else { c.AbortWithStatusJSON(http.StatusOK, struct { Message string `json:"message"` }{"服务器繁忙,请稍后再试"}) } }
|