internal

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Example (MakeKey)
u, err := url.Parse(
	"https://example.com:8443/abc?query=param&another=value#fragment=part1&part2",
)
if err != nil {
	fmt.Println("Error parsing URL:", err)
	return
}
cacheKey := makeKey(u)
fmt.Println("Cache Key:", cacheKey)
Output:

Cache Key: https://example.com:8443/abc?query=param&another=value

Index

Examples

Constants

View Source
const CacheStatusHeader = "X-Httpcache-Status"

Variables

This section is empty.

Functions

func NewCacheInvalidator

func NewCacheInvalidator(cache ResponseCache, cke CacheKeyer) *cacheInvalidator

func NewClock

func NewClock() *clock

func NewFreshnessCalculator

func NewFreshnessCalculator(clock Clock) *freshnessCalculator

func NewResponseCache

func NewResponseCache(cache Cache) *responseCache

func NewStaleIfErrorPolicy

func NewStaleIfErrorPolicy(clock Clock) *staleIfErrorPolicy

func NewValidationResponseHandler

func NewValidationResponseHandler(
	clock Clock,
	ci CacheInvalidator,
	ce CacheabilityEvaluator,
	siep StaleIfErrorPolicy,
	rs ResponseStorer,
) *validationResponseHandler

func ParseQuotedString

func ParseQuotedString(s string) string

ParseQuotedString parses an HTTP quoted-string (RFC 9110 §5.6.4). It returns the unescaped string, or the original string if parsing fails.

func ParseQuotedStringE

func ParseQuotedStringE(s string) (string, error)

ParseQuotedStringE parses an HTTP quoted-string (RFC 9110 §5.6.4). It returns the unescaped string, or an error if the input is not valid.

func SetAgeHeader

func SetAgeHeader(resp *http.Response, clock Clock, age *Age)

SetAgeHeader sets the Age header in the response based on the Age value. It assumes a non-nil Age pointer is provided.

func TrimmedCSVSeq

func TrimmedCSVSeq(s string) iter.Seq[string]

TrimmedCSVSeq returns an iterator over the raw comma-separated string. It yields each part of the string, trimmed of whitespace, and does not split inside quoted strings.

Types

type Age

type Age struct {
	Value     time.Duration // Age of the cached response (RFC9111 §4.2.3)
	Timestamp time.Time     // Time when the age was calculated
}

type CCRequestDirectives

type CCRequestDirectives map[string]string

CCRequestDirectives is a map of request directives from the Cache-Control header field. The keys are the directive names and the values are the arguments.

func ParseCCRequestDirectives

func ParseCCRequestDirectives(header http.Header) CCRequestDirectives

func (CCRequestDirectives) MaxAge

func (d CCRequestDirectives) MaxAge() (dur time.Duration, valid bool)

MaxAge parses the "max-age" request directive as defined in RFC 9111, §5.2.1.1. It indicates the client's maximum acceptable age for a cached response.

func (CCRequestDirectives) MaxStale

func (d CCRequestDirectives) MaxStale() (dur RawDeltaSeconds, valid bool)

MaxStale parses the "max-stale" request directive as defined in RFC 9111, §5.2.1.2. Indicates the client's maximum acceptable staleness of a cached response.

func (CCRequestDirectives) MinFresh

func (d CCRequestDirectives) MinFresh() (dur time.Duration, valid bool)

MinFresh parses the "min-fresh" request directive as defined in RFC 9111, §5.2.1.3. It indicates the minimum time a cached response must remain fresh before it can be served.

func (CCRequestDirectives) NoCache

func (d CCRequestDirectives) NoCache() bool

NoCache reports the presence of the "no-cache" request directive as defined in RFC 9111, §5.2.1.4. It indicates that the request must be validated with the origin server before being served from cache.

func (CCRequestDirectives) NoStore

func (d CCRequestDirectives) NoStore() bool

NoStore reports the presence of the "no-store" request directive as defined in RFC 9111, §5.2.1.5. It indicates that the request must not be stored by any cache.

func (CCRequestDirectives) NoTransform

