go>> rate>> 返回
项目作者: hedzr

项目描述 :
rate limit library in golang
高级语言: Go
项目地址: git://github.com/hedzr/rate.git
创建时间: 2021-06-05T08:08:41Z
项目社区:https://github.com/hedzr/rate

开源协议:MIT License

下载


go-rate

Go
GitHub tag (latest SemVer)

GoDoc Go Report Card
Coverage Status

go-rate provides the rate limiters generally.

Features

History

  • v0.5.0

    • BREAK: To decrease unecessary dependants, we removed middleware subpackage. It has been moved into supports/ and taged with ignore.
      • You must copy its codes to use it.
    • the codes reviewed
    • no any third-party deps now, even from mine.
  • v0.1.x

    • as is

Usages

Simple

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/hedzr/rate"
  5. "time"
  6. )
  7. func main() {
  8. l := rate.New(rate.LeakyBucket, 100, time.Second)
  9. for i := 0; i < 120; i++ {
  10. ok := l.Take(1)
  11. if !ok {
  12. fmt.Printf("#%d Take() returns not ok, counter: %v\n", i, rate.CountOf(l))
  13. time.Sleep(50 * time.Millisecond)
  14. }
  15. }
  16. }

As a gin middleware

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/hedzr/rate"
  5. "github.com/hedzr/rate/middleware"
  6. "time"
  7. )
  8. func webserver() {
  9. r := engine()
  10. r.Run(":3000")
  11. }
  12. func engine() *gin.Engine {
  13. config := &middleware.Config{
  14. Name: "...",
  15. Description: "...",
  16. Algorithm: string(rate.TokenBucket),
  17. Interval: time.Second,
  18. MaxRequests: 1000,
  19. HeaderKeyName: "X-API-TOKEN",
  20. ExceptionKeys: nil,
  21. Routes: nil,
  22. }
  23. r := gin.Default()
  24. r.Use(middleware.ForGin(config))
  25. return r
  26. }

Load limit config with cmdr Option Store

While integrated with hedzr/cmdr, the short loading is available:

  1. import "github.com/hedzr/rate/middleware"
  2. func BuildRoutes(rg *gin.Engine) *gin.Engine {
  3. buildRoutes(rg.Group("/prefix"), rg)
  4. }
  5. func buildRoutes(rg Router, root *gin.Engine) {
  6. middleware.LoadConfigForGin("server.rate-limits", rg)
  7. rg.Get("/echo/*action", echoHandler)
  8. }
  9. func echoGinHandler(c *gin.Context) {
  10. action := c.Param("action")
  11. if action == "" || action == "/" {
  12. action = "<no action>"
  13. }
  14. _, _ = io.WriteString(c.Writer, fmt.Sprintf("action: %v\n", action))
  15. }

A config file (eg. rate-limit.yml) should be put in cmdr-standard conf.d directory, so it can be loaded automatically:

  1. app:
  2. your-app: # <- replace it with your app name, the further KB in cmdr docs.
  3. server:
  4. rate-limits:
  5. - name: by-api-key
  6. interval: 1ms
  7. max-requests: 30
  8. header-key-name: X-API-KEY
  9. exception-keys: [voxr-apps-test-api-key-fndsfjn]

License

MIT