Browse Source

Limit max connections

DarthSim 7 years ago
parent
commit
1e9282c6b1
3 changed files with 16 additions and 2 deletions
  1. 1 0
      README.md
  2. 6 0
      config.go
  3. 9 2
      main.go

+ 1 - 0
README.md

@@ -131,6 +131,7 @@ $ xxd -g 2 -l 64 -p /dev/random | tr -d '\n'
 * `IMGPROXY_WRITE_TIMEOUT` — the maximum duration (in seconds) for writing the response. Default: `10`;
 * `IMGPROXY_DOWNLOAD_TIMEOUT` — the maximum duration (in seconds) for downloading the source image. Default: `5`;
 * `IMGPROXY_CONCURRENCY` — the maximum number of image requests to be processed simultaneously. Default: `100`;
+* `IMGPROXY_MAX_CLIENTS` — the maximum number of simultaneous active connections. Default: `IMGPROXY_CONCURRENCY * 2`;
 
 #### Security
 

+ 6 - 0
config.go

@@ -64,6 +64,7 @@ type config struct {
 	WriteTimeout    int
 	DownloadTimeout int
 	Concurrency     int
+	MaxClients      int
 	TTL             int
 
 	MaxSrcDimension int
@@ -99,6 +100,7 @@ func init() {
 	intEnvConfig(&conf.WriteTimeout, "IMGPROXY_WRITE_TIMEOUT")
 	intEnvConfig(&conf.DownloadTimeout, "IMGPROXY_DOWNLOAD_TIMEOUT")
 	intEnvConfig(&conf.Concurrency, "IMGPROXY_CONCURRENCY")
+	intEnvConfig(&conf.MaxClients, "IMGPROXY_MAX_CLIENTS")
 
 	intEnvConfig(&conf.TTL, "IMGPROXY_TTL")
 
@@ -142,6 +144,10 @@ func init() {
 		log.Fatalf("Concurrency should be greater than 0, now - %d\n", conf.Concurrency)
 	}
 
+	if conf.MaxClients <= 0 {
+		conf.MaxClients = conf.Concurrency * 2
+	}
+
 	if conf.TTL <= 0 {
 		log.Fatalf("TTL should be greater than 0, now - %d\n", conf.TTL)
 	}

+ 9 - 2
main.go

@@ -2,13 +2,20 @@ package main
 
 import (
 	"log"
+	"net"
 	"net/http"
 	"time"
+
+	"golang.org/x/net/netutil"
 )
 
 func main() {
+	l, err := net.Listen("tcp", conf.Bind)
+	if err != nil {
+		log.Fatal(err)
+	}
+
 	s := &http.Server{
-		Addr:           conf.Bind,
 		Handler:        newHttpHandler(),
 		ReadTimeout:    time.Duration(conf.ReadTimeout) * time.Second,
 		WriteTimeout:   time.Duration(conf.WriteTimeout) * time.Second,
@@ -17,5 +24,5 @@ func main() {
 
 	log.Printf("Starting server at %s\n", conf.Bind)
 
-	log.Fatal(s.ListenAndServe())
+	log.Fatal(s.Serve(netutil.LimitListener(l, conf.MaxClients)))
 }