From 03e009a243a81274076a398f36e0149d8de8f02c Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Mon, 23 Nov 2026 14:45:14 +0000 Subject: [PATCH 1/2] feat(routing)!: the server listens as its config says Run read HOST, PORT and SHUTDOWN_TIMEOUT from the environment itself. It now takes config.Server, handed to routing.WithConfig, which it needs: without one, Run fails with ErrNoConfig. An empty host is 0.0.0.0, port 0 is 80, and no timeout is 30s, as before. BREAKING CHANGE: routing.WithConfig is required to Run. --- config/server.go | 14 +++++++ routing/options.go | 13 +++++- routing/routing.go | 46 ++++++++++------------ {routing => tests/routing}/routing_test.go | 14 +++++-- 4 files changed, 57 insertions(+), 30 deletions(-) create mode 100644 config/server.go rename {routing => tests/routing}/routing_test.go (85%) diff --git a/config/server.go b/config/server.go new file mode 100644 index 0000000..08d4bae --- /dev/null +++ b/config/server.go @@ -0,0 +1,14 @@ +package config + +import "time" + +// Server is how the HTTP server listens, handed to routing.WithConfig. +type Server struct { + // Host is the address it listens on: 0.0.0.0 when empty. + Host string + // Port is the port it listens on: 80 when 0. + Port int + // ShutdownTimeout is how long a stopping server lets the requests in + // flight finish: 30s when 0. + ShutdownTimeout time.Duration +} diff --git a/routing/options.go b/routing/options.go index 5afea60..d9786df 100644 --- a/routing/options.go +++ b/routing/options.go @@ -1,6 +1,9 @@ package routing -import "github.com/gonstruct/core/routing/response" +import ( + "github.com/gonstruct/core/config" + "github.com/gonstruct/core/routing/response" +) type Option func(*Routing) @@ -10,6 +13,14 @@ func WithRouters(routers ...func(*Engine)) Option { } } +// WithConfig is how the server listens: its host, port and shutdown +// timeout. Run needs it. +func WithConfig(server config.Server) Option { + return func(r *Routing) { + r.Config = &server + } +} + func WithHealth(endpoint string) Option { return func(r *Routing) { r.HealthEndpoint = endpoint diff --git a/routing/routing.go b/routing/routing.go index f437b25..7f4ec46 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -2,15 +2,16 @@ package routing import ( "context" + "errors" "fmt" "net" "net/http" "os" "os/signal" - "strconv" "syscall" "time" + "github.com/gonstruct/core/config" "github.com/gonstruct/core/console" "github.com/gonstruct/core/routing/requestid" "github.com/gonstruct/core/routing/response" @@ -20,7 +21,11 @@ import ( "github.com/gin-gonic/gin" ) +// ErrNoConfig is Run without WithConfig. +var ErrNoConfig = errors.New("[routing] no config: pass routing.WithConfig") + type Routing struct { + Config *config.Server Routers []func(*Engine) Middlewares MiddlewareEngine Recovery RecoveryHandler @@ -118,23 +123,21 @@ func (r *Routing) Engine() *Engine { // Run serves until the process is asked to stop, by SIGTERM as a container // is or by an interrupt, then takes no new connections and lets the -// requests already in flight finish, for up to SHUTDOWN_TIMEOUT (30s when -// unset): a deploy that starts a new container beside this one and then -// stops it drops nothing. +// requests already in flight finish, for up to the config's +// ShutdownTimeout: a deploy that starts a new container beside this one and +// then stops it drops nothing. func (r *Routing) Run() error { + if r.Config == nil { + return ErrNoConfig + } engine := r.Engine() - host := "0.0.0.0" - port := 80 - - if h := os.Getenv("HOST"); h != "" { - host = h + host, port := r.Config.Host, r.Config.Port + if host == "" { + host = "0.0.0.0" } - - if p := os.Getenv("PORT"); p != "" { - if p, err := strconv.Atoi(p); err == nil { - port = p - } + if port == 0 { + port = 80 } hostWithPort := net.JoinHostPort(host, fmt.Sprint(port)) @@ -159,20 +162,13 @@ func (r *Routing) Run() error { case <-stopping.Done(): } - timeout := shutdownTimeout() + timeout := r.Config.ShutdownTimeout + if timeout <= 0 { + timeout = 30 * time.Second + } log.Info().Msgf("Stopping: finishing the requests in flight, for up to %s.", timeout) finishing, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return server.Shutdown(finishing) } - -// shutdownTimeout is how long a stopping server waits for its requests in -// flight: SHUTDOWN_TIMEOUT as a duration, 30s when unset or unreadable. -func shutdownTimeout() time.Duration { - if value, err := time.ParseDuration(os.Getenv("SHUTDOWN_TIMEOUT")); err == nil && value > 0 { - return value - } - - return 30 * time.Second -} diff --git a/routing/routing_test.go b/tests/routing/routing_test.go similarity index 85% rename from routing/routing_test.go rename to tests/routing/routing_test.go index 34373bb..242c043 100644 --- a/routing/routing_test.go +++ b/tests/routing/routing_test.go @@ -1,6 +1,7 @@ package routing_test import ( + "errors" "fmt" "io" "net" @@ -10,6 +11,7 @@ import ( "testing" "time" + "github.com/gonstruct/core/config" "github.com/gonstruct/core/routing" "github.com/gonstruct/core/routing/response" @@ -27,12 +29,10 @@ func TestRunFinishesTheRequestsInFlightWhenStopped(t *testing.T) { if err := listener.Close(); err != nil { t.Fatal(err) } - t.Setenv("HOST", "127.0.0.1") - t.Setenv("PORT", fmt.Sprint(port)) - t.Setenv("SHUTDOWN_TIMEOUT", "5s") started := make(chan struct{}) - server := routing.New(routing.WithRouters(func(engine *routing.Engine) { + listening := config.Server{Host: "127.0.0.1", Port: port, ShutdownTimeout: 5 * time.Second} + server := routing.New(routing.WithConfig(listening), routing.WithRouters(func(engine *routing.Engine) { engine.GET("/slow", func(*gin.Context) response.Response { close(started) time.Sleep(300 * time.Millisecond) @@ -93,3 +93,9 @@ func TestRunFinishesTheRequestsInFlightWhenStopped(t *testing.T) { t.Fatal("expected the stopped server to take no new connections") } } + +func TestRunNeedsAConfig(t *testing.T) { + if err := routing.New().Run(); !errors.Is(err, routing.ErrNoConfig) { + t.Fatalf("expected ErrNoConfig, got %v", err) + } +} From 2fe5438559f6cda8c8edffa69a05275417a03c91 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Mon, 23 Nov 2026 15:56:17 +0000 Subject: [PATCH 2/2] refactor(routing): take the health endpoint and trusted platform from the server config Both are how the server is set up, like its host and port, so they sit in config.Server instead of options of their own. The missing config error is returned inline and the defaults are set before the config overrides them. --- config/server.go | 7 +++++ routing/options.go | 14 +--------- routing/routing.go | 48 ++++++++++++++++++++--------------- tests/routing/routing_test.go | 24 +++++++++++++++--- 4 files changed, 56 insertions(+), 37 deletions(-) diff --git a/config/server.go b/config/server.go index 08d4bae..3f4b20a 100644 --- a/config/server.go +++ b/config/server.go @@ -11,4 +11,11 @@ type Server struct { // ShutdownTimeout is how long a stopping server lets the requests in // flight finish: 30s when 0. ShutdownTimeout time.Duration + // HealthEndpoint is the path that answers healthy while the server + // runs, for a load balancer or a container's health check: none when + // empty. + HealthEndpoint string + // TrustedPlatform is the header the platform in front of the server + // puts the client's IP in, as gin's TrustedPlatform: none when empty. + TrustedPlatform string } diff --git a/routing/options.go b/routing/options.go index d9786df..976f7a5 100644 --- a/routing/options.go +++ b/routing/options.go @@ -14,25 +14,13 @@ func WithRouters(routers ...func(*Engine)) Option { } // WithConfig is how the server listens: its host, port and shutdown -// timeout. Run needs it. +// timeout, its health endpoint and the platform it trusts. Run needs it. func WithConfig(server config.Server) Option { return func(r *Routing) { r.Config = &server } } -func WithHealth(endpoint string) Option { - return func(r *Routing) { - r.HealthEndpoint = endpoint - } -} - -func WithTrustedPlatform(platform string) Option { - return func(r *Routing) { - r.TrustedPlatform = platform - } -} - func WithRecovery(handler RecoveryHandler) Option { return func(r *Routing) { r.Recovery = handler diff --git a/routing/routing.go b/routing/routing.go index 7f4ec46..e09091b 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -21,16 +21,11 @@ import ( "github.com/gin-gonic/gin" ) -// ErrNoConfig is Run without WithConfig. -var ErrNoConfig = errors.New("[routing] no config: pass routing.WithConfig") - type Routing struct { - Config *config.Server - Routers []func(*Engine) - Middlewares MiddlewareEngine - Recovery RecoveryHandler - HealthEndpoint string - TrustedPlatform string + Config *config.Server + Routers []func(*Engine) + Middlewares MiddlewareEngine + Recovery RecoveryHandler } type RecoveryHandler func(context *gin.Context, recovered any) response.Response @@ -49,8 +44,9 @@ func (r *Routing) Engine() *Engine { gin.SetMode(gin.ReleaseMode) router := NewEngine() + server := r.server() - router.TrustedPlatform = r.TrustedPlatform + router.TrustedPlatform = server.TrustedPlatform router.ContextWithFallback = true router.RemoteIPHeaders = []string{ "CF-Connecting-IP", @@ -104,9 +100,9 @@ func (r *Routing) Engine() *Engine { return response.NotFound(response.WithMessage("Route not found")) }) - if r.HealthEndpoint != "" { + if server.HealthEndpoint != "" { startedAt := time.Now() - router.GET(r.HealthEndpoint, func(c *gin.Context) response.Response { + router.GET(server.HealthEndpoint, func(c *gin.Context) response.Response { return response.Success(response.WithRaw(map[string]any{ "status": "healthy", "uptime": time.Since(startedAt), @@ -128,16 +124,16 @@ func (r *Routing) Engine() *Engine { // then stops it drops nothing. func (r *Routing) Run() error { if r.Config == nil { - return ErrNoConfig + return errors.New("[routing] no config: pass routing.WithConfig") } engine := r.Engine() - host, port := r.Config.Host, r.Config.Port - if host == "" { - host = "0.0.0.0" + host, port := "0.0.0.0", 80 + if r.Config.Host != "" { + host = r.Config.Host } - if port == 0 { - port = 80 + if r.Config.Port != 0 { + port = r.Config.Port } hostWithPort := net.JoinHostPort(host, fmt.Sprint(port)) @@ -162,9 +158,9 @@ func (r *Routing) Run() error { case <-stopping.Done(): } - timeout := r.Config.ShutdownTimeout - if timeout <= 0 { - timeout = 30 * time.Second + timeout := 30 * time.Second + if r.Config.ShutdownTimeout > 0 { + timeout = r.Config.ShutdownTimeout } log.Info().Msgf("Stopping: finishing the requests in flight, for up to %s.", timeout) finishing, cancel := context.WithTimeout(context.Background(), timeout) @@ -172,3 +168,13 @@ func (r *Routing) Run() error { return server.Shutdown(finishing) } + +// server is the config the routes are built from: none yet when only the +// engine is asked for, as a test does. +func (r *Routing) server() config.Server { + if r.Config == nil { + return config.Server{} + } + + return *r.Config +} diff --git a/tests/routing/routing_test.go b/tests/routing/routing_test.go index 242c043..103d772 100644 --- a/tests/routing/routing_test.go +++ b/tests/routing/routing_test.go @@ -1,12 +1,13 @@ package routing_test import ( - "errors" "fmt" "io" "net" "net/http" + "net/http/httptest" "os" + "strings" "syscall" "testing" "time" @@ -95,7 +96,24 @@ func TestRunFinishesTheRequestsInFlightWhenStopped(t *testing.T) { } func TestRunNeedsAConfig(t *testing.T) { - if err := routing.New().Run(); !errors.Is(err, routing.ErrNoConfig) { - t.Fatalf("expected ErrNoConfig, got %v", err) + if err := routing.New().Run(); err == nil || !strings.Contains(err.Error(), "no config") { + t.Fatalf("expected no config, got %v", err) + } +} + +// The health endpoint is the config's, and there is none without it. +func TestTheHealthEndpointIsTheConfigs(t *testing.T) { + healthy := routing.New(routing.WithConfig(config.Server{HealthEndpoint: "/health"})).Engine().Handler() + recorder := httptest.NewRecorder() + healthy.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/health", nil)) + if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "healthy") { + t.Fatalf("expected healthy, got %d: %s", recorder.Code, recorder.Body) + } + + bare := routing.New(routing.WithConfig(config.Server{})).Engine().Handler() + recorder = httptest.NewRecorder() + bare.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/health", nil)) + if recorder.Code != http.StatusNotFound { + t.Fatalf("expected no health endpoint, got %d", recorder.Code) } }