Repository navigation
A production-ready HTTP client package with automatic token management, caching, and retry logic for service-to-service communication
The new pkg/http package provides:
- Automatic Token Management: Fetches and caches service tokens with expiration handling
- Token Refresh on 401: Automatically refreshes tokens when receiving 401 Unauthorized responses
- Retry Logic: Configurable retry with exponential backoff for failed requests
- Thread-Safe: Safe for concurrent use with proper locking
- Context Support: Full context.Context support for cancellation and timeouts
- Request/Response Hooks: Extensible hooks for custom request/response processing
- JSON Helpers: Convenient methods for JSON requests and responses
Key Features
- OAuth2 client credentials token provider implementation
- Static and custom token provider support
- Automatic token caching until expiration
- Automatic retry on 401 with token refresh
- Configurable retry attempts with exponential backoff
- Base URL support for API clients
- Request/response hooks for extensibility
Usage
provider := http.NewOAuth2ClientCredentialsProvider(
"https://auth.example.com/oauth/token",
"client-id",
"client-secret",
"read write",
)
client := http.NewClient(
http.WithTokenProvider(provider, 30*time.Second),
http.WithLogger(logger),
http.WithRetry(3, 100*time.Millisecond),
http.WithBaseURL("https://api.example.com"),
)
resp, err := client.Get(ctx, "/api/v1/users")