httpcache

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2024 License: MIT Imports: 9 Imported by: 7

README

Tests on Linux, MacOS and Windows Go Report Card GoDoc

This is a fork of gregjones/httpcache.

License

Documentation

Overview

Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses.

It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy).

Index

Constants

View Source
const (

	// XFromCache is the header added to responses that are returned from the cache
	XFromCache = "X-From-Cache"
)

Variables

View Source
var ErrNoDateHeader = errors.New("no Date header")

ErrNoDateHeader indicates that the HTTP headers contained no Date header.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Get returns the []byte representation of a cached response and a bool
	// set to true if the value isn't empty
	Get(key string) (responseBytes []byte, ok bool)
	// Set stores the []byte representation of a response against a key
	Set(key string, responseBytes []byte)
	// Delete removes the value associated with the key
	Delete(key string)
}

A Cache interface is used by the Transport to store and retrieve responses.

type Transport

type Transport struct {
	// The RoundTripper interface actually used to make requests
	// If nil, http.DefaultTransport is used
	Transport http.RoundTripper

	// The Cache interface used to store and retrieve responses.
	Cache Cache

	// If true, responses returned from the cache will be given an extra header, X-From-Cache
	MarkCachedResponses bool

	// AroundRoundTrip is an optional func.
	// If set, the Transport will call AroundRoundTrip at the start of RoundTrip
	// and defer the returned func until the end of RoundTrip.
	// Typically used to implement a lock that is held for the duration of the RoundTrip.
	AroundRoundTrip func(key string) func()
}

Transport is an implementation of http.RoundTripper that will return values from a cache where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since) to repeated requests allowing servers to return 304 / Not Modified

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error)

RoundTrip takes a Request and returns a Response

If there is a fresh Response already in cache, then it will be returned without connecting to the server.

If there is a stale Response, then any validators it contains will be set on the new request to give the server a chance to respond with NotModified. If this happens, then the cached Response will be returned.

Jump to

Keyboard shortcuts

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