diff --git a/internal/conf/config.go b/internal/conf/config.go index 735e870f..ea09cf75 100644 --- a/internal/conf/config.go +++ b/internal/conf/config.go @@ -47,6 +47,7 @@ type Config struct { TempDir string `json:"temp_dir" env:"TEMP_DIR"` BleveDir string `json:"bleve_dir" env:"BLEVE_DIR"` Log LogConfig `json:"log"` + MaxConnections int `json:"max_connections" env:"MAX_CONNECTIONS"` } func DefaultConfig() *Config { @@ -74,5 +75,6 @@ func DefaultConfig() *Config { MaxBackups: 5, MaxAge: 28, }, + MaxConnections: 0, } } diff --git a/server/middlewares/limit.go b/server/middlewares/limit.go new file mode 100644 index 00000000..44c079b3 --- /dev/null +++ b/server/middlewares/limit.go @@ -0,0 +1,16 @@ +package middlewares + +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() + defer release() + c.Next() + } +} diff --git a/server/router.go b/server/router.go index 84246792..d8e58254 100644 --- a/server/router.go +++ b/server/router.go @@ -16,6 +16,9 @@ func Init(r *gin.Engine) { common.SecretKey = []byte(conf.Conf.JwtSecret) Cors(r) r.Use(middlewares.StoragesLoaded) + if conf.Conf.MaxConnections > 0 { + r.Use(middlewares.MaxAllowed(conf.Conf.MaxConnections)) + } WebDav(r.Group("/dav")) r.GET("/favicon.ico", handles.Favicon)