internal

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2025 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package internal provides the core unexported functionality for the httpcache package.

Example (MakeURLKey)
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 := makeURLKey(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"
	FromCacheHeader   = "X-From-Cache" // Deprecated: use [CacheStatusHeader] instead
)
View Source
const (
	FromCache    = "1"
	NotFromCache = ""
)

Variables

View Source
var (
	CacheStatusHit         = CacheStatus{"HIT", FromCache}         // served from cache
	CacheStatusMiss        = CacheStatus{"MISS", NotFromCache}     // served from origin
	CacheStatusStale       = CacheStatus{"STALE", FromCache}       // served from cache but stale
	CacheStatusRevalidated = CacheStatus{"REVALIDATED", FromCache} // revalidated with origin server
	CacheStatusBypass      = CacheStatus{"BYPASS", NotFromCache}   // cache bypassed
)
View Source
var TraceIDKey contextKey

Functions

func FixDateHeader added in v0.5.0

func FixDateHeader(h http.Header, receivedAt time.Time) bool

FixDateHeader sets the "Date" header to the current time in UTC if it is missing or empty, as per RFC 9110 §6.6.1, and reports whether it was changed.

NOTE: This cache forwards all requests to the client, so it MUST set the "Date" header to the current time for responses that do not have it set.

func IsNonErrorStatus added in v0.5.0

func IsNonErrorStatus(status int) bool

func IsUnsafeMethod added in v0.5.0

func IsUnsafeMethod(method string) bool

func NewCacheInvalidator

func NewCacheInvalidator(cache ResponseCache, cke URLKeyer) *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(
	dl *Logger,
	clock Clock,
	ci CacheInvalidator,
	ce CacheabilityEvaluator,
	siep StaleIfErrorPolicy,
	rs ResponseStorer,
) *validationResponseHandler

func NewVaryMatcher

func NewVaryMatcher(hvn HeaderValueNormalizer) *varyMatcher

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 TraceIDFromContext added in v0.10.0

func TraceIDFromContext(ctx context.Context) (string, bool)

func TrimmedCSVCanonicalSeq added in v0.7.0

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

TrimmedCSVCanonicalSeq is the same as TrimmedCSVSeq, but it yields each part in canonical form.

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
}

func (Age) LogValue added in v0.10.0

func (a Age) LogValue() slog.Value

type CCRequestDirectives

type CCRequestDirectives map[string]string

CCRequestDirectives is a map of request directives from the Cache-Control header field as defined in RFC 9111, §5.2.1. The keys are the directive tokens, and the values are the arguments (if any) as strings.

This implementation does not perform any transformations on the request, hence we ignore the "no-transform" directive.

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.

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.

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.

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.

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.

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.

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.

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 tokens, and the values are the arguments (if any) as strings.

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

  • "private" (§5.2.2.7)
  • "proxy-revalidate" (§5.2.2.8)
  • "s-maxage" (§5.2.2.10)

This implementation does not perform any transformations on the request, hence we ignore the "no-transform" directive.

func ParseCCResponseDirectives

func ParseCCResponseDirectives(header http.Header) CCResponseDirectives

func (CCResponseDirectives) Immutable added in v0.4.0

func (d CCResponseDirectives) Immutable() bool

Immutable reports the presence of the "immutable" response directive (extension) as defined in RFC 8246, §2.

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.

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.

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.

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) 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.

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.

type Cache

type Cache = driver.Conn

type CacheError added in v0.9.1

type CacheError struct {
	Op      string
	Message string
	Err     error
}

func (*CacheError) Error added in v0.9.1

func (c *CacheError) Error() string

func (CacheError) LogValue added in v0.9.1

func (c CacheError) LogValue() slog.Value

func (*CacheError) Unwrap added in v0.9.1

func (c *CacheError) Unwrap() error

type CacheInvalidator

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

CacheInvalidator describes the interface implemented by types that can invalidate cache entries for a target URI when an unsafe request receives a non-error response, as required by RFC 9111 §4.4. It may also invalidate entries for URIs in Location or Content-Location headers, but only if they share the same origin as the target URI.

