Skip to content

HTTP Server & OpenAPI ​

boot/server/http.go wraps gin.Engine and net/http.Server with production-hardened defaults, health/readiness probes, TLS 1.2+, and Huma v2 OpenAPI 3.1 support.


HTTPServer & HTTPOption ​

go
type Router interface {
	Register(engine *gin.Engine)
}

func NewHTTPServer(cfg *config.AllConfig, routers []Router, opts ...HTTPOption) *HTTPServer

Available options:

  • server.WithReadinessCheck(fn func(context.Context) error) — boot/kernel.go wires db.Ping automatically.
  • server.WithLimiterStore(store *middleware.LimiterStore) — inject a shared or custom rate-limiter store (otherwise HTTPServer creates and owns one and closes it on Stop()).

Exposed methods:

  • Name() string — "HTTPS" if cfg.HTTP.TLSEnabled, else "HTTP".
  • Engine() *gin.Engine — returns the underlying Gin engine (used in httptest suites).
  • Start() error — calls ListenAndServeTLS (when TLS enabled) or ListenAndServe.
  • Stop(ctx context.Context) error — closes owned LimiterStore and calls http.Server.Shutdown(ctx).

Exact Middleware & Route Order ​

text
Incoming HTTP Request
  1. middleware.Recovery()               # Catches panics, logs stack + request_id, returns 500 AppError
  2. middleware.RequestID()              # Validates incoming X-Request-ID or generates 128-bit hex ID
  3. middleware.CustomLogger()           # Zerolog access log (method, path, status, ip, latency, request_id)
  4. middleware.CORSWithConfig(cfg.HTTP) # Strict origin & credential handling
  5. middleware.RateLimiterWithStore()   # Bounded token-bucket per ClientIP() -> 429 AppError
  6. middleware.ErrorHandler()           # Formats c.Errors into canonical AppError JSON, logs 5xx
  ├── GET /health                        # Public liveness probe (200 {"status":"healthy",...})
  ├── GET /ready                         # Public readiness probe (runs readinessCheck with 2s timeout -> 200 or 503)
  7. middleware.AppKeyWithConfig(cfg.App)# Constant-time X-App-Key check (docs paths exempt ONLY if APP_DEBUG=true)
  └── Registered server.Router instances # All service routes & Huma docs

Server Hardening Defaults ​

SettingDefaultConfig / Env Var
Gin Modegin.ReleaseMode when !cfg.App.DebugAPP_DEBUG
Trusted Proxiesnil (trusts NO proxies)TRUSTED_PROXIES (comma-separated CIDRs/IPs)
ReadHeaderTimeout10sHTTP_READ_HEADER_TIMEOUT
ReadTimeout30sHTTP_READ_TIMEOUT
WriteTimeout30sHTTP_WRITE_TIMEOUT
IdleTimeout120sHTTP_IDLE_TIMEOUT
MaxHeaderBytes1 MiB (1 << 20)Hardcoded in NewHTTPServer
TLS MinVersiontls.VersionTLS12TLS_ENABLED, TLS_CERT_FILE, TLS_KEY_FILE

OpenAPI 3.1 Docs with Huma v2 (boot/server/docs.go) ​

server.NewHumaConfig(title, version, docsPath) returns a preconfigured huma.Config:

  • DocsPath: docsPath (e.g., /api/docs/todo)
  • OpenAPIPath: docsPath + ".json" (e.g., /api/docs/todo.json)
  • SchemasPath: docsPath + "/schemas"
  • Security scheme AppKey (apiKey in header X-App-Key) applied globally.

Two Ways to Register Operations ​

  1. Live Huma Handler (huma.Register) — Huma handles routing, input parsing, and OpenAPI schema generation together:
    go
    api := humagin.New(engine, server.NewHumaConfig("Todo API", "1.0.0", "/api/docs/todo"))
    huma.Register(api, huma.Operation{
        OperationID: "get-health",
        Method:      http.MethodGet,
        Path:        "/api/todo/health",
        Summary:     "Health check",
        Tags:        []string{"Health"},
    }, func(ctx context.Context, _ *struct{}) (*struct{ Body string }, error) {
        return &struct{ Body string }{Body: "OK"}, nil
    })
  2. Spec-Only Documentation (api.OpenAPI().AddOperation) — Documents existing Gin or Limen routes without registering duplicate handlers:
    go
    api.OpenAPI().AddOperation(&huma.Operation{
        OperationID: "list-tasks",
        Method:      http.MethodGet,
        Path:        "/api/tasks",
        Summary:     "List tasks",
        Tags:        []string{"Tasks"},
    })

Released under the Apache-2.0 License.