-
Notifications
You must be signed in to change notification settings - Fork 7.9k
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
Labels
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example, I allow up to 2000 current connections and reject excess requests.
The text was updated successfully, but these errors were encountered: