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:
29
middleware/middleware.go
Normal file
29
middleware/middleware.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user