func (d CCRequestDirectives) NoTransform() bool

It indicates that the client does not want any transformation of the response content,.

func (CCRequestDirectives) OnlyIfCached

func (d CCRequestDirectives) OnlyIfCached() bool

OnlyIfCached reports the presence of the "only-if-cached" request directive as defined in RFC 9111, §5.2.1.7. It indicates that the client only wants a response from the cache and does not want to contact the origin server. If the response is not in the cache, the server should return a 504 (Gateway Timeout) status code.

func (CCRequestDirectives) StaleIfError

func (d CCRequestDirectives) StaleIfError() (dur time.Duration, valid bool)

StaleIfError parses the "stale-if-error" request directive (extension) as defined in RFC 5861, §4. It indicates that the client is willing to accept a stale response if the origin server is unavailable or returns an error.

type CCResponseDirectives

type CCResponseDirectives map[string]string

CCResponseDirectives is a map of response directives from the Cache-Control header field. The keys are the directive names and the values are the arguments.

The following directives per RFC 9111, §5.2.2 are not applicable to private caches:

  • "proxy-revalidate" (§5.2.2.8)
  • "public" (§5.2.2.9)
  • "s-maxage" (§5.2.2.10)

Additionally, the following extension directives are supported:

func ParseCCResponseDirectives

func ParseCCResponseDirectives(header http.Header) CCResponseDirectives

func (CCResponseDirectives) MaxAge

func (d CCResponseDirectives) MaxAge() (dur time.Duration, valid bool)

MaxAge parses the "max-age" response directive as defined in RFC 9111, §5.2.2.1. It indicates the maximum time a response can be cached before it must be revalidated.

func (CCResponseDirectives) MaxAgePresent

func (d CCResponseDirectives) MaxAgePresent() bool

MaxAgePresent reports the presence of the "max-age" response directive as defined in RFC 9111, §5.2.2.1. It indicates that the response has a valid "max-age" directive, regardless of its value.

func (CCResponseDirectives) MustRevalidate

func (d CCResponseDirectives) MustRevalidate() bool

MustRevalidate reports the presence of the "must-revalidate" response directive as defined in RFC 9111, §5.2.2.2.

func (CCResponseDirectives) MustUnderstand

func (d CCResponseDirectives) MustUnderstand() bool

MustUnderstand reports the presence of the "must-understand" response directive as defined in RFC 9111, §5.2.2.3.

func (CCResponseDirectives) NoCache

func (d CCResponseDirectives) NoCache() (fields RawCSVSeq, present bool)

NoCache parses the "no-cache" response directive as defined in RFC 9111, §5.2.2.4. If the directive is present, it returns the raw comma-separated values.

func (CCResponseDirectives) NoStore

func (d CCResponseDirectives) NoStore() bool

NoStore reports the presence of the "no-store" response directive as defined in RFC 9111, §5.2.2.5.

func (CCResponseDirectives) NoTransform

func (d CCResponseDirectives) NoTransform() bool

NoTransform reports the presence of the "no-transform" response directive as defined in RFC 9111, §5.2.2.6.

func (CCResponseDirectives) Public

func (d CCResponseDirectives) Public() bool

Public reports the presence of the "public" response directive as defined in RFC 9111, §5.2.2.9.

func (CCResponseDirectives) StaleIfError

func (d CCResponseDirectives) StaleIfError() (dur time.Duration, valid bool)

StaleIfError parses the "stale-if-error" response directive (extension) as defined in RFC 5861, §4. It indicates that a cache can serve a stale response if the origin server is unavailable or returns an error.

func (CCResponseDirectives) StaleWhileRevalidate

func (d CCResponseDirectives) StaleWhileRevalidate() (dur time.Duration, valid bool)

StaleWhileRevalidate parses the "stale-while-revalidate" response directive (extension) as defined in RFC 5861, §3. It indicates that a cache can serve a stale response while it revalidates the response in the background.

type Cache

type Cache = store.Cache

type CacheInvalidator

type CacheInvalidator interface {
	InvalidateCache(reqURL *url.URL, respHeader http.Header, key string)
}

