Add package-level doc comments for go doc and gopls

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-22 22:20:33 +03:00
parent 3aa7536328
commit 138d4b6c6d
6 changed files with 197 additions and 0 deletions

34
balancer/doc.go Normal file
View File

@@ -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

27
circuitbreaker/doc.go Normal file
View File

@@ -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

39
doc.go Normal file
View File

@@ -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

28
middleware/doc.go Normal file
View File

@@ -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

31
retry/doc.go Normal file
View File

@@ -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

38
server/doc.go Normal file
View File

@@ -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