type CacheStatus

type CacheStatus struct {
	Value string
	// Value for compatibility with github.com/gregjones/httpcache:
	// 	"1" means served from cache (less specific "HIT")
	// 	"" means not served from cache (less specific "MISS")
	//
	// Deprecated: only used for compatibility with unmaintained (still widely
	// used) github.com/gregjones/httpcache; use Value instead.
	Legacy string
}

func (CacheStatus) ApplyTo

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

func (CacheStatus) LogValue added in v0.10.0

func (s CacheStatus) LogValue() slog.Value

type CacheabilityEvaluator

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

CacheabilityEvaluator describes the interface implemented by types that can evaluate whether a response can be stored in cache, according to RFC 9111 §3.

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 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)
}

func (Freshness) LogValue added in v0.10.0

func (f Freshness) LogValue() slog.Value

type FreshnessCalculator

type FreshnessCalculator interface {
	// CalculateFreshness calculates the freshness of a cached response
	// based on the request and response cache control directives.
	CalculateFreshness(
		resp *Response,
		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 HeaderValueNormalizer added in v0.5.0

type HeaderValueNormalizer interface {
	NormalizeHeaderValue(field, value string) string
}

func NewHeaderValueNormalizer added in v0.5.0

func NewHeaderValueNormalizer() HeaderValueNormalizer

type HeaderValueNormalizerFunc added in v0.5.0

type HeaderValueNormalizerFunc func(field, value string) string

func (HeaderValueNormalizerFunc) NormalizeHeaderValue added in v0.5.0

func (f HeaderValueNormalizerFunc) NormalizeHeaderValue(field, value string) string

type LogEntry added in v0.10.0

type LogEntry struct {
	URLKey       string
	MiscProvider MiscProvider
	Error        error
}

type LogFunc added in v0.10.0

type LogFunc func() (CacheStatus, *http.Request, LogEntry)

func (LogFunc) MakeLog added in v0.10.0

func (f LogFunc) MakeLog() (event CacheStatus, req *http.Request, cl LogEntry)

type LogProvider added in v0.10.0

type LogProvider interface {
	MakeLog() (CacheStatus, *http.Request, LogEntry)
}

type LogValueFunc added in v0.10.0

type LogValueFunc func() slog.Value

func (LogValueFunc) LogValue added in v0.10.0

func (f LogValueFunc) LogValue() slog.Value

type Logger added in v0.10.0

type Logger struct {
	// contains filtered or unexported fields
}

func NewLogger added in v0.10.0

func NewLogger(h slog.Handler) *Logger

func (*Logger) Enabled added in v0.10.0

func (l *Logger) Enabled(ctx context.Context, level slog.Level) bool

func (*Logger) Handler added in v0.10.0

func (l *Logger) Handler() slog.Handler

func (*Logger) LogCacheBypass added in v0.10.0

func (l *Logger) LogCacheBypass(msg string, req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) LogCacheError added in v0.10.0

func (l *Logger) LogCacheError(
	msg string,
	err error,
	req *http.Request,
	urlKey string,
	mp MiscProvider,
)

func (*Logger) LogCacheHit added in v0.10.0

func (l *Logger) LogCacheHit(req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) LogCacheMiss added in v0.10.0

func (l *Logger) LogCacheMiss(req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) LogCacheRevalidated added in v0.10.0

func (l *Logger) LogCacheRevalidated(req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) LogCacheStale added in v0.10.0

func (l *Logger) LogCacheStale(req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) LogCacheStaleIfError added in v0.10.0

func (l *Logger) LogCacheStaleIfError(req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) LogCacheStaleRevalidate added in v0.10.0

func (l *Logger) LogCacheStaleRevalidate(req *http.Request, urlKey string, mp MiscProvider)

func (*Logger) With added in v0.10.0

func (l *Logger) With(attrs ...slog.Attr) *Logger

func (*Logger) WithGroup added in v0.10.0

func (l *Logger) WithGroup(name string) *Logger

type Misc added in v0.10.0

type Misc struct {
	CCReq     CCRequestDirectives
	CCResp    CCResponseDirectives
	Stored    *Response
	Freshness *Freshness
	Refs      ResponseRefs
	RefIndex  int
}

func (Misc) LogValue added in v0.10.0

func (m Misc) LogValue() slog.Value

type MiscFunc added in v0.10.0

type MiscFunc func() Misc

func (MiscFunc) MakeMisc added in v0.10.0

func (f MiscFunc) MakeMisc() Misc

type MiscProvider added in v0.10.0

type MiscProvider interface {
	MakeMisc() Misc
}

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, headers ResponseRefs, key string)
}

