Documentation
¶
Overview ¶
Package http provides HTTP utilities including chi-compatible error handling
Index ¶
- func CORSMiddleware(origins []string) func(http.Handler) http.Handler
- func ChiRoutePattern(r *http.Request) string
- func DefaultErrorHandler(w http.ResponseWriter, err error)
- func HandleError(h HandlerFunc) http.HandlerFunc
- func RequestMetricsMiddleware(m *HTTPMetrics) func(http.Handler) http.Handler
- func ServeAndWait(ctx context.Context, handler http.Handler, logger *zap.Logger, ...) error
- type HTTPMetrics
- type HandlerFunc
- type ServerConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CORSMiddleware ¶
CORSMiddleware returns a CORS middleware restricted to the given origins. If origins contains "*", all origins are permitted. Otherwise, the request Origin is reflected back only if it matches the allowlist.
func ChiRoutePattern ¶
ChiRoutePattern extracts the matched chi route pattern from the request context, e.g. "/v1/tokens/{id}" rather than the raw path. Falls back to "unknown" for unmatched routes (404s).
func DefaultErrorHandler ¶
func DefaultErrorHandler(w http.ResponseWriter, err error)
DefaultErrorHandler handles errors returned from HTTP handlers
func HandleError ¶
func HandleError(h HandlerFunc) http.HandlerFunc
HandleError wraps an error-returning HandlerFunc into a standard http.HandlerFunc This allows using clean error-returning handlers with any router (chi, http.ServeMux, etc.)
Usage with chi:
r.Post("/register", http.HandleError(handler.register))
func RequestMetricsMiddleware ¶
func RequestMetricsMiddleware(m *HTTPMetrics) func(http.Handler) http.Handler
RequestMetricsMiddleware returns a chi-compatible middleware that records HTTP request metrics: total count (by method/route/status), duration, and active connection gauge.
Route patterns (e.g. /v1/tokens/{id}) are used as the endpoint label rather than raw paths to avoid unbounded cardinality.
func ServeAndWait ¶
func ServeAndWait(ctx context.Context, handler http.Handler, logger *zap.Logger, cfg *ServerConfig) error
ServeAndWait starts an HTTP server with the given handler and config in a goroutine and blocks until either:
- ctx is canceled, or
- the server fails unexpectedly.
It then performs a graceful shutdown with the configured timeout.
Returns a non-nil error if:
- the server exits unexpectedly (not ErrServerClosed), or
- shutdown fails.
Types ¶
type HTTPMetrics ¶
type HTTPMetrics struct {
// RequestsTotal counts HTTP requests by method, route pattern, and status code.
RequestsTotal *prometheus.CounterVec
// RequestDuration tracks HTTP request processing time by method and route pattern.
RequestDuration *prometheus.HistogramVec
// ActiveConnections tracks the current number of in-flight HTTP requests.
ActiveConnections prometheus.Gauge
}
HTTPMetrics holds Prometheus collectors for an HTTP server. Create with NewHTTPMetrics and pass to RequestMetricsMiddleware.
func NewHTTPMetrics ¶
func NewHTTPMetrics(reg sharedmetrics.NamespacedRegisterer) *HTTPMetrics
NewHTTPMetrics registers HTTP server metrics against the given registerer. Metrics are named <namespace>_http_requests_total etc.
func (*HTTPMetrics) IncRequestsTotal ¶
func (m *HTTPMetrics) IncRequestsTotal(method, endpoint, statusCode string)
IncRequestsTotal increments the HTTP request counter.
func (*HTTPMetrics) ObserveRequestDuration ¶
func (m *HTTPMetrics) ObserveRequestDuration(method, endpoint string) prometheus.Observer
ObserveRequestDuration returns the observer for a request's duration.
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, *http.Request) error
HandlerFunc defines a function that returns an error for clean error handling
type ServerConfig ¶
type ServerConfig struct {
Host string `yaml:"host" validate:"required"`
Port int `yaml:"port" validate:"required,gt=0"`
ReadTimeout time.Duration `yaml:"read_timeout" default:"15s"`
WriteTimeout time.Duration `yaml:"write_timeout" default:"15s"`
IdleTimeout time.Duration `yaml:"idle_timeout" default:"60s"`
ShutdownTimeout time.Duration `yaml:"shutdown_timeout" default:"30s"`
}
ServerConfig contains HTTP server settings