Categorygithub.com/Joepolymath/go-rate-limiter
modulepackage
0.0.0-20230713100232-12b64f78067d
Repository: https://github.com/joepolymath/go-rate-limiter.git
Documentation: pkg.go.dev

# README

rate-limiter

This package provides a rate limiter in Go (Golang) with a middleware adaptable for Gin web servers.

Installation

  • Download

    Type the following command in your terminal.

    go get github.com/go-redis/redis
    go get github.com/Joepolymath/go-rate-limiter
    
  • Import

    import "github.com/go-redis/redis"
    import limiter "github.com/Joepolymath/go-rate-limiter"
    import "time"
    

Quickstart

  • Create a limiter object

    // Set redis client
    rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379", Password: "", DB: 0})
    
    // set up rate limiter object
    cop := &limiter.RateLimiter{
        TotalLimit : 100, BurstLimit : 10,
      MaxTime :  time.Hour * 24,   BurstPeriod : time.Hour * 2
      Client : rdb,  TotalLimitPrefix : "TotalLimitPrefixForRandomService"
      BurstLimitPrefix : "BurstLimitPrefixForRandomService"
    }
    
    
  • Add different rate limiter type middleware to controlling each route.

    server := gin.Default()
    
    // create middleware for
    
    server.POST("/ExamplePost1", limiter.IPLimiter(cop), func(ctx *gin.Context) {
    	ctx.String(http.StatusOK, "Hello ExamplePost1")
    })
    
    server.GET("/ExampleGet1", limiter.UserLimiter(cop, "sample_user_id"), func(ctx *gin.Context) {
    	ctx.String(http.StatusOK, "Hello ExampleGet1")
    })
    
    err = server.Run(":8080")
    if err != nil {
    	log.Println("gin server error = ", err)
    }
    

Response

  • When the consecutive requests and total request times is within limit, the request is allowed to continue.

  • When limit is reached, the request is aborted and a 429 HTTP status code is sent.



License

All source code is licensed under the MIT License.

# Functions

No description provided by the author
enforce rate limit based on ip address of client making the request.
enforce rate limit based on ip address of client and user making the request.
enforce rate limit based on the user making the request.

# Structs

RateLimiter is the limiter instance.