Overview
The SDK providesoption.WithMiddleware which applies the given middleware to requests. Middleware allows you to intercept requests before they’re sent and responses after they’re received.
Creating Middleware
Middleware is a function that receives an HTTP request and a next handler, and returns a response and error.Basic Middleware Example
Applying Middleware
Middleware can be applied at the client level or per-request.Client-Level Middleware
Per-Request Middleware
You can also apply middleware to individual requests:Middleware Execution Order
When multiple middlewares are provided as variadic arguments, the middlewares are applied left to right.
option.WithMiddleware is given multiple times, for example first in the client then the method, the middleware in the client will run first and the middleware given in the method will run next.
Multiple Middleware Example
- Logger (before request)
- Authentication (before request)
- RateLimiter (before request)
- Actual HTTP request
- RateLimiter (after response)
- Authentication (after response)
- Logger (after response)
Custom HTTP Client
You may also replace the default
http.Client with option.WithHTTPClient(client).Use Cases
Middleware is useful for:- Logging: Track request/response details and timing
- Authentication: Add custom authentication headers
- Rate limiting: Implement client-side rate limiting
- Retry logic: Implement custom retry strategies
- Monitoring: Send metrics to monitoring services
- Request modification: Modify requests before they’re sent
- Response transformation: Transform responses before they’re returned
