Gin: how can I limit the number of current requests?

Created on 21 Jun 2017  路  3Comments  路  Source: gin-gonic/gin

For example, I allow up to 2000 current connections and reject excess requests.

question

Most helpful comment

You could write a middleware that tries to insert into a buffered channel every time a new connection is made.

(this is just proof of concept, not valid syntax)


func LimitMiddleware() gin.HandlerFunc {
     // create a buffered channel with 2000 spaces
     semaphore := make(chan bool, 2000) 


    return func (c *gin.Context) {        
        select {
            case semaphore  <- true: // Try putting a new val into our semaphore
                // Ok, managed to get a space in queue. execute the handler
                c.Next()

                // Don't forget to release a handle
                <-semaphore 
            default:
                 // Buffer full, so drop the connection. Return whatever status you want here
                 return
        }
    }
}


All 3 comments

You could write a middleware that tries to insert into a buffered channel every time a new connection is made.

(this is just proof of concept, not valid syntax)


func LimitMiddleware() gin.HandlerFunc {
     // create a buffered channel with 2000 spaces
     semaphore := make(chan bool, 2000) 


    return func (c *gin.Context) {        
        select {
            case semaphore  <- true: // Try putting a new val into our semaphore
                // Ok, managed to get a space in queue. execute the handler
                c.Next()

                // Don't forget to release a handle
                <-semaphore 
            default:
                 // Buffer full, so drop the connection. Return whatever status you want here
                 return
        }
    }
}


@wangcn I have written gin's limit middleware to limit the number of current requests and it can better handle requests limit when panic occurs, you can use it as follows:

package main

import (
    "github.com/easonlin404/limit"
    "github.com/gin-gonic/gin"
)

func main() {

    r := gin.Default()
    r.Use(limit.Limit(200)) // limit the number of current requests

    r.GET("/", func(c *gin.Context) {
        // your code
    })

    r.Run()
}

Using sync/atomic may be preferable here since your're never blocking.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sofish picture sofish  路  3Comments

gplume picture gplume  路  3Comments

mdnight picture mdnight  路  3Comments

olegsobchuk picture olegsobchuk  路  3Comments

ccaza picture ccaza  路  3Comments