Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions config/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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
// 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
}
17 changes: 8 additions & 9 deletions routing/options.go
Original file line number Diff line number Diff line change
@@ -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)

Expand All @@ -10,15 +13,11 @@ func WithRouters(routers ...func(*Engine)) Option {
}
}

func WithHealth(endpoint string) Option {
// WithConfig is how the server listens: its host, port and shutdown
// timeout, its health endpoint and the platform it trusts. Run needs it.
func WithConfig(server config.Server) Option {
return func(r *Routing) {
r.HealthEndpoint = endpoint
}
}

func WithTrustedPlatform(platform string) Option {
return func(r *Routing) {
r.TrustedPlatform = platform
r.Config = &server
}
}

Expand Down
60 changes: 31 additions & 29 deletions routing/routing.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -21,11 +22,10 @@ import (
)

type Routing struct {
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
Expand All @@ -44,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",
Expand Down Expand Up @@ -99,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),
Expand All @@ -118,23 +119,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 errors.New("[routing] no config: pass routing.WithConfig")
}
engine := r.Engine()

host := "0.0.0.0"
port := 80

if h := os.Getenv("HOST"); h != "" {
host = h
host, port := "0.0.0.0", 80
if r.Config.Host != "" {
host = r.Config.Host
}

if p := os.Getenv("PORT"); p != "" {
if p, err := strconv.Atoi(p); err == nil {
port = p
}
if r.Config.Port != 0 {
port = r.Config.Port
}

hostWithPort := net.JoinHostPort(host, fmt.Sprint(port))
Expand All @@ -159,20 +158,23 @@ func (r *Routing) Run() error {
case <-stopping.Done():
}

timeout := shutdownTimeout()
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)
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
// 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 30 * time.Second
return *r.Config
}
32 changes: 28 additions & 4 deletions routing/routing_test.go → tests/routing/routing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import (
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"syscall"
"testing"
"time"

"github.com/gonstruct/core/config"
"github.com/gonstruct/core/routing"
"github.com/gonstruct/core/routing/response"

Expand All @@ -27,12 +30,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)
Expand Down Expand Up @@ -93,3 +94,26 @@ 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(); 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)
}
}