CacheInvalidator describes the interface implemented by types that can invalidate cache entries based on request and response headers, as specified in RFC 9111 §4.4.

type CacheKeyer

type CacheKeyer interface {
	CacheKey(u *url.URL) string
}

CacheKeyer describes the interface implemented by types that can generate a cache key for a given URL according to RFC 9111 §4.1.

func NewCacheKeyer

func NewCacheKeyer() CacheKeyer

type CacheKeyerFunc

type CacheKeyerFunc func(u *url.URL) string

func (CacheKeyerFunc) CacheKey

func (f CacheKeyerFunc) CacheKey(u *url.URL) string

type CacheStatus

type CacheStatus string
const (
	CacheStatusHit         CacheStatus = "HIT"         // Response was served from cache
	CacheStatusMiss        CacheStatus = "MISS"        // Response was not found in cache, and was served from origin
	CacheStatusStale       CacheStatus = "STALE"       // Response was served from cache but is stale
	CacheStatusRevalidated CacheStatus = "REVALIDATED" // Response was revalidated with the origin server
	CacheStatusBypass      CacheStatus = "BYPASS"      // Response was not served from cache due to cache bypass
)

func (CacheStatus) ApplyTo

func (s CacheStatus) ApplyTo(header http.Header)

ApplyTo sets the cache status header on the provided HTTP header.

func (CacheStatus) String

func (s CacheStatus) String() string

type CacheabilityEvaluator

type CacheabilityEvaluator interface {
	CanStoreResponse(
		resp *http.Response,
		reqCC CCRequestDirectives,
		resCC CCResponseDirectives,
	) bool
}

func NewCacheabilityEvaluator

func NewCacheabilityEvaluator() CacheabilityEvaluator

type CacheabilityEvaluatorFunc

type CacheabilityEvaluatorFunc func(
	resp *http.Response,
	reqCC CCRequestDirectives,
	resCC CCResponseDirectives,
) bool

func (CacheabilityEvaluatorFunc) CanStoreResponse

func (f CacheabilityEvaluatorFunc) CanStoreResponse(
	resp *http.Response,
	reqCC CCRequestDirectives,
	resCC CCResponseDirectives,
) bool

type Clock

type Clock interface {
	Now() time.Time
	Since(t time.Time) time.Duration
}

type Entry

type Entry struct {
	Response *http.Response // The HTTP response to cache
	ReqTime  time.Time      // Timestamp of the request
	RespTime time.Time      // Timestamp of the response
}

Entry represents a cached HTTP response entry.

func (*Entry) MarshalBinary

func (e *Entry) MarshalBinary() ([]byte, error)

func (*Entry) UnmarshalBinaryWithRequest

func (e *Entry) UnmarshalBinaryWithRequest(data []byte, req *http.Request) error

type Freshness

type Freshness struct {
	IsStale    bool          // Whether the response is stale
	Age        *Age          // Current age (seconds) of the response (RFC9111 §4.2.3)
	UsefulLife time.Duration // Freshness lifetime (seconds) of the response (RFC9111 §4.2.1)
}

Freshness represents the freshness status of a cached response.

type FreshnessCalculator

type FreshnessCalculator interface {
	// CalculateFreshness calculates the freshness of a cached response
	// based on the request and response cache control directives.
	CalculateFreshness(
		resp *Entry,
		reqCC CCRequestDirectives,
		resCC CCResponseDirectives,
	) *Freshness
}

FreshnessCalculator describes the interface implemented by types that can calculate the freshness of a cached response based on request and response cache control directives according to RFC 9111 §4.2.

type HeaderKey

type HeaderKey string

func (HeaderKey) Equal

func (h HeaderKey) Equal(h1, h2 http.Header) bool

func (HeaderKey) String

func (h HeaderKey) String() string

type MockCache

type MockCache struct {
	GetFunc    func(key string) ([]byte, error)
	SetFunc    func(key string, entry []byte) error
	DeleteFunc func(key string) error
}

func (*MockCache) Delete

func (m *MockCache) Delete(key string) error

func (*MockCache) Get