func (*MockCacheInvalidator) InvalidateCache

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

type MockCacheKeyer

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

func (*MockCacheKeyer) URLKey added in v0.5.0

func (m *MockCacheKeyer) URLKey(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 *Response,
	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) (*Response, error)
	SetFunc     func(key string, entry *Response) error
	DeleteFunc  func(key string) error
	GetRefsFunc func(key string) (ResponseRefs, error)
	SetRefsFunc func(key string, headers ResponseRefs) error
}

func (*MockResponseCache) Delete

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

func (*MockResponseCache) Get

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

func (*MockResponseCache) GetRefs added in v0.5.0

func (m *MockResponseCache) GetRefs(key string) (ResponseRefs, error)

func (*MockResponseCache) Set

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

func (*MockResponseCache) SetRefs added in v0.5.0

func (m *MockResponseCache) SetRefs(key string, headers ResponseRefs) error

type MockResponseStorer

type MockResponseStorer struct {
	StoreResponseFunc func(req *http.Request, resp *http.Response, key string, headers ResponseRefs, reqTime, respTime time.Time, refIndex int) error
}

func (*MockResponseStorer) StoreResponse

func (m *MockResponseStorer) StoreResponse(
	req *http.Request,
	resp *http.Response,
	key string,
	headers ResponseRefs,
	reqTime, respTime time.Time,
	refIndex int,
) error

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(cachedHdrs ResponseRefs, reqHdr http.Header) (int, bool)
}

func (*MockVaryMatcher) VaryHeadersMatch

