Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how can I limit the number of current requests? #955

Closed
wangcn opened this issue Jun 21, 2017 · 3 comments
Closed

how can I limit the number of current requests? #955

wangcn opened this issue Jun 21, 2017 · 3 comments
Labels

Comments

@wangcn
Copy link

wangcn commented Jun 21, 2017

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

@nazwa
Copy link

nazwa commented Jun 22, 2017

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
        }
    }
}

@easonlin404
Copy link
Contributor

@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()
}

@ammario
Copy link
Contributor

ammario commented Jul 7, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants