Add foundation: middleware type, error types, and internal clock

Introduce the core building blocks for the httpx library:
- middleware.Middleware type and Chain() composer
- Error struct with sentinel errors (ErrRetryExhausted, ErrCircuitOpen, ErrNoHealthy)
- internal/clock package with Clock interface and MockClock for deterministic testing
This commit is contained in:
2026-03-20 14:21:43 +03:00
parent f2a4a4fccc
commit 6b1941fce7
4 changed files with 226 additions and 0 deletions

29
middleware/middleware.go Normal file
View File

@@ -0,0 +1,29 @@
package middleware
import "net/http"
// Middleware wraps an http.RoundTripper to add behavior.
// This is the fundamental building block of the httpx library.
type Middleware func(http.RoundTripper) http.RoundTripper
// Chain composes middlewares so that Chain(A, B, C)(base) == A(B(C(base))).
// Middlewares are applied from right to left: C wraps base first, then B wraps
// the result, then A wraps last. This means A is the outermost layer and sees
// every request first.
func Chain(mws ...Middleware) Middleware {
return func(rt http.RoundTripper) http.RoundTripper {
for i := len(mws) - 1; i >= 0; i-- {
rt = mws[i](rt)
}
return rt
}
}
// RoundTripperFunc is an adapter to allow the use of ordinary functions as
// http.RoundTripper. It works exactly like http.HandlerFunc for handlers.
type RoundTripperFunc func(*http.Request) (*http.Response, error)
// RoundTrip implements http.RoundTripper.
func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}