For example, I allow up to 2000 current connections and reject excess requests.
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.
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)