func (m *MockCache) Get(key string) ([]byte, error)

func (*MockCache) Set

func (m *MockCache) Set(key string, entry []byte) error

type MockCacheInvalidator

type MockCacheInvalidator struct {
	InvalidateCacheFunc func(reqURL *url.URL, respHeader http.Header, key string)
}

func (*MockCacheInvalidator) InvalidateCache

func (m *MockCacheInvalidator) InvalidateCache(
	reqURL *url.URL,
	respHeader http.Header,
	key string,
)

type MockCacheKeyer

type MockCacheKeyer struct {
	CacheKeyFunc func(u *url.URL) string
}

func (*MockCacheKeyer) CacheKey

func (m *MockCacheKeyer) CacheKey(u *url.URL) string

type MockClock

type MockClock struct {
	NowResult   time.Time
	SinceResult time.Duration
}

func (*MockClock) Now

func (m *MockClock) Now() time.Time

func (*MockClock) Since

func (m *MockClock) Since(t time.Time) time.Duration

type MockFreshnessCalculator

type MockFreshnessCalculator struct {
	CalculateFreshnessFunc func(resp *http.Response, reqCC CCRequestDirectives, resCC CCResponseDirectives) *Freshness
}

func (*MockFreshnessCalculator) CalculateFreshness

func (m *MockFreshnessCalculator) CalculateFreshness(
	resp *Entry,
	reqCC CCRequestDirectives,
	resCC CCResponseDirectives,
) *Freshness

type MockRequestMethodChecker

type MockRequestMethodChecker struct {
	IsRequestMethodUnderstoodFunc func(req *http.Request) bool
}

func (*MockRequestMethodChecker) IsRequestMethodUnderstood

func (m *MockRequestMethodChecker) IsRequestMethodUnderstood(req *http.Request) bool

type MockResponseCache

type MockResponseCache struct {
	GetFunc    func(key string, req *http.Request) (*Entry, error)
	SetFunc    func(key string, entry *Entry) error
	DeleteFunc func(key string) error
}

func (*MockResponseCache) Delete

func (m *MockResponseCache) Delete(key string) error

func (*MockResponseCache) Get

func (m *MockResponseCache) Get(key string, req *http.Request) (*Entry, error)

func (*MockResponseCache) Set

func (m *MockResponseCache) Set(key string, entry *Entry) error

type MockResponseStorer

type MockResponseStorer struct {
	StoreResponseFunc func(resp *http.Response, key string, reqTime, respTime time.Time) error
}

func (*MockResponseStorer) StoreResponse

func (m *MockResponseStorer) StoreResponse(
	resp *http.Response,
	key string,
	reqTime, respTime time.Time,
) error

StoreResponse implements ResponseStorer.

type MockRoundTripper

type MockRoundTripper struct {
	RoundTripFunc func(req *http.Request) (*http.Response, error)
}

func (*MockRoundTripper) RoundTrip

