From 6ad85c4bd167c9f114c1d2574f4887826689b76d Mon Sep 17 00:00:00 2001 From: mo khan Date: Thu, 13 Mar 2025 09:12:17 -0600 Subject: refactor: extract srv package --- cmd/gtwy/main.go | 21 +++++++-------------- pkg/srv/config.go | 42 ++++++++++++++++++++++++++++++++++++++++++ pkg/srv/srv.go | 24 ++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 14 deletions(-) create mode 100644 pkg/srv/config.go create mode 100644 pkg/srv/srv.go diff --git a/cmd/gtwy/main.go b/cmd/gtwy/main.go index 3d4a2472..8d1baa6f 100644 --- a/cmd/gtwy/main.go +++ b/cmd/gtwy/main.go @@ -6,11 +6,11 @@ import ( "net/http" "net/http/httputil" "strings" - "time" "github.com/casbin/casbin/v2" "github.com/xlgmokha/x/pkg/env" "github.com/xlgmokha/x/pkg/x" + "gitlab.com/mokhax/spike/pkg/srv" ) func NewRouter(routes map[string]string) http.Handler { @@ -48,21 +48,14 @@ func NewRouter(routes map[string]string) http.Handler { func main() { mux := http.NewServeMux() - routes := map[string]string{ + mux.Handle("/", NewRouter(map[string]string{ "idp.example.com": "localhost:8282", "ui.example.com": "localhost:8283", "api.example.com": "localhost:8284", - } - mux.Handle("/", NewRouter(routes)) + })) - bindAddress := env.Fetch("BIND_ADDR", ":8080") - log.Fatal((&http.Server{ - Addr: bindAddress, - Handler: mux, - ReadHeaderTimeout: 10 * time.Second, - ReadTimeout: 30 * time.Second, - WriteTimeout: 2 * time.Minute, - IdleTimeout: 5 * time.Minute, - ErrorLog: log.Default(), - }).ListenAndServe()) + log.Fatal(srv.Run(srv.NewConfig( + env.Fetch("BIND_ADDR", ":8080"), + srv.WithMux(mux), + ))) } diff --git a/pkg/srv/config.go b/pkg/srv/config.go new file mode 100644 index 00000000..c02a9c7a --- /dev/null +++ b/pkg/srv/config.go @@ -0,0 +1,42 @@ +package srv + +import ( + "crypto/tls" + "net/http" +) + +type Option func(*Config) + +type Config struct { + BindAddress string + Mux http.Handler + TLS *tls.Config +} + +func WithMux(mux http.Handler) Option { + return func(config *Config) { + config.Mux = mux + } +} + +func NewConfig(addr string, options ...Option) *Config { + if addr == "" { + addr = ":0" + } + + c := &Config{ + BindAddress: addr, + Mux: http.DefaultServeMux, + } + for _, option := range options { + option(c) + } + return c +} + +func (c *Config) Run(server *http.Server) error { + if c.TLS != nil { + return server.ListenAndServeTLS("", "") + } + return server.ListenAndServe() +} diff --git a/pkg/srv/srv.go b/pkg/srv/srv.go new file mode 100644 index 00000000..a2be3635 --- /dev/null +++ b/pkg/srv/srv.go @@ -0,0 +1,24 @@ +package srv + +import ( + "log" + "net/http" + "time" +) + +func New(cfg *Config) *http.Server { + return &http.Server{ + Addr: cfg.BindAddress, + Handler: cfg.Mux, + TLSConfig: cfg.TLS, + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 2 * time.Minute, + IdleTimeout: 5 * time.Minute, + ErrorLog: log.Default(), + } +} + +func Run(c *Config) error { + return c.Run(New(c)) +} -- cgit v1.2.3