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