Overview
Hooks allow you to execute custom logic at specific points in the request lifecycle:- Pre-request hooks run before each request is sent
- Post-response hooks run after each request completes (success or failure)
Type definitions
PreRequestHookFunc
PostResponseHookFunc
PostResponseContext
Error handling
ErrContinueHooks
ErrContinueHooks from a hook to log the error but continue executing subsequent hooks:
Adding hooks
At client creation
Add hooks when creating the client:After client creation
Add hooks dynamically using the client methods:Resetting hooks
Remove all hooks:Execution behavior
Pre-request hooks
- Execute in the order they were added
- Run before the HTTP request is sent
- If any hook returns an error (without
ErrContinueHooks), the request is aborted - Hooks can modify the request object
- Panics are caught and converted to errors
Post-response hooks
- Execute in the order they were added
- Always run, even if the request failed
- Receive both the response (if available) and any error
- If any hook returns an error (without
ErrContinueHooks), subsequent hooks are not executed - Panics are caught and logged
Usage examples
Request logging
Log all outgoing requests:Adding custom headers
Automatically add headers to all requests:Request timing
Measure request duration:Response validation
Validate response status codes:Retry logic
Implement custom retry logic with exponential backoff:Metrics collection
Collect detailed request metrics:Request rate limiting
Implement simple rate limiting:Continue on error
UseErrContinueHooks to log errors without aborting:
Best practices
- Keep hooks lightweight: Hooks execute synchronously and block the request
- Handle errors gracefully: Use
ErrContinueHooksfor non-critical errors - Avoid panics: Hooks catch panics, but they still abort the request
- Thread safety: Use proper synchronization for shared state (see rate limiter example)
- Clean up resources: Store request-specific data in maps and clean up in post-hooks
- Order matters: Hooks execute in the order they were added
Related methods
WithPreHook()- Add pre-request hook at client creationWithPostHook()- Add post-response hook at client creationHttpClient.AddPreRequestHook()- Add pre-request hook dynamicallyHttpClient.AddPostResponseHook()- Add post-response hook dynamicallyHttpClient.ResetPreHooks()- Remove all pre-request hooksHttpClient.ResetPostHooks()- Remove all post-response hooks