httpserver

package
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

Shared HTTP server

This package owns the repository's Gin engine and HTTP server lifecycle. Services register routes on a caller-owned engine; the composing binary owns the listener, shutdown and deployment.

OpenAPI request validation

ValidateOpenAPIRequests builds a Gin middleware from an openapi3.T, openapi3filter.Options and a validation-error callback. It returns an error if the contract cannot initialize the schema router. Gin continues to route HTTP requests; kin-openapi's routers/legacy resolves the schema operation and openapi3filter validates the request. No Gorilla router or oapi-codegen/gin-middleware is used.

Install the middleware only on routes declared by that contract. The maintained consumer shows the generated-route mounting pattern:

  • Copilot Adapter passes it as middleware to the generated Gin registration.

The regression suite also demonstrates a route group with a custom URI format validator.

The caller supplies a non-nil error callback and owns its response body and authentication policy. Undeclared paths produce 404; other route lookup or request-validation failures produce 400. The adapter aborts the Gin chain after the callback. Successful validation preserves the request body for the handler, passes the request context to validation, and keeps Gin's complete path parameter values, including decoded trailing slashes. Treat the contract and validation options as immutable after registration.

The regression suite covers body preservation, unrelated routes, path/query/body validation, encoded path values, format options, request-context cancellation and invalid contracts. From the standalone repository root, run:

go test -mod=readonly -race ./pkg/httpserver ./services/copilot-adapter/...

The repository-wide dependency gate also checks manifests and imports. See its documentation before dependency maintenance: upstream kin-openapi still declares mux for its own tests.

Documentation

Overview

Package httpserver provides the shared Gin HTTP surface used by Candace services. Applications register routes; this package owns the behavior that must remain identical across service binaries.

Index

Constants

View Source
const BrowserContentSecurityPolicy = "default-src 'none'; " +
	"script-src 'self'; " +
	"style-src 'self'; " +
	"connect-src 'self'; " +
	"img-src 'self' data:; " +
	"object-src 'none'; " +
	"base-uri 'none'; " +
	"form-action 'none'; " +
	"frame-ancestors 'none'"

BrowserContentSecurityPolicy permits only the same-origin assets and socket needed by a server-rendered Candace page.

Variables

This section is empty.

Functions

func BindLifecycle added in v0.2.0

func BindLifecycle(ctx context.Context, server *http.Server) (restore func())

BindLifecycle merges ctx into the server's base context and returns the function that restores the original. Shutdown waits for active handlers but deliberately does not cancel them; with the process lifecycle merged in, an SSE or WebSocket handler observing request.Context exits before that drain, while any values or earlier cancellation the caller put on BaseContext are preserved.

func EncodeEvent

func EncodeEvent[Data any](writer io.Writer, identifier string, data Data) error

EncodeEvent writes one server-sent-event frame. It is gin-contrib/sse's encoder, named here so a streaming handler depends on this package alone. Data is a type parameter rather than any so the caller's frame type is carried to this boundary and erased exactly once, where the third-party encoder's own interface{} field demands it (CS-7).

func EventStream

func EventStream(context *gin.Context, step func(writer io.Writer) bool)

EventStream writes the server-sent-event headers and then runs step until it returns false or the client hangs up. gin's Stream owns the flush-per-step and client-gone loop; step writes frames, for which EncodeEvent is the encoder.

func EventStreamHeaders

func EventStreamHeaders() gin.HandlerFunc

EventStreamHeaders is the middleware form: mount it on a route group and every response in that group is a server-sent-event stream. Handlers that stream from inside a generated wrapper use EventStream instead.

func NewEngine

func NewEngine(service string, options ...EngineOption) *gin.Engine

NewEngine returns a quiet production Gin engine with explicit 404/405 behavior and panic recovery through core.Logger.

func NewStreamingServer

func NewStreamingServer(address string, handler http.Handler) *http.Server

NewStreamingServer returns the canonical server shape for long-lived SSE or WebSocket responses. It deliberately leaves ReadTimeout and WriteTimeout unset; ReadHeaderTimeout still bounds the unauthenticated request phase.

func Probe

func Probe(ctx context.Context, target string) error

Probe requests a health endpoint and requires a 2xx response.

func Recovery

func Recovery(service string) gin.HandlerFunc

Recovery converts a panic into a 500 response and records it with the shared logger. It deliberately does not include Gin's default text logger.

func RequestLogger

func RequestLogger(service string) gin.HandlerFunc

RequestLogger assigns or preserves a request ID and emits one structured log event after the request completes.

func Serve

func Serve(ctx context.Context, server *http.Server) error

Serve runs server until it fails or ctx is canceled, then performs a bounded graceful shutdown and waits for the listener goroutine to exit.

func Shutdown added in v0.2.0

func Shutdown(server *http.Server) error

Shutdown performs the bounded graceful shutdown every server here shares: drain within the shutdown budget, then close whatever is left.

func ShutdownWithin added in v0.2.0

func ShutdownWithin(server *http.Server, budget time.Duration) error

ShutdownWithin is Shutdown with an explicit drain budget, for a binary whose stop sequence must fit its supervisor's grace period.

func StrictBrowserSecurity

func StrictBrowserSecurity() gin.HandlerFunc

StrictBrowserSecurity applies the shared browser-facing response policy.

func ValidateOpenAPIRequests

func ValidateOpenAPIRequests(document *openapi3.T, options openapi3filter.Options, onError func(context *gin.Context, message string, statusCode int)) (gin.HandlerFunc, error)

ValidateOpenAPIRequests adapts kin-openapi validation to a caller-owned Gin router. Callers own authentication options and the validation error response. The returned middleware must be scoped to routes declared in the contract.

Types

type EngineOption

type EngineOption func(config *engineConfig)

EngineOption enables optional shared middleware.

func WithRequestLogging

func WithRequestLogging() EngineOption

WithRequestLogging adds structured completion logs and request IDs.

func WithStrictBrowserSecurity

func WithStrictBrowserSecurity() EngineOption

WithStrictBrowserSecurity applies the shared locked-down browser policy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL