Files
galaxy-game/game/internal/router/middleware.go
T
Ilia Denisov 9ade76e21d fs storage
2026-03-13 21:07:23 +02:00

29 lines
562 B
Go

package router
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// LimitMiddleware limits number of concurrent connections using a buffered channel with limit spaces
func LimitMiddleware(limit int) gin.HandlerFunc {
if limit <= 0 {
panic("limit must be greater than 0")
}
semaphore := make(chan bool, limit)
t := time.NewTimer(time.Millisecond * 100)
return func(c *gin.Context) {
t.Reset(time.Millisecond * 100)
select {
case semaphore <- true:
c.Next()
<-semaphore
case <-t.C:
c.Status(http.StatusGatewayTimeout)
}
}
}