Documentation
¶
Overview ¶
Package httpcache provides an implementation of http.RoundTripper that adds transparent HTTP response caching according to RFC 9111 (HTTP Caching).
The primary entry point is NewTransport, which returns an http.RoundTripper that can be used with http.Client to cache HTTP responses in a user-provided Cache.
The package supports standard HTTP caching semantics, including validation, freshness calculation, cache revalidation, and support for directives such as stale-while-revalidate and stale-if-error.
Example usage:
client := &http.Client{
Transport: httpcache.NewTransport(myCache, httpcache.WithLogger(myLogger)),
}
Index ¶
Constants ¶
const CacheStatusHeader = internal.CacheStatusHeader
const DefaultSWRTimeout = 5 * time.Second // Default timeout for Stale-While-Revalidate
Variables ¶
var ErrNilCache = errors.New("httpcache: cache cannot be nil")
ErrNilCache is returned when a nil cache is provided to [NewRoundTripper]. Although not recommended, it is possible to handle this error gracefully by recovering from the panic that occurs when a nil cache is passed.
For example:
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok && errors.Is(err, ErrNilCache) {
// Handle the error gracefully, e.g., log it or return a default transport
log.Println("Cache cannot be nil:", err)
} else {
// Re-panic if it's not the expected error
panic(r)
}
}
}()
Functions ¶
func NewTransport ¶
func NewTransport(cache Cache, options ...Option) http.RoundTripper
NewTransport creates a new http.RoundTripper that caches HTTP responses. It requires a non-nil Cache implementation to store and retrieve cached responses. It also accepts functional options to configure the transport, SWR timeout, and logger. If the cache is nil, it panics with ErrNilCache.
Types ¶
type Cache ¶
type Cache interface {
Get(key string) ([]byte, error)
Set(key string, entry []byte) error
Delete(key string) error
}
Cache describes the interface implemented by types that can store, retrieve, and delete cache entries.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option is a functional option for configuring the RoundTripper.
func WithLogger ¶
WithLogger sets the logger for debug output; default: slog.New(slog.DiscardHandler).
func WithSWRTimeout ¶
WithSWRTimeout sets the timeout for Stale-While-Revalidate requests; default: DefaultSWRTimeout.
func WithTransport ¶
func WithTransport(transport http.RoundTripper) Option
WithTransport sets the underlying HTTP transport for making requests; default: http.DefaultTransport.
