Documentation
¶
Overview ¶
Package roundtripware provides HTTP client middlewares, called RoundTripwares, that wrap an net/http.RoundTripper.
A RoundTripware wraps a Handler the same way a server middleware wraps an net/http.Handler. NewRoundTripper chains RoundTripwares around a parent transport:
client := &http.Client{
Transport: roundtripware.NewRoundTripper(l, http.DefaultTransport,
roundtripware.RequestID(),
roundtripware.Logger(),
),
}
RoundTripwares ¶
- Context propagation: RequestID, SessionID, TrackingID and Referer copy values from the request context into request headers.
- Resilience: CircuitBreaker, Retry and Recover.
- Observability: Logger and the deprecated Metric.
- Transport: GZip.
- Debugging: Dump, DumpRequest and DumpResponse.
Index ¶
- Variables
- func LabelerFromContext(ctx context.Context) (context.Context, *otelhttp.Labeler)
- type BearerTokenOption
- type BearerTokenOptions
- type CircuitBreakerOption
- type CircuitBreakerOptions
- type CircuitBreakerSettings
- type GZipOption
- type GZipOptions
- type Handler
- type LoggerOption
- type LoggerOptions
- type RecoverOption
- type RecoverOptions
- type RefererOption
- type RefererOptions
- type RequestIDOption
- type RequestIDOptions
- type RetryHandler
- type RetryOption
- func RetryWithAttempts(v uint) RetryOption
- func RetryWithContext(ctx context.Context) RetryOption
- func RetryWithDelay(delay time.Duration) RetryOption
- func RetryWithDelayType(delayType retry.DelayTypeFunc) RetryOption
- func RetryWithLastErrorOnly(lastErrorOnly bool) RetryOption
- func RetryWithMaxDelay(maxDelay time.Duration) RetryOption
- func RetryWithOnRetry(onRetry retry.OnRetryFunc) RetryOption
- func RetryWithRetryIf(retryIf retry.RetryIfFunc) RetryOption
- type RetryOptions
- type RoundTripper
- type RoundTripperFunc
- type RoundTripware
- func BearerToken(token string, opts ...BearerTokenOption) RoundTripware
- func CircuitBreaker(set *CircuitBreakerSettings, opts ...CircuitBreakerOption) RoundTripware
- func Dump() RoundTripware
- func DumpRequest() RoundTripware
- func DumpResponse() RoundTripware
- func GZip(opts ...GZipOption) RoundTripware
- func Logger(opts ...LoggerOption) RoundTripware
- func Metric(meter metric.Meter, name, description string) RoundTripwaredeprecated
- func Recover(opts ...RecoverOption) RoundTripware
- func RecoverWithOptions(opts RecoverOptions) RoundTripware
- func Referer(opts ...RefererOption) RoundTripware
- func RequestID(opts ...RequestIDOption) RoundTripware
- func Retry(opts ...RetryOption) RoundTripware
- func SessionID(opts ...SessionIDOption) RoundTripware
- func TrackingID(opts ...TrackingIDOption) RoundTripware
- type SessionIDGenerator
- type SessionIDOption
- type SessionIDOptions
- type TrackingIDGenerator
- type TrackingIDOption
- type TrackingIDOptions
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCircuitBreaker is returned when the circuit breaker did not let the request pass to the next // RoundTripware. It is joined with the underlying gobreaker error (ErrTooManyRequests or ErrOpenState) so a // single [errors.Is] comparison is needed. ErrCircuitBreaker = errors.New("circuit breaker triggered") // ErrIgnoreSuccessfulness can be returned by the IsSuccessful callback to have the request counted neither as // success nor as failure. ErrIgnoreSuccessfulness = errors.New("ignored successfulness") // ErrReadFromActualBody is returned when the IsSuccessful callback reads a request or response body that was not // copied (see [CircuitBreakerWithIsSuccessful]). ErrReadFromActualBody = errors.New("read from actual body") )
var DefaultGZipOptions = GZipOptions{ CompressionLevel: gzip.DefaultCompression, MinSize: 1024, }
DefaultGZipOptions holds the defaults used by GZip: the default compression level and a minimum size of 1024 bytes.
Functions ¶
func LabelerFromContext ¶ added in v0.9.12
LabelerFromContext returns the otelhttp.Labeler stored in ctx. If there is none, a new, empty Labeler is created and returned together with a derived context that holds it.
Types ¶
type BearerTokenOption ¶ added in v0.34.0
type BearerTokenOption func(*BearerTokenOptions)
BearerTokenOption configures BearerTokenOptions.
func BearerTokenWithHeader ¶ added in v0.34.0
func BearerTokenWithHeader(v string) BearerTokenOption
BearerTokenWithHeader sets the request header name.
func BearerTokenWithScheme ¶ added in v0.34.0
func BearerTokenWithScheme(v string) BearerTokenOption
BearerTokenWithScheme sets the token prefix, including any trailing space. An empty scheme writes the token without a prefix.
type BearerTokenOptions ¶ added in v0.34.0
BearerTokenOptions configures the BearerToken RoundTripware.
func GetDefaultBearerTokenOptions ¶ added in v0.34.0
func GetDefaultBearerTokenOptions() BearerTokenOptions
GetDefaultBearerTokenOptions uses Authorization with the Bearer scheme.
type CircuitBreakerOption ¶ added in v0.11.8
type CircuitBreakerOption func(opts *CircuitBreakerOptions)
CircuitBreakerOption configures CircuitBreakerOptions.
func CircuitBreakerWithIsSuccessful ¶ added in v0.11.8
func CircuitBreakerWithIsSuccessful( isSuccessful func(err error, req *http.Request, resp *http.Response) error, copyReqBody bool, copyRespBody bool, ) CircuitBreakerOption
CircuitBreakerWithIsSuccessful sets the callback that classifies a request as success (nil) or failure (non-nil); returning ErrIgnoreSuccessfulness ignores the request. copyReqBody and copyRespBody enable copying the bodies so the callback can read them; reading a body that was not copied makes the RoundTripware return ErrReadFromActualBody.
func CircuitBreakerWithMetric ¶ added in v0.11.8
func CircuitBreakerWithMetric( meter metric.Meter, meterName string, meterDescription string, ) CircuitBreakerOption
CircuitBreakerWithMetric adds an Int64Counter named meterName that counts successful and failed requests. It panics if the counter cannot be created.
type CircuitBreakerOptions ¶ added in v0.11.8
type CircuitBreakerOptions struct {
// Counter, when non-nil, counts requests with state and error attributes.
Counter metric.Int64Counter
// IsSuccessful decides whether a request counts as success (nil error) or
// failure. It receives copies of the request and response.
IsSuccessful func(err error, req *http.Request, resp *http.Response) error
// CopyReqBody reports whether the request body is copied for IsSuccessful.
CopyReqBody bool
// CopyRespBody reports whether the response body is copied for IsSuccessful.
CopyRespBody bool
}
CircuitBreakerOptions configures the CircuitBreaker RoundTripware.
func NewDefaultCircuitBreakerOptions ¶ added in v0.11.8
func NewDefaultCircuitBreakerOptions() *CircuitBreakerOptions
NewDefaultCircuitBreakerOptions returns the default options: no counter, no body copies and an IsSuccessful that treats every transport error as failure.
type CircuitBreakerSettings ¶ added in v0.11.8
type CircuitBreakerSettings struct {
// Name is the name of the CircuitBreaker.
Name string
// MaxRequests is the maximum number of requests allowed to pass through
// when the CircuitBreaker is half-open.
// If MaxRequests is 0, the CircuitBreaker allows only 1 request.
MaxRequests uint32
// Interval is the cyclic period of the closed state
// for the CircuitBreaker to clear the internal Counts.
// If Interval is less than or equal to 0, the CircuitBreaker doesn't clear internal Counts during the closed state.
Interval time.Duration
// Timeout is the period of the open state,
// after which the state of the CircuitBreaker becomes half-open.
// If Timeout is less than or equal to 0, the timeout value of the CircuitBreaker is set to 60 seconds.
Timeout time.Duration
// ReadyToTrip is called with a copy of Counts whenever a request fails in the closed state.
// If ReadyToTrip returns true, the CircuitBreaker will be placed into the open state.
// If ReadyToTrip is nil, default ReadyToTrip is used.
// Default ReadyToTrip returns true when the number of consecutive failures is more than 5.
ReadyToTrip func(counts gobreaker.Counts) bool
// OnStateChange is called whenever the state of the CircuitBreaker changes.
OnStateChange func(name string, from gobreaker.State, to gobreaker.State)
}
CircuitBreakerSettings is a copy of gobreaker.Settings without the IsSuccessful function, which is replaced by one with access to the request and response. See CircuitBreakerWithIsSuccessful.
type GZipOption ¶ added in v0.19.0
type GZipOption func(*GZipOptions)
GZipOption configures GZipOptions.
func GZipWithLevel ¶ added in v0.19.0
func GZipWithLevel(v int) GZipOption
GZipWithLevel allows setting a specific compression level for gzip (default: gzip.DefaultCompression).
func GZipWithMinSize ¶ added in v0.19.0
func GZipWithMinSize(v int) GZipOption
GZipWithMinSize allows setting a minimum request body length to apply gzip compression (default: 1024 bytes).
type GZipOptions ¶ added in v0.19.0
type GZipOptions struct {
// CompressionLevel is the gzip compression level.
CompressionLevel int
// MinSize is the minimum request Content-Length in bytes to compress.
MinSize int
}
GZipOptions configures the GZip RoundTripware.
type Handler ¶
Handler sends a request and returns its response, like http.RoundTripper.RoundTrip.
type LoggerOption ¶ added in v0.11.8
type LoggerOption func(*LoggerOptions)
LoggerOption configures LoggerOptions.
func LoggerWithErrorMessage ¶ added in v0.11.8
func LoggerWithErrorMessage(v string) LoggerOption
LoggerWithErrorMessage sets the log message for failed requests. Defaults to "failed to sent request".
func LoggerWithMessage ¶ added in v0.11.8
func LoggerWithMessage(v string) LoggerOption
LoggerWithMessage sets the log message. Defaults to "sent request".
func LoggerWithMinErrorCode ¶ added in v0.11.8
func LoggerWithMinErrorCode(v int) LoggerOption
LoggerWithMinErrorCode sets the status code from which requests are logged at error level. Defaults to 500.
func LoggerWithMinWarnCode ¶ added in v0.11.8
func LoggerWithMinWarnCode(v int) LoggerOption
LoggerWithMinWarnCode sets the status code from which requests are logged at warn level. Defaults to 400.
type LoggerOptions ¶ added in v0.11.8
type LoggerOptions struct {
// Message is the log message for completed requests.
Message string
// ErrorMessage is the log message for requests that failed with an
// error.
ErrorMessage string
// MinWarnCode is the status code from which requests are logged at
// warn level. Zero disables it.
MinWarnCode int
// MinErrorCode is the status code from which requests are logged at
// error level. Zero disables it.
MinErrorCode int
}
LoggerOptions configures the Logger RoundTripware.
func GetDefaultLoggerOptions ¶ added in v0.11.8
func GetDefaultLoggerOptions() LoggerOptions
GetDefaultLoggerOptions returns the default options: warn from 400 and error from 500.
type RecoverOption ¶
type RecoverOption func(options *RecoverOptions)
RecoverOption configures RecoverOptions.
func RecoverWithDisablePrintStack ¶
func RecoverWithDisablePrintStack(v bool) RecoverOption
RecoverWithDisablePrintStack sets RecoverOptions.DisablePrintStack.
type RecoverOptions ¶
type RecoverOptions struct {
// DisablePrintStack reports whether the stack trace is omitted from
// the log entry.
DisablePrintStack bool
}
RecoverOptions configures the Recover RoundTripware.
func GetDefaultRecoverOptions ¶
func GetDefaultRecoverOptions() RecoverOptions
GetDefaultRecoverOptions returns the default options, which include the stack trace.
type RefererOption ¶ added in v0.14.3
type RefererOption func(*RefererOptions)
RefererOption configures RefererOptions.
func RefererWithHeader ¶ added in v0.14.3
func RefererWithHeader(v string) RefererOption
RefererWithHeader sets the request header name. Defaults to X-Referer.
type RefererOptions ¶ added in v0.14.3
type RefererOptions struct {
// Header is the name of the request header to set.
Header string
}
RefererOptions configures the Referer RoundTripware.
func GetDefaultRefererOptions ¶ added in v0.14.3
func GetDefaultRefererOptions() RefererOptions
GetDefaultRefererOptions returns the default options using the X-Referer header.
type RequestIDOption ¶ added in v0.11.3
type RequestIDOption func(*RequestIDOptions)
RequestIDOption configures RequestIDOptions.
func RequestIDWithHeader ¶ added in v0.11.3
func RequestIDWithHeader(v string) RequestIDOption
RequestIDWithHeader sets the request header name. Defaults to X-Request-ID.
func RequestIDWithProvider ¶ added in v0.11.4
func RequestIDWithProvider(v provider.RequestID) RequestIDOption
RequestIDWithProvider sets the request ID provider. Defaults to provider.DefaultRequestID.
type RequestIDOptions ¶ added in v0.11.3
type RequestIDOptions struct {
// Header is the name of the request header to set.
Header string
// Provider generates a request ID when the context holds none.
Provider provider.RequestID
// SetHeader is not used.
SetHeader bool
}
RequestIDOptions configures the RequestID RoundTripware.
func GetDefaultRequestIDOptions ¶ added in v0.11.3
func GetDefaultRequestIDOptions() RequestIDOptions
GetDefaultRequestIDOptions returns the default options using the X-Request-ID header and provider.DefaultRequestID.
type RetryHandler ¶ added in v0.13.0
RetryHandler returns a non-nil error if the response should be retried.
type RetryOption ¶ added in v0.13.0
type RetryOption func(*RetryOptions)
RetryOption configures RetryOptions.
func RetryWithAttempts ¶ added in v0.13.0
func RetryWithAttempts(v uint) RetryOption
RetryWithAttempts applies retry.Attempts.
func RetryWithContext ¶ added in v0.13.0
func RetryWithContext(ctx context.Context) RetryOption
RetryWithContext applies retry.Context.
func RetryWithDelay ¶ added in v0.13.0
func RetryWithDelay(delay time.Duration) RetryOption
RetryWithDelay applies retry.Delay.
func RetryWithDelayType ¶ added in v0.13.0
func RetryWithDelayType(delayType retry.DelayTypeFunc) RetryOption
RetryWithDelayType applies retry.DelayType.
func RetryWithLastErrorOnly ¶ added in v0.13.0
func RetryWithLastErrorOnly(lastErrorOnly bool) RetryOption
RetryWithLastErrorOnly applies retry.LastErrorOnly.
func RetryWithMaxDelay ¶ added in v0.13.0
func RetryWithMaxDelay(maxDelay time.Duration) RetryOption
RetryWithMaxDelay applies retry.MaxDelay.
func RetryWithOnRetry ¶ added in v0.13.0
func RetryWithOnRetry(onRetry retry.OnRetryFunc) RetryOption
RetryWithOnRetry applies retry.OnRetry.
func RetryWithRetryIf ¶ added in v0.13.0
func RetryWithRetryIf(retryIf retry.RetryIfFunc) RetryOption
RetryWithRetryIf applies retry.RetryIf.
type RetryOptions ¶ added in v0.13.0
type RetryOptions struct {
// Handler classifies a response; a non-nil error triggers a retry.
Handler RetryHandler
// contains filtered or unexported fields
}
RetryOptions configures the Retry RoundTripware.
func GetDefaultRetryOptions ¶ added in v0.13.0
func GetDefaultRetryOptions() RetryOptions
GetDefaultRetryOptions returns the default options, which retry every response whose status is not 200 OK using the retry-go defaults.
type RoundTripper ¶
type RoundTripper struct {
http.RoundTripper
// contains filtered or unexported fields
}
RoundTripper is an http.RoundTripper that runs requests through a chain of RoundTripwares before passing them to the parent RoundTripper.
func NewRoundTripper ¶
func NewRoundTripper(l *zap.Logger, parent http.RoundTripper, roundTripwares ...RoundTripware) *RoundTripper
NewRoundTripper returns a RoundTripper that wraps parent with roundTripwares. They are applied in order, so the last one is the outermost and sees a request first.
type RoundTripperFunc ¶ added in v0.19.0
type RoundTripperFunc Handler
RoundTripperFunc adapts a Handler to http.RoundTripper.
type RoundTripware ¶
RoundTripware wraps next with additional client-side request handling.
func BearerToken ¶ added in v0.34.0
func BearerToken(token string, opts ...BearerTokenOption) RoundTripware
BearerToken authenticates outbound requests with a static token, unless the header is already set. An empty token leaves the request unchanged.
func CircuitBreaker ¶ added in v0.11.8
func CircuitBreaker(set *CircuitBreakerSettings, opts ...CircuitBreakerOption) RoundTripware
CircuitBreaker returns a RoundTripware which wraps all the following RoundTripwares and the Handler with a circuit breaker. It rejects requests with ErrCircuitBreaker once the breaker trips and logs state changes.
It is strongly advised to add this RoundTripware before the metric RoundTripware (if both are used), as the execution time measurements will otherwise be falsified.
func Dump ¶ added in v0.9.1
func Dump() RoundTripware
Dump returns a RoundTripware that prints the request and response bodies to stdout, pretty-printing JSON and msgpack. Bodies are only printed when a Content-Type header is set.
func DumpRequest ¶
func DumpRequest() RoundTripware
DumpRequest is like Dump but prints only the request body.
func DumpResponse ¶
func DumpResponse() RoundTripware
DumpResponse is like Dump but prints only the response body.
func GZip ¶ added in v0.19.0
func GZip(opts ...GZipOption) RoundTripware
GZip returns a RoundTripware that gzip-compresses request bodies whose Content-Length is at least MinSize and that are not already gzip encoded, and transparently decompresses gzip responses.
func Logger ¶
func Logger(opts ...LoggerOption) RoundTripware
Logger returns a RoundTripware that logs every outgoing request with its duration and, on success, status code and response size. The level depends on the error and status code.
func Metric
deprecated
added in
v0.9.12
func Metric(meter metric.Meter, name, description string) RoundTripware
Metric returns a RoundTripware that records the request duration in seconds in a Float64Histogram named name. Failed requests are not recorded. It panics if the histogram cannot be created.
Deprecated: Use keelhttp.WithTelemetry instead.
func Recover ¶
func Recover(opts ...RecoverOption) RoundTripware
Recover returns a RoundTripware that recovers and logs panics from the next handler. A recovered request returns a nil response and a nil error.
func RecoverWithOptions ¶
func RecoverWithOptions(opts RecoverOptions) RoundTripware
RecoverWithOptions is like Recover but takes fully populated options.
func Referer ¶ added in v0.14.3
func Referer(opts ...RefererOption) RoundTripware
Referer returns a RoundTripware that sets the referer stored in the request context as request header, unless the header is already present.
func RequestID ¶ added in v0.11.3
func RequestID(opts ...RequestIDOption) RoundTripware
RequestID returns a RoundTripware that sets a request ID header, unless already present, using the ID from the request context or a generated one.
func Retry ¶ added in v0.13.0
func Retry(opts ...RetryOption) RoundTripware
Retry returns a RoundTripware that retries requests failing with an error or rejected by the RetryHandler. It returns the last response and the retry-go error. Request bodies are not rewound between attempts.
func SessionID ¶ added in v0.11.3
func SessionID(opts ...SessionIDOption) RoundTripware
SessionID returns a RoundTripware that sets the session ID stored in the request context as request header, unless the header is already present.
func TrackingID ¶ added in v0.11.3
func TrackingID(opts ...TrackingIDOption) RoundTripware
TrackingID returns a RoundTripware that sets the tracking ID stored in the request context as request header, unless the header is already present.
type SessionIDGenerator ¶ added in v0.11.3
type SessionIDGenerator func() string
SessionIDGenerator returns a new session ID. It is not used by this package.
type SessionIDOption ¶ added in v0.11.3
type SessionIDOption func(*SessionIDOptions)
SessionIDOption configures SessionIDOptions.
func SessionIDWithHeader ¶ added in v0.11.3
func SessionIDWithHeader(v string) SessionIDOption
SessionIDWithHeader sets the request header name. Defaults to X-Session-ID.
type SessionIDOptions ¶ added in v0.11.3
type SessionIDOptions struct {
// Header is the name of the request header to set.
Header string
}
SessionIDOptions configures the SessionID RoundTripware.
func GetDefaultSessionIDOptions ¶ added in v0.11.3
func GetDefaultSessionIDOptions() SessionIDOptions
GetDefaultSessionIDOptions returns the default options using the X-Session-ID header.
type TrackingIDGenerator ¶ added in v0.11.3
type TrackingIDGenerator func() string
TrackingIDGenerator returns a new tracking ID. It is not used by this package.
type TrackingIDOption ¶ added in v0.11.3
type TrackingIDOption func(*TrackingIDOptions)
TrackingIDOption configures TrackingIDOptions.
func TrackingIDWithHeader ¶ added in v0.11.3
func TrackingIDWithHeader(v string) TrackingIDOption
TrackingIDWithHeader sets the request header name. Defaults to X-Tracking-ID.
type TrackingIDOptions ¶ added in v0.11.3
type TrackingIDOptions struct {
// Header is the name of the request header to set.
Header string
}
TrackingIDOptions configures the TrackingID RoundTripware.
func GetDefaultTrackingIDOptions ¶ added in v0.11.3
func GetDefaultTrackingIDOptions() TrackingIDOptions
GetDefaultTrackingIDOptions returns the default options using the X-Tracking-ID header.