From 47a90eef81608322674c6fbe398730f423d2d8c5 Mon Sep 17 00:00:00 2001 From: Joeky Date: Fri, 17 Mar 2023 23:15:50 +0800 Subject: [PATCH] Add thread pool Signed-off-by: Joeky --- main.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/main.go b/main.go index 311d399..77f1a4d 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,14 @@ import ( "time" ) +var poolGuard chan struct{} + +const MaxGoroutine = 512 + +func init() { + poolGuard = make(chan struct{}, MaxGoroutine) +} + func handleTunneling(w http.ResponseWriter, r *http.Request) { destConn, err := net.DialTimeout("tcp", r.Host, 10*time.Second) if err != nil { @@ -59,10 +67,20 @@ func copyHeader(dst, src http.Header) { } } +func acquireRequestPool() { + poolGuard <- struct{}{} // Would block if guard channel is full +} + +func releaseRequestPool() { + <-poolGuard +} + func main() { server := &http.Server{ Addr: ":13002", Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + acquireRequestPool() + defer releaseRequestPool() if r.Method == http.MethodConnect { handleTunneling(w, r) } else {