httpcache

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 2, 2025 License: Apache-2.0 Imports: 10 Imported by: 1

README

httpcache

Go Reference Go Report Card Test codecov

httpcache is a Go package that provides a standards-compliant http.RoundTripper for transparent HTTP response caching, following RFC 9111 (HTTP Caching).

Note: This package is intended for use as a private (client-side) cache. It is not a shared or proxy cache.

Features

  • Plug-and-Play: Drop-in replacement for http.RoundTripper with no additional configuration required.
  • RFC 9111 Compliance: Handles validation, expiration, and revalidation.
  • Advanced directives: Supports stale-while-revalidate, stale-if-error, and more.
  • Custom cache backends: Bring your own cache implementation
  • Extensible: Options for logging, transport and timeouts.
  • Debuggable: Adds a cache status header to every response

Made with VHS

Refer to _examples/app for the source code.

Quick Start

package main

import (
    "fmt"
    "net/http"

    "github.com/bartventer/httpcache"
)

func main() {
    myCache := /* your implementation of httpcache.Cache */
    client := &http.Client{
        Transport: httpcache.NewTransport(myCache)

    resp, err := client.Get("https://example.com/resource")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    fmt.Println(resp.Header.Get(httpcache.CacheStatusHeader)) // e.g. "HIT", "MISS"
}

Cache Interface

The httpcache.Cache interface defines the methods required for a cache implementation:

type Cache interface {
    Get(key string) ([]byte, error)
    Set(key string, value []byte) error
    Delete(key string) error
}

Options

  • WithTransport(tr http.RoundTripper): Set the underlying transport (default: http.DefaultTransport).
  • WithSWRTimeout(timeout time.Duration): Set the stale-while-revalidate timeout (default: 5s).
  • WithLogger(logger *slog.Logger): Set a logger (default: discard).

Supported Cache-Control Directives

Directive Request Response Description
max-age Maximum age for cache freshness
min-fresh Minimum freshness required
max-stale Accept response stale by up to N seconds
no-cache Must revalidate with origin before using
no-store Do not store in any cache
only-if-cached Only serve from cache, never contact origin
must-revalidate Must revalidate once stale
must-understand Require cache to understand directive
public Response may be cached, even if normally non-cacheable
stale-while-revalidate Serve stale while revalidating in background (RFC 5861)
stale-if-error Serve stale if origin returns error (RFC 5861)

Note: The private, proxy-revalidate, and s-maxage directives bear no relevance in a private client-side cache and are ignored.

Cache Status Header

Every response includes a cache status header to indicate how the response was served:

Status Description
HIT Served from cache
MISS Fetched from origin
STALE Served stale from cache
REVALIDATED Revalidated with origin
BYPASS Cache bypassed

License

This project is licensed under the Apache License 2.0. See the LICENSE file for details.

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

View Source
const CacheStatusHeader = internal.CacheStatusHeader
View Source
const DefaultSWRTimeout = 5 * time.Second // Default timeout for Stale-While-Revalidate

Variables

View Source
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

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for debug output; default: slog.New(slog.DiscardHandler).

func WithSWRTimeout

func WithSWRTimeout(timeout time.Duration) Option

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.

Directories

Path Synopsis
_examples
app command
testutil
Package testutil provides utility functions for testing in Go.
Package testutil provides utility functions for testing in Go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL