meetandeat/runtime/limit.go

18 lines
318 B
Go
Raw Permalink Normal View History

2019-03-22 16:35:16 +01:00
package runtime
import (
"github.com/gin-gonic/gin"
)
func MaxAllowed(n int) gin.HandlerFunc {
sem := make(chan struct{}, n)
acquire := func() { sem <- struct{}{} }
release := func() { <-sem }
return func(c *gin.Context) {
acquire() // before request
defer release() // after request
c.Next()
}
}