Skip to content

Commit 7947ff1

Browse files
authored
feat: limit max connection count (#2701)
1 parent 33bae52 commit 7947ff1

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

internal/conf/config.go

+2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ type Config struct {
4747
TempDir string `json:"temp_dir" env:"TEMP_DIR"`
4848
BleveDir string `json:"bleve_dir" env:"BLEVE_DIR"`
4949
Log LogConfig `json:"log"`
50+
MaxConnections int `json:"max_connections" env:"MAX_CONNECTIONS"`
5051
}
5152

5253
func DefaultConfig() *Config {
@@ -74,5 +75,6 @@ func DefaultConfig() *Config {
7475
MaxBackups: 5,
7576
MaxAge: 28,
7677
},
78+
MaxConnections: 0,
7779
}
7880
}

server/middlewares/limit.go

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package middlewares
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
)
6+
7+
func MaxAllowed(n int) gin.HandlerFunc {
8+
sem := make(chan struct{}, n)
9+
acquire := func() { sem <- struct{}{} }
10+
release := func() { <-sem }
11+
return func(c *gin.Context) {
12+
acquire()
13+
defer release()
14+
c.Next()
15+
}
16+
}

server/router.go

+3
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ func Init(r *gin.Engine) {
1616
common.SecretKey = []byte(conf.Conf.JwtSecret)
1717
Cors(r)
1818
r.Use(middlewares.StoragesLoaded)
19+
if conf.Conf.MaxConnections > 0 {
20+
r.Use(middlewares.MaxAllowed(conf.Conf.MaxConnections))
21+
}
1922
WebDav(r.Group("/dav"))
2023

2124
r.GET("/favicon.ico", handles.Favicon)

0 commit comments

Comments
 (0)