feat: limit max connection count (#2701)

pull/2715/head
BoYanZh 2022-12-14 10:33:58 +08:00 committed by GitHub
parent 33bae52fa1
commit 7947ff1ae4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 0 deletions

View File

@ -47,6 +47,7 @@ type Config struct {
TempDir string `json:"temp_dir" env:"TEMP_DIR"` TempDir string `json:"temp_dir" env:"TEMP_DIR"`
BleveDir string `json:"bleve_dir" env:"BLEVE_DIR"` BleveDir string `json:"bleve_dir" env:"BLEVE_DIR"`
Log LogConfig `json:"log"` Log LogConfig `json:"log"`
MaxConnections int `json:"max_connections" env:"MAX_CONNECTIONS"`
} }
func DefaultConfig() *Config { func DefaultConfig() *Config {
@ -74,5 +75,6 @@ func DefaultConfig() *Config {
MaxBackups: 5, MaxBackups: 5,
MaxAge: 28, MaxAge: 28,
}, },
MaxConnections: 0,
} }
} }

View File

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

View File

@ -16,6 +16,9 @@ func Init(r *gin.Engine) {
common.SecretKey = []byte(conf.Conf.JwtSecret) common.SecretKey = []byte(conf.Conf.JwtSecret)
Cors(r) Cors(r)
r.Use(middlewares.StoragesLoaded) r.Use(middlewares.StoragesLoaded)
if conf.Conf.MaxConnections > 0 {
r.Use(middlewares.MaxAllowed(conf.Conf.MaxConnections))
}
WebDav(r.Group("/dav")) WebDav(r.Group("/dav"))
r.GET("/favicon.ico", handles.Favicon) r.GET("/favicon.ico", handles.Favicon)