func (m *MockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

type MockStaleIfErrorPolicy

type MockStaleIfErrorPolicy struct {
	CanStaleOnErrorFunc func(freshness *Freshness, sies ...StaleIfErrorer) bool
}

func (*MockStaleIfErrorPolicy) CanStaleOnError

func (m *MockStaleIfErrorPolicy) CanStaleOnError(
	freshness *Freshness,
	sies ...StaleIfErrorer,
) bool

type MockValidationResponseHandler

type MockValidationResponseHandler struct {
	HandleValidationResponseFunc func(ctx RevalidationContext, req *http.Request, resp *http.Response, err error) (*http.Response, error)
}

func (*MockValidationResponseHandler) HandleValidationResponse

func (m *MockValidationResponseHandler) HandleValidationResponse(
	ctx RevalidationContext,
	req *http.Request,
	resp *http.Response,
	err error,
) (*http.Response, error)

type MockVaryMatcher

type MockVaryMatcher struct {
	VaryHeadersMatchFunc func(cachedHdr, reqHdr http.Header) bool
}

func (*MockVaryMatcher) VaryHeadersMatch

func (m *MockVaryMatcher) VaryHeadersMatch(cachedHdr, reqHdr http.Header) bool

type RawCSVSeq

type RawCSVSeq string

RawCSVSeq is a string that represents a sequence of comma-separated values.

func (RawCSVSeq) Value

func (s RawCSVSeq) Value() (seq iter.Seq[string], valid bool)

Value returns an iterator over the raw comma-separated string and a boolean indicating whether the result is valid.

type RawDeltaSeconds

type RawDeltaSeconds string

RawDeltaSeconds is a string that represents a delta time in seconds, as defined in §1.2.2 of RFC 9111.

This implementation supports values up to the maximum range of int64 (9223372036854775807 seconds). Values exceeding 2147483648 (2^31) are valid and will not be capped, as allowed by the RFC, which permits using the greatest positive integer the implementation can represent.

func (RawDeltaSeconds) Value

func (r RawDeltaSeconds) Value() (dur time.Duration, valid bool)

type RawTime

type RawTime string

RawTime is a string that represents a time in HTTP date format.

func (RawTime) Value

func (r RawTime) Value() (t time.Time, valid bool)

Value returns the time and a boolean indicating whether the result is valid.

type RequestMethodChecker

type RequestMethodChecker interface {
	IsRequestMethodUnderstood(req *http.Request) bool
}

RequestMethodChecker describes the interface implemented by types that can check whether the request method is understood by the cache according to RFC 9111 §3.

func NewRequestMethodChecker

func NewRequestMethodChecker() RequestMethodChecker

type RequestMethodCheckerFunc

type RequestMethodCheckerFunc func(req *http.Request) bool

func (RequestMethodCheckerFunc) IsRequestMethodUnderstood

func (f RequestMethodCheckerFunc) IsRequestMethodUnderstood(req *http.Request) bool

type ResponseCache

type ResponseCache interface {
	Get(key string, req *http.Request) (*Entry, error)
	Set(key string, entry *Entry) error
	Delete(key string) error
}

type ResponseStorer

type ResponseStorer interface {
	StoreResponse(resp *http.Response, key string, reqTime, respTime time.Time) error
}

ResponseStorer describes the interface implemented by types that can store HTTP responses in a cache, as specified in RFC 9111 §3.1.

func NewResponseStorer

func NewResponseStorer(cache ResponseCache) ResponseStorer

NewResponseStorer creates a new ResponseStorer with the given cache.

type RevalidationContext

type RevalidationContext struct {
	CacheKey   string
	Start, End time.Time
	CCReq      CCRequestDirectives
	Stored     *Entry
	Freshness  *Freshness
}

type StaleIfErrorPolicy

type StaleIfErrorPolicy interface {
	CanStaleOnError(freshness *Freshness, sies ...StaleIfErrorer) bool
}

StaleIfErrorPolicy describes the interface implemented by types that can evaluate cache control directives for storing responses (RFC 9111 §3) and determining whether a stale response can be served in case of an error (RFC 5861 §4).

type StaleIfErrorer

type StaleIfErrorer interface {
	// StaleIfError returns the duration for which the cache can serve a stale response
	// when an error occurs, according to the Stale-If-Error directive (RFC 5861 §4).
	StaleIfError() (dur time.Duration, valid bool)
}

type ValidationResponseHandler

type ValidationResponseHandler interface {
	HandleValidationResponse(
		ctx RevalidationContext,
		req *http.Request,
		resp *http.Response,
		err error,
	) (*http.Response, error)
}

type VaryMatcher

type VaryMatcher interface {
	VaryHeadersMatch(cachedHdr, reqHdr http.Header) bool
}

VaryMatcher describes the interface implemented by types that can check whether the Vary headers of a cached response match the request headers according to RFC 9111 §4.1.

func NewVaryMatcher

func NewVaryMatcher() VaryMatcher

type VaryMatcherFunc

type VaryMatcherFunc func(cachedHdr, reqHdr http.Header) bool

func (VaryMatcherFunc) VaryHeadersMatch

func (f VaryMatcherFunc) VaryHeadersMatch(cachedHdr, reqHdr http.Header) bool

Directories

Path Synopsis
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