func (m *MockVaryMatcher) VaryHeadersMatch(
	cachedHdrs ResponseRefs,
	reqHdr http.Header,
) (int, 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 Response added in v0.5.0

type Response struct {
	ID          string         // unique identifier for the response entry
	Data        *http.Response // the actual HTTP response data
	RequestedAt time.Time      // time when the request was made used for determining cache freshness
	ReceivedAt  time.Time      // time when the response was received, used for determining cache freshness
}

Response represents a cached HTTP response entry.

func ParseResponse added in v0.5.0

func ParseResponse(data []byte, req *http.Request) (resp *Response, err error)

ParseResponse parses a cached HTTP response entry from binary data and reconstructs a Response using the provided request for context. Returns an error if parsing fails.

func (*Response) DateHeader added in v0.5.0

func (r *Response) DateHeader() time.Time

DateHeader returns the parsed value of the "Date" header from the response.

NOTE: It assumes a valid "Date" header has been set by FixDateHeader.

func (*Response) ExpiresHeader added in v0.5.0

func (r *Response) ExpiresHeader() (t time.Time, found bool, valid bool)

func (Response) LogValue added in v0.10.0

func (r Response) LogValue() slog.Value

func (Response) MarshalBinary added in v0.5.0

func (r Response) MarshalBinary() ([]byte, error)

func (*Response) WriteTo added in v0.5.0

func (r *Response) WriteTo(w io.Writer) (int64, error)

type ResponseCache

type ResponseCache interface {
	Get(key string, req *http.Request) (*Response, error)
	Set(key string, entry *Response) error
	Delete(key string) error
	GetRefs(key string) (ResponseRefs, error)
	SetRefs(key string, refs ResponseRefs) error
}

ResponseCache is an interface for caching HTTP responses. It provides methods to delete any cached item by its key, retrieve and set full cached responses, and manage references associated with a given URL key.

type ResponseRef added in v0.5.0

type ResponseRef struct {
	ResponseID   string            `json:"id"`                   // unique identifier for the response entry.
	Vary         string            `json:"vary"`                 // value of the Vary response header.
	VaryResolved map[string]string `json:"vary_resolved"`        // resolved varying request headers, keys are canonicalized.
	ReceivedAt   time.Time         `json:"received_at,omitzero"` // when the response was generated.
}

ResponseRef represents a reference to a cached HTTP response.

func (ResponseRef) LogValue added in v0.10.0

func (r ResponseRef) LogValue() slog.Value

type ResponseRefs added in v0.5.0

type ResponseRefs []*ResponseRef

func (ResponseRefs) ResponseIDs added in v0.5.0

func (he ResponseRefs) ResponseIDs() iter.Seq[string]

type ResponseStorer

type ResponseStorer interface {
	StoreResponse(
		req *http.Request,
		resp *http.Response,
		urlKey string,
		refs ResponseRefs,
		reqTime, respTime time.Time,
		refIndex int,
	) error
}

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

If refs is nil, a new slice should be created. If refIndex is valid, the reference at that index should be updated; otherwise, a new reference should be appended.

func NewResponseStorer

func NewResponseStorer(cache ResponseCache, vhn VaryHeaderNormalizer, vk VaryKeyer) ResponseStorer

type RevalidationContext

type RevalidationContext struct {
	URLKey     string
	Start, End time.Time
	CCReq      CCRequestDirectives
	Stored     *Response
	Freshness  *Freshness
	Refs       ResponseRefs
	RefIndex   int
}

func (RevalidationContext) ToMisc added in v0.10.0

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 URLKeyer added in v0.5.0

type URLKeyer interface {
	URLKey(u *url.URL) string
}

URLKeyer describes the interface implemented by types that can generate a normalized cache key from a URL, following rules specified in RFC 3986 §6.

func NewURLKeyer added in v0.5.0

func NewURLKeyer() URLKeyer

type URLKeyerFunc added in v0.5.0

type URLKeyerFunc func(u *url.URL) string

func (URLKeyerFunc) URLKey added in v0.5.0

func (f URLKeyerFunc) URLKey(u *url.URL) string

type ValidationResponseHandler

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

type VaryHeaderNormalizer added in v0.5.0

type VaryHeaderNormalizer interface {
	NormalizeVaryHeader(vary string, reqHeader http.Header) iter.Seq2[string, string]
}

VaryHeaderNormalizer describes the interface implemented by types that can normalize request header field values given a Vary header field value, as per RFC 9111 §4.1.

func NewVaryHeaderNormalizer added in v0.5.0

func NewVaryHeaderNormalizer() VaryHeaderNormalizer

type VaryHeaderNormalizerFunc added in v0.5.0

type VaryHeaderNormalizerFunc func(vary string, reqHeader http.Header) iter.Seq2[string, string]

func (VaryHeaderNormalizerFunc) NormalizeVaryHeader added in v0.5.0

func (f VaryHeaderNormalizerFunc) NormalizeVaryHeader(
	vary string,
	reqHeader http.Header,
) iter.Seq2[string, string]

type VaryKeyer added in v0.5.0

type VaryKeyer interface {
	VaryKey(urlKey string, varyHeaders map[string]string) string
}

VaryKeyer describes the interface implemented by types that can generate a unique key for a cached response based on the URL and Vary headers, according to RFC 9111 §4.1.

func NewVaryKeyer added in v0.5.0

func NewVaryKeyer() VaryKeyer

type VaryKeyerFunc added in v0.5.0

type VaryKeyerFunc func(urlKey string, varyHeaders map[string]string) string

func (VaryKeyerFunc) VaryKey added in v0.5.0

func (f VaryKeyerFunc) VaryKey(urlKey string, varyHeaders map[string]string) string

type VaryMatcher

type VaryMatcher interface {
	VaryHeadersMatch(cachedHdrs ResponseRefs, reqHdr http.Header) (int, bool)
}

VaryMatcher defines the interface implemented by types that can match request headers nominated by the a cached response's Vary header against the headers of an incoming request.

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