From 138d4b6c6d66c3ef8dddcd987786c53585faf993 Mon Sep 17 00:00:00 2001 From: Aleksey Shakhmatov Date: Sun, 22 Mar 2026 22:20:33 +0300 Subject: [PATCH] Add package-level doc comments for go doc and gopls Co-Authored-By: Claude Opus 4.6 (1M context) --- balancer/doc.go | 34 ++++++++++++++++++++++++++++++++++ circuitbreaker/doc.go | 27 +++++++++++++++++++++++++++ doc.go | 39 +++++++++++++++++++++++++++++++++++++++ middleware/doc.go | 28 ++++++++++++++++++++++++++++ retry/doc.go | 31 +++++++++++++++++++++++++++++++ server/doc.go | 38 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 197 insertions(+) create mode 100644 balancer/doc.go create mode 100644 circuitbreaker/doc.go create mode 100644 doc.go create mode 100644 middleware/doc.go create mode 100644 retry/doc.go create mode 100644 server/doc.go diff --git a/balancer/doc.go b/balancer/doc.go new file mode 100644 index 0000000..d9cd051 --- /dev/null +++ b/balancer/doc.go @@ -0,0 +1,34 @@ +// Package balancer provides client-side load balancing as HTTP middleware. +// +// It distributes requests across multiple backend endpoints using pluggable +// strategies (round-robin, weighted, failover) with optional health checking. +// +// # Usage +// +// mw, closer := balancer.Transport( +// []balancer.Endpoint{ +// {URL: "http://backend1:8080"}, +// {URL: "http://backend2:8080"}, +// }, +// balancer.WithStrategy(balancer.RoundRobin()), +// balancer.WithHealthCheck(5 * time.Second), +// ) +// defer closer.Close() +// transport := mw(http.DefaultTransport) +// +// # Strategies +// +// - RoundRobin — cycles through healthy endpoints +// - Weighted — distributes based on endpoint Weight field +// - Failover — prefers primary, falls back to secondaries +// +// # Health checking +// +// When enabled, a background goroutine periodically probes each endpoint. +// The returned Closer must be closed to stop the health checker goroutine. +// In httpx.Client, this is handled by Client.Close(). +// +// # Sentinel errors +// +// ErrNoHealthy is returned when no healthy endpoints are available. +package balancer diff --git a/circuitbreaker/doc.go b/circuitbreaker/doc.go new file mode 100644 index 0000000..20cdc1b --- /dev/null +++ b/circuitbreaker/doc.go @@ -0,0 +1,27 @@ +// Package circuitbreaker provides a per-host circuit breaker as HTTP middleware. +// +// The circuit breaker monitors request failures and temporarily blocks requests +// to unhealthy hosts, allowing them time to recover before retrying. +// +// # State machine +// +// - Closed — normal operation, requests pass through +// - Open — too many failures, requests are rejected with ErrCircuitOpen +// - HalfOpen — after a cooldown period, one probe request is allowed through +// +// # Usage +// +// mw := circuitbreaker.Transport( +// circuitbreaker.WithThreshold(5), +// circuitbreaker.WithTimeout(30 * time.Second), +// ) +// transport := mw(http.DefaultTransport) +// +// The circuit breaker is per-host: each unique request host gets its own +// independent breaker state machine stored in a sync.Map. +// +// # Sentinel errors +// +// ErrCircuitOpen is returned when a request is rejected because the circuit +// is in the Open state. +package circuitbreaker diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..b9f36ae --- /dev/null +++ b/doc.go @@ -0,0 +1,39 @@ +// Package httpx provides a high-level HTTP client with composable middleware +// for retry, circuit breaking, load balancing, structured logging, and more. +// +// The client is configured via functional options and assembled as a middleware +// chain around a standard http.RoundTripper: +// +// Logging → User Middlewares → Retry → Circuit Breaker → Balancer → Transport +// +// # Quick start +// +// client := httpx.New( +// httpx.WithBaseURL("https://api.example.com"), +// httpx.WithTimeout(10 * time.Second), +// httpx.WithRetry(), +// httpx.WithCircuitBreaker(), +// ) +// defer client.Close() +// +// resp, err := client.Get(ctx, "/users/1") +// +// # Request builders +// +// NewJSONRequest and NewFormRequest create requests with appropriate +// Content-Type headers and GetBody set for retry compatibility. +// +// # Error handling +// +// Failed requests return *httpx.Error with structured fields (Op, URL, +// StatusCode). Sentinel errors ErrRetryExhausted, ErrCircuitOpen, and +// ErrNoHealthy can be checked with errors.Is. +// +// # Sub-packages +// +// - middleware — client-side middleware (logging, auth, headers, recovery, request ID) +// - retry — configurable retry with backoff and Retry-After support +// - circuitbreaker — per-host circuit breaker (closed → open → half-open) +// - balancer — client-side load balancing with health checking +// - server — production HTTP server with router, middleware, and graceful shutdown +package httpx diff --git a/middleware/doc.go b/middleware/doc.go new file mode 100644 index 0000000..78208be --- /dev/null +++ b/middleware/doc.go @@ -0,0 +1,28 @@ +// Package middleware provides client-side HTTP middleware for use with +// httpx.Client or any http.RoundTripper-based transport chain. +// +// Each middleware is a function of type func(http.RoundTripper) http.RoundTripper. +// Compose them with Chain: +// +// chain := middleware.Chain( +// middleware.Logging(logger), +// middleware.Recovery(), +// middleware.UserAgent("my-service/1.0"), +// ) +// transport := chain(http.DefaultTransport) +// +// # Available middleware +// +// - Logging — structured request/response logging via slog +// - Recovery — panic recovery, converts panics to errors +// - DefaultHeaders — adds default headers to outgoing requests +// - UserAgent — sets User-Agent header +// - BearerAuth — dynamic Bearer token authentication +// - BasicAuth — HTTP Basic authentication +// - RequestID — propagates request ID from context to X-Request-Id header +// +// # RoundTripperFunc +// +// RoundTripperFunc adapts plain functions to http.RoundTripper, similar to +// http.HandlerFunc. Useful for testing and inline middleware. +package middleware diff --git a/retry/doc.go b/retry/doc.go new file mode 100644 index 0000000..54646a0 --- /dev/null +++ b/retry/doc.go @@ -0,0 +1,31 @@ +// Package retry provides configurable HTTP request retry as client middleware. +// +// The retry middleware wraps an http.RoundTripper and automatically retries +// failed requests based on a configurable policy, with exponential backoff +// and optional jitter. +// +// # Usage +// +// mw := retry.Transport( +// retry.WithMaxAttempts(3), +// retry.WithBackoff(retry.ExponentialBackoff(100*time.Millisecond, 5*time.Second)), +// ) +// transport := mw(http.DefaultTransport) +// +// # Retry-After +// +// The retry middleware respects the Retry-After response header. If a server +// returns 429 or 503 with Retry-After, the delay from the header overrides +// the backoff strategy. +// +// # Request bodies +// +// For requests with bodies to be retried, the request must have GetBody set. +// Use httpx.NewJSONRequest or httpx.NewFormRequest which set GetBody +// automatically. +// +// # Sentinel errors +// +// ErrRetryExhausted is returned when all attempts fail. The original error +// is wrapped and accessible via errors.Unwrap. +package retry diff --git a/server/doc.go b/server/doc.go new file mode 100644 index 0000000..b3d79b0 --- /dev/null +++ b/server/doc.go @@ -0,0 +1,38 @@ +// Package server provides a production-ready HTTP server with graceful +// shutdown, middleware composition, routing, and JSON response helpers. +// +// # Server +// +// Server wraps http.Server with net.Listener, signal-based graceful shutdown +// (SIGINT/SIGTERM), and lifecycle hooks. It is configured via functional options: +// +// srv := server.New(handler, +// server.WithAddr(":8080"), +// server.Defaults(logger), +// ) +// srv.ListenAndServe() +// +// # Router +// +// Router wraps http.ServeMux with middleware groups, prefix-based route groups, +// and sub-handler mounting. It supports Go 1.22+ method-based patterns: +// +// r := server.NewRouter() +// r.HandleFunc("GET /users/{id}", getUser) +// +// api := r.Group("/api/v1", authMiddleware) +// api.HandleFunc("GET /items", listItems) +// +// # Middleware +// +// Server middleware follows the func(http.Handler) http.Handler pattern. +// Available middleware: RequestID, Recovery, Logging, CORS, RateLimit, +// MaxBodySize, Timeout. Use Chain to compose them: +// +// chain := server.Chain(server.RequestID(), server.Recovery(logger), server.Logging(logger)) +// +// # Response helpers +// +// WriteJSON and WriteError provide JSON response writing with proper +// Content-Type headers. +package server