From 0c6e174d82c245429301c9412e6a5d76fccc93d0 Mon Sep 17 00:00:00 2001 From: Mikalai Konan Date: Fri, 31 Dec 2021 15:43:45 +0300 Subject: [PATCH] configurable concurrency limit --- main.go | 5 +++-- proxy/config.go | 7 +++++-- proxy/router.go | 19 +++++++++++-------- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/main.go b/main.go index 2cc8c78..af6471a 100644 --- a/main.go +++ b/main.go @@ -43,8 +43,9 @@ func newApp() *app { KucoinApiURL: "https://openapi-v2.kucoin.com", }, ProxyConfig: proxy.Config{ - Port: "8080", - Bindaddr: "0.0.0.0", + Port: "8080", + Bindaddr: "0.0.0.0", + ConcurrencyLimit: fasthttp.DefaultConcurrency, }, } } diff --git a/proxy/config.go b/proxy/config.go index c2caf78..674f4fc 100644 --- a/proxy/config.go +++ b/proxy/config.go @@ -3,16 +3,19 @@ package proxy import ( validation "github.com/go-ozzo/ozzo-validation/v4" "github.com/go-ozzo/ozzo-validation/v4/is" + "github.com/valyala/fasthttp" ) type Config struct { - Port string `help:"listen port"` - Bindaddr string `help:"bindable address"` + Port string `help:"listen port"` + Bindaddr string `help:"bindable address"` + ConcurrencyLimit int `help:"server concurrency limit"` } func (c Config) Validate() error { return validation.ValidateStruct(&c, validation.Field(&c.Port, is.Port), validation.Field(&c.Bindaddr, is.IPv4), + validation.Field(&c.ConcurrencyLimit, validation.Min(fasthttp.DefaultConcurrency)), ) } diff --git a/proxy/router.go b/proxy/router.go index 149f85b..082d2ee 100644 --- a/proxy/router.go +++ b/proxy/router.go @@ -20,7 +20,7 @@ type Routable interface { Name() string } -func New(config *Config, routable Routable) *Router { +func New(config *Config, routable Routable) *Server { router := routing.New() for _, route := range routable.Routes() { @@ -35,18 +35,21 @@ func New(config *Config, routable Routable) *Router { router.To(route.Method, path, route.Handler) } - return &Router{ - router: router, + return &Server{ + server: &fasthttp.Server{ + Handler: router.HandleRequest, + Concurrency: config.ConcurrencyLimit, + }, config: config, } } -type Router struct { +type Server struct { config *Config - router *routing.Router + server *fasthttp.Server } -func (r *Router) Serve() { - logrus.Infof("starting proxy server on :%s port...", r.config.Port) - panic(fasthttp.ListenAndServe(fmt.Sprintf("%s:%s", r.config.Bindaddr, r.config.Port), r.router.HandleRequest)) +func (s *Server) Serve() { + logrus.Infof("starting proxy server on :%s port...", s.config.Port) + logrus.Fatal(s.server.ListenAndServe(fmt.Sprintf("%s:%s", s.config.Bindaddr, s.config.Port))) }