Documentation
¶
Overview ¶
Package site implements public-site delivery on top of go-admin CMS records.
Locale-path model:
- Family identity is anchored by FamilyID first, then route_key.
- path is the localized public path for a specific translation record.
- locale prefix policy is applied at runtime, not baked into stored paths.
V1 compatibility:
- runtime still tolerates legacy locale-prefixed stored paths
- bridge diagnostics can surface when that compatibility branch is used
Historical URL redirects:
- WithContentURLRedirectStore wires an optional lookup-only dependency for public-site requests that normal content resolution did not match.
- Redirect persistence is host-owned. Stores implement ContentURLRedirectStore and should index normalized source path by site scope, locale, and content channel, plus any host-specific tenant key. WithContentURLRedirectSiteKey can provide an explicit stable site scope; otherwise lookup derives scope from request host, base path, and channel.
- Runtime lookup is a safe first rollout step: existing current-content canonical redirects remain authoritative, unknown paths still fall through to the normal 404 flow, and only eligible GET/HEAD HTML requests can use historical redirects.
- Hosts that want automatic capture around content moves can call ResolveContentDeliveryPath and CaptureContentURLRedirect from their write flows. Capture compares old and new public delivery paths and calls a host-provided ContentURLRedirectRecorder when a published, routable path changed.
- Capture stores runtime-public paths by default, including site base path and locale-prefix policy. Use ContentURLRedirectPathExplicit only for migration tools that intentionally need caller-controlled path shape.
- Route-template, base-path, channel, and locale-prefix changes should use CaptureContentURLRedirectBulk so every affected record is evaluated with before/after resolver inputs. Bulk capture supports distinct before/after content channels for channel moves. Use best-effort mode for migrations that should report per-record failures, or fail-fast mode when one bad record should stop the run.
- ContentURLRedirectChainUpdater and ContentURLRedirectSourceOwnerLookupService are optional capture-side hooks. Stores can use them to flatten chains such as /a -> /b -> /c and reject source paths that still belong to different active content by ID, type, locale, or channel scope. Set ContentURLRedirectChainRequired when capture must fail instead of recording a redirect without chain flattening.
- Backfills should write normalized source paths and validated same-site targets before enabling lookup. If rollout notes are needed for a release, write them in .release-notes.md.
Render cache:
- WithRenderCache wires anonymous public HTML response caching for capability-driven site delivery.
- WithRenderCacheRuntime carries the store, policy, and request observers as one runtime dependency. RenderCacheRequestObserver receives one bounded eligibility event and one terminal outcome per public delivery request; observer panics are isolated from visitor responses.
- WrapRenderCacheHandler applies the same lifecycle to deterministic host HTML handlers. Hosts own canonical path/query decisions and dependency tags; the wrapper owns bounded capture, safe replay, freshness, failures, request observation, and generation-fence rechecks.
- RenderCacheSharedFenceScope protects common public-site dependencies. Generic delivery reads it automatically; arbitrary handlers can combine it with bounded surface-specific RenderCacheHandlerDecision.FenceScopes. Mutations advance affected generations after commit and before reporting success, then invalidate tags to reclaim old-generation entries.
- Enabled memory runtimes require RenderCacheConfig.AllowProcessLocalFence. That flag is only for explicitly single-process development and tests; multi-instance environments must use a shared generation store such as the built-in Valkey runtime.
- Concurrent cold GET misses for one process and representation are coalesced. Followers re-evaluate the key and generations after the leader completes, so a concurrent mutation cannot publish a stale fill.
- Request-level observations are independent of backend Store operations. In particular, auth, preview, and cookie-mutation bypasses are observable even though they intentionally perform no cache lookup.
- Hosts provide the cache backend through RenderCacheStore. The interface is compatible with go-cache-style typed stores, but this package does not import go-cache.
- Standard go-router Fiber and HTTPRouter contexts use router-backed response capture by default. RenderCacheTemplateRenderer is optional for tests, custom render stacks, and contexts without the router template capture capability.
- RenderCachePolicy.MaxCaptureBodySize limits buffered template output and defaults to router.DefaultMaxCapturedBodySize. Oversized captures bypass storage and then use the normal router template renderer.
- Cache hits replay stored RenderedSiteResponse values through site-owned safe-header filtering, HEAD handling, debug headers, and freshness metadata; raw router.CapturedResponse values are not stored or replayed.
- RenderCachePolicy.ExpirationMode defaults to fixed. Sliding mode renews only fresh GET/HEAD hits, preserves CreatedAt, and resets logical and backend deadlines through RenderCacheSetIfPresentStore. Stale hits never renew. Custom sliding stores must implement that optional capability.
- StaleTTL enables stale-while-revalidate behavior: stores retain entries for FreshTTL plus StaleTTL, stale hits replay with cache status "stale", expired entries are deleted and refreshed as misses, and hosts can wire RenderCachePolicy.StaleRevalidator for safe background regeneration. Revalidation is keyed so duplicate stale hits do not stampede one process, and host callback panics are recovered.
- Sliding expiration adds one backend write per fresh hit and can keep hot entries fresh indefinitely. Production hosts must retain mutation-driven tag, prefix, render-version, or handler-generation invalidation.
- The default policy is conservative: GET/HEAD, status 200, no arbitrary query variation, auth/session/preview/JSON/search/API/cookie-mutating requests bypass, and only safe response headers are replayed.
- Built-in auth bypass checks include Authorization, admin authenticated request context, go-auth claims/actor context, common session/JWT cookies, and host-declared RenderCachePolicy.AuthCookieNames.
- RenderCachePolicy.RequireTagIndex is a production guard: memory backends bypass caching, stores must explicitly declare backend kind, stores must implement RenderCacheTagInvalidator, and tag attachment failure removes the just-written entry before it can be served.
Public HTML errors:
- SiteViewConfig.ErrorPolicy adds ordered concrete or theme-manifest-backed candidates while the legacy ErrorTemplate, ErrorTemplatesByStatus, and ErrorTemplatesByCode fields remain supported.
- RenderSiteErrorHTML is HTML-only. Host routes keep ownership of JSON negotiation and schemas, then call the shared renderer for browser HTML.
- Candidates render through isolated go-router response captures. Failed templates, including nested partial failures, cannot commit bytes before the next candidate is attempted.
- SiteErrorContextProvider adds request-scoped public error fields without rerunning normal SiteModule.ViewContext methods. The base site_error model contains only code, status, and ResolveSitePublicPath-derived home_href.
- SiteErrorRenderObserver receives sanitized provenance only; observer panics are isolated from visitor responses.
See /LOCALE_PATH_V1_GUIDE.md and /LOCALE_PATH_RUNBOOK.md for the full V1 rollout model, migration guidance, and V2 cleanup plan.
Index ¶
- Constants
- Variables
- func AdvanceRenderCacheGeneration(ctx context.Context, runtime *RenderCacheRuntime, scope string) (uint64, error)
- func BuildLocaleSwitcherContract(cfg ResolvedSiteConfig, currentPath string, requestedLocale string, ...) map[string]any
- func DefaultSiteSearchEndpointForAdminConfig(cfg admin.Config) string
- func HashRenderCacheCanonicalData(data []byte) string
- func LabelTemplateFS(fsys fs.FS, label string, kind TemplateSourceKind) fs.FS
- func LocaleCookieMutatedFromRequest(c router.Context) bool
- func LocalizedPath(path, locale, defaultLocale string, mode LocalePrefixMode) string
- func LocalizedPathWithQuery(path, locale, defaultLocale string, mode LocalePrefixMode, ...) string
- func MergeViewContext(in router.ViewContext, c router.Context) router.ViewContext
- func ReadRenderCacheGeneration(ctx context.Context, runtime *RenderCacheRuntime, scope string) (uint64, error)
- func ReadTemplateFromStack(name string, stack ...fs.FS) ([]byte, error)
- func ReadTemplateSourcesFromStack(name string, stack ...fs.FS) (*ResolvedTemplateSource, []ResolvedTemplateSource, error)
- func RegisterRenderCacheDebugPanel(runtime *RenderCacheRuntime) error
- func RegisterSiteRoutes[T any](r router.Router[T], adm *admin.Admin, cfg admin.Config, siteCfg SiteConfig, ...) error
- func RegisterSiteRoutingOwnership(adm *admin.Admin, cfg admin.Config, siteCfg SiteConfig, opts ...SiteOption) error
- func RenderCacheBackendKind(store RenderCacheStore) string
- func RenderCacheGenerationIsShared(runtime *RenderCacheRuntime) bool
- func RenderCacheHandlerTags(c router.Context) []string
- func RenderCacheStoreSupportsBackendDescriptor(store RenderCacheStore) bool
- func RenderCacheStoreSupportsClose(store RenderCacheStore) bool
- func RenderCacheStoreSupportsPrefixInvalidation(store RenderCacheStore) bool
- func RenderCacheStoreSupportsSetIfPresent(store RenderCacheStore) bool
- func RenderCacheStoreSupportsTagInvalidation(store RenderCacheStore) bool
- func RequestContext(c router.Context) context.Context
- func ResolveErrorTemplate(cfg ResolvedSiteViewConfig, code string, status int) string
- func ResolveErrorTemplateCandidates(cfg ResolvedSiteViewConfig, code string, status int) []string
- func ResolveSitePublicPath(cfg ResolvedSiteConfig, canonicalPath, locale string) string
- func ResolveSiteThemeTemplateDiagnostics(siteTheme map[string]any, stack ...fs.FS) map[string]SiteTemplatePrecedenceDiagnostic
- func SetLocalePathBridgeDiagnosticSink(record func(LocalePathBridgeDiagnostic)) func()
- func SetRenderCacheHandlerTags(c router.Context, tags ...string)
- func ShouldReloadTemplates(viewCfg ResolvedSiteViewConfig, environment string) bool
- func SiteReservedPrefixesForAdminConfig(cfg admin.Config) []string
- func SiteReservedPrefixesForAdminConfigWithStaticInput(cfg admin.Config, input staticprefixes.Input) []string
- func StripSupportedLocalePrefix(path string, supported []string) (string, string)
- func TemplateFSStack(viewCfg ResolvedSiteViewConfig, defaults ...fs.FS) []fs.FS
- func ValidateRenderCachePolicy(policy RenderCachePolicy) error
- func ValidateSiteConfig(_ admin.Config, input SiteConfig) error
- func ValidateSiteFallbackPolicy(policy SiteFallbackPolicy) error
- func ViewContextFromRequest(c router.Context) router.ViewContext
- func ViewEngineOptions(cfg admin.Config, siteCfg SiteConfig) []quickstart.ViewEngineOption
- func ViewEngineOptionsResolved(siteCfg ResolvedSiteConfig) []quickstart.ViewEngineOption
- func WithSiteThemeSelection(ctx context.Context, selector SiteThemeSelector) context.Context
- func WrapRenderCacheHandler(runtime *RenderCacheRuntime, handler router.HandlerFunc, ...) router.HandlerFunc
- type CanonicalRedirectMode
- type ContentDeliveryPathInput
- type ContentDeliveryPathResult
- type ContentURLRedirect
- type ContentURLRedirectBulkCaptureInput
- type ContentURLRedirectBulkCaptureResult
- type ContentURLRedirectBulkItem
- type ContentURLRedirectBulkItemResult
- type ContentURLRedirectBulkMode
- type ContentURLRedirectCaptureInput
- type ContentURLRedirectCaptureResult
- type ContentURLRedirectChainPolicy
- type ContentURLRedirectChainUpdater
- type ContentURLRedirectChange
- type ContentURLRedirectLookup
- type ContentURLRedirectPathShape
- type ContentURLRedirectRecorder
- type ContentURLRedirectSourceOwner
- type ContentURLRedirectSourceOwnerLookup
- type ContentURLRedirectSourceOwnerLookupService
- type ContentURLRedirectStore
- type DeliveryProvenance
- type DeliveryTemplateAttempt
- type LocalePathBridgeDiagnostic
- type LocalePrefixMode
- type RenderCacheBackendDescriber
- type RenderCacheBypassPredicate
- type RenderCacheConfig
- type RenderCacheDebugCachedResponse
- type RenderCacheDebugCapabilities
- type RenderCacheDebugCommand
- type RenderCacheDebugConfig
- type RenderCacheDebugCounters
- type RenderCacheDebugError
- type RenderCacheDebugKey
- type RenderCacheDebugObservedStore
- type RenderCacheDebugObserver
- func (s *RenderCacheDebugObserver) ClearAll(ctx context.Context) RenderCacheDebugCommand
- func (s *RenderCacheDebugObserver) Delete(ctx context.Context, key string) error
- func (s *RenderCacheDebugObserver) Get(ctx context.Context, key string) (RenderedSiteResponse, bool, error)
- func (s *RenderCacheDebugObserver) ObserveRenderCacheRequest(_ context.Context, observation RenderCacheRequestObservation)
- func (s *RenderCacheDebugObserver) RenderCacheDebugObserver() *RenderCacheDebugObserver
- func (s *RenderCacheDebugObserver) Set(ctx context.Context, key string, value RenderedSiteResponse, ttl time.Duration) error
- func (s *RenderCacheDebugObserver) Snapshot(runtime *RenderCacheRuntime) RenderCacheDebugSnapshot
- type RenderCacheDebugOperation
- type RenderCacheDebugRequestCounters
- type RenderCacheDebugSnapshot
- type RenderCacheDebugSurfaceCounters
- type RenderCacheExpirationMode
- type RenderCacheGenerationStore
- type RenderCacheHandlerDecision
- type RenderCacheHandlerOptions
- type RenderCachePolicy
- type RenderCachePrefixInvalidator
- type RenderCacheRequestObservation
- type RenderCacheRequestObserver
- type RenderCacheRequestOutcome
- type RenderCacheRequestPhase
- type RenderCacheRevalidationRequest
- type RenderCacheRuntime
- type RenderCacheSetIfPresentStore
- type RenderCacheStaleRevalidator
- type RenderCacheStartupDiagnostic
- type RenderCacheStartupError
- type RenderCacheStore
- type RenderCacheTagInvalidator
- type RenderCacheTemplateRenderer
- type RenderCacheValkeyConfig
- type RenderCacheValkeyDebugCfg
- type RenderedSiteResponse
- type RenderedTemplate
- type RequestState
- type ResolvedSiteConfig
- type ResolvedSiteFeatures
- type ResolvedSiteInternalOpsConfig
- type ResolvedSiteThemeConfig
- type ResolvedSiteViewConfig
- type ResolvedTemplateSource
- type SiteConfig
- type SiteErrorContextProvider
- type SiteErrorContextRequest
- type SiteErrorRenderEvent
- type SiteErrorRenderObserver
- type SiteErrorRenderRequest
- type SiteErrorRenderResult
- type SiteErrorTemplateCandidate
- type SiteErrorTemplatePolicy
- type SiteFallbackMode
- type SiteFallbackPolicy
- type SiteFeatures
- type SiteInternalOpsConfig
- type SiteModule
- type SiteModuleContext
- type SiteNavigationConfig
- type SiteOption
- func WithAllowedExactPaths(paths ...string) SiteOption
- func WithAllowedFallbackMethods(methods ...router.HTTPMethod) SiteOption
- func WithAllowedPathPrefixes(prefixes ...string) SiteOption
- func WithContentHandler(handler router.HandlerFunc) SiteOption
- func WithContentURLRedirectSiteKey(siteKey string) SiteOption
- func WithContentURLRedirectStore(store ContentURLRedirectStore) SiteOption
- func WithDeliveryServices(contentSvc admin.CMSContentService, contentTypeSvc admin.CMSContentTypeService) SiteOption
- func WithFallbackPolicy(policy SiteFallbackPolicy) SiteOption
- func WithRenderCache(store RenderCacheStore, policy RenderCachePolicy) SiteOption
- func WithRenderCacheRequestObservers(observers ...RenderCacheRequestObserver) SiteOption
- func WithRenderCacheRuntime(runtime *RenderCacheRuntime) SiteOption
- func WithReservedPrefixes(prefixes ...string) SiteOption
- func WithSearchHandlers(pageHandler, apiHandler router.HandlerFunc) SiteOption
- func WithSearchOperations(ops *admin.GoSearchOperations) SiteOption
- func WithSearchProvider(provider admin.SearchProvider) SiteOption
- func WithSiteTheme(selector gotheme.ThemeSelector) SiteOption
- func WithSiteThemeProvider(provider SiteThemeProvider) SiteOption
- func WithSuggestHandler(handler router.HandlerFunc) SiteOption
- type SiteRouter
- type SiteRoutingOwnershipContext
- type SiteRoutingOwnershipProvider
- type SiteRuntimeError
- type SiteSearchConfig
- type SiteSearchFacetExpansionPolicy
- type SiteSearchFilterInjector
- type SiteSearchFilterOnlyPolicy
- type SiteSearchFilterRequest
- type SiteSearchPageSizePolicy
- type SiteSearchVariantPolicy
- type SiteTemplatePrecedenceDiagnostic
- type SiteTemplateRef
- type SiteThemeConfig
- type SiteThemeProvider
- type SiteThemeRequest
- type SiteThemeSelector
- type SiteViewConfig
- type SiteViewRuntime
- type TemplateSourceKind
- type TemplateSourceMeta
Examples ¶
Constants ¶
const ( DefaultMainMenuLocation = "site.main" DefaultFallbackMenuCode = "site_main" DefaultBaseTemplate = "site/base" DefaultErrorTemplate = "site/error" DefaultSearchRoute = "/search" DefaultSearchEndpoint = "/api/v1/site/search" DefaultSearchSuggestRoute = "/api/v1/site/search/suggest" )
const ( ContributionLocalePolicyFallback = "fallback" ContributionLocalePolicyStrict = "strict" )
const ( DeliveryProvenanceRequestHeader = "X-Site-Delivery-Provenance" DeliveryTextCodeRendered = "PUBLIC_SITE_DELIVERY_RENDERED" DeliveryTextCodeRenderFailed = "PUBLIC_TEMPLATE_RENDER_FAILED" DeliveryCacheStatusBypass = "bypass" DeliveryCacheStatusMiss = "miss" DeliveryCacheStatusHit = "hit" DeliveryCacheStatusStale = "stale" DeliveryProvenanceRouteFamilyHeader = "X-Site-Delivery-Route-Family" DeliveryProvenanceOwnerKindHeader = "X-Site-Delivery-Owner-Kind" DeliveryProvenanceModeHeader = "X-Site-Delivery-Mode" DeliveryProvenanceRequestedTemplateHeader = "X-Site-Delivery-Requested-Template" DeliveryProvenanceSelectedTemplateHeader = "X-Site-Delivery-Selected-Template" DeliveryProvenanceTemplateAttemptsHeader = "X-Site-Delivery-Template-Attempts" DeliveryProvenanceFallbackHeader = "X-Site-Delivery-Fallback-Used" DeliveryProvenanceCacheStatusHeader = "X-Site-Delivery-Cache-Status" DeliveryProvenanceRenderVersionHeader = "X-Site-Delivery-Render-Version" DeliveryProvenanceSemanticIdentityHeader = "X-Site-Delivery-Semantic-Identity" DeliveryProvenanceTextCodeHeader = "X-Site-Delivery-Text-Code" )
const ( DefaultReservedPrefixAdmin = "/admin" DefaultReservedPrefixAPI = "/api" DefaultReservedPrefixWellKnown = "/.well-known" DefaultReservedPrefixStatic = "/static" DefaultReservedPrefixAssets = "/assets" )
const ( RenderCacheBackendMemory = "memory" RenderCacheBackendValkey = "valkey" RenderCacheDebugPanelID = "site-render-cache" RenderCacheDebugPanelSnapshot = "site-render-cache" RenderCacheAllSiteTag = "site:render" RenderCacheKeyPrefix = "site-render:" )
const (
RenderCacheObservationSurfaceGeneric = "generic"
)
RenderCacheSharedFenceScope is the generation shared by every public HTML surface that renders common site chrome such as navigation, theme, widgets, or locale catalogs.
Variables ¶
var ErrContentURLRedirectChainUpdaterRequired = errors.New("content URL redirect chain updater required")
ErrContentURLRedirectChainUpdaterRequired reports capture inputs that require chain flattening without providing a chain updater capability.
ErrRenderCacheGenerationUnavailable identifies a missing or unusable generation fence. Callers may use errors.Is to distinguish this from a backend operation failure.
var ErrRenderCacheInvalidExpirationMode = errors.New("site render cache expiration mode is invalid")
ErrRenderCacheInvalidExpirationMode identifies unsupported fixed/sliding policy values rejected during runtime construction or route registration.
var ErrRenderCacheProcessLocalFenceRequired = errors.New("site render cache memory backend requires explicit process-local fence authorization")
ErrRenderCacheProcessLocalFenceRequired identifies an enabled memory-backed public HTML cache that was not explicitly authorized for single-process development or test use.
Functions ¶
func AdvanceRenderCacheGeneration ¶ added in v0.127.4
func AdvanceRenderCacheGeneration(ctx context.Context, runtime *RenderCacheRuntime, scope string) (uint64, error)
AdvanceRenderCacheGeneration advances a runtime generation atomically.
func BuildLocaleSwitcherContract ¶
func BuildLocaleSwitcherContract( cfg ResolvedSiteConfig, currentPath string, requestedLocale string, resolvedLocale string, translationGroupID string, availableLocales []string, pathsByLocale map[string]string, query map[string]string, ) map[string]any
BuildLocaleSwitcherContract returns a stable template contract for language switcher rendering, preserving translation-group identity metadata.
func DefaultSiteSearchEndpointForAdminConfig ¶ added in v0.36.0
DefaultSiteSearchEndpointForAdminConfig derives the public site search API endpoint from the configured public API root.
func HashRenderCacheCanonicalData ¶ added in v0.127.4
HashRenderCacheCanonicalData returns a deterministic fixed-width token for host-owned canonical key material. Raw paths, queries, tokens, and filters do not need to be exposed in backend keys.
func LabelTemplateFS ¶ added in v0.36.0
func LocaleCookieMutatedFromRequest ¶ added in v0.66.0
func LocalizedPath ¶
func LocalizedPath(path, locale, defaultLocale string, mode LocalePrefixMode) string
LocalizedPath rewrites a canonical path using the configured locale prefix policy.
func LocalizedPathWithQuery ¶
func LocalizedPathWithQuery(path, locale, defaultLocale string, mode LocalePrefixMode, query map[string]string) string
LocalizedPathWithQuery rewrites a path and preserves query params.
func MergeViewContext ¶
func MergeViewContext(in router.ViewContext, c router.Context) router.ViewContext
MergeViewContext fills missing keys from request-level site context without overwriting explicitly resolved render values.
func ReadRenderCacheGeneration ¶ added in v0.127.4
func ReadRenderCacheGeneration(ctx context.Context, runtime *RenderCacheRuntime, scope string) (uint64, error)
ReadRenderCacheGeneration reads a runtime generation while preserving a stable errors.Is contract when the capability is unavailable.
func ReadTemplateFromStack ¶
ReadTemplateFromStack reads a template file from a multi-FS stack.
func ReadTemplateSourcesFromStack ¶ added in v0.36.0
func ReadTemplateSourcesFromStack(name string, stack ...fs.FS) (*ResolvedTemplateSource, []ResolvedTemplateSource, error)
func RegisterRenderCacheDebugPanel ¶ added in v0.69.0
func RegisterRenderCacheDebugPanel(runtime *RenderCacheRuntime) error
func RegisterSiteRoutes ¶
func RegisterSiteRoutes[T any]( r router.Router[T], adm *admin.Admin, cfg admin.Config, siteCfg SiteConfig, opts ...SiteOption, ) error
RegisterSiteRoutes registers quickstart site routes with deterministic ordering.
func RegisterSiteRoutingOwnership ¶ added in v0.36.0
func RegisterSiteRoutingOwnership( adm *admin.Admin, cfg admin.Config, siteCfg SiteConfig, opts ...SiteOption, ) error
RegisterSiteRoutingOwnership records public-site exact routes and fallback ownership in the shared routing planner without mutating the runtime router.
func RenderCacheBackendKind ¶ added in v0.69.0
func RenderCacheBackendKind(store RenderCacheStore) string
func RenderCacheGenerationIsShared ¶ added in v0.127.4
func RenderCacheGenerationIsShared(runtime *RenderCacheRuntime) bool
RenderCacheGenerationIsShared reports whether a runtime fence is visible to every process using the configured backend.
func RenderCacheHandlerTags ¶ added in v0.127.4
RenderCacheHandlerTags returns a copy of tags published by a wrapped handler.
func RenderCacheStoreSupportsBackendDescriptor ¶ added in v0.69.0
func RenderCacheStoreSupportsBackendDescriptor(store RenderCacheStore) bool
func RenderCacheStoreSupportsClose ¶ added in v0.69.0
func RenderCacheStoreSupportsClose(store RenderCacheStore) bool
func RenderCacheStoreSupportsPrefixInvalidation ¶ added in v0.69.0
func RenderCacheStoreSupportsPrefixInvalidation(store RenderCacheStore) bool
func RenderCacheStoreSupportsSetIfPresent ¶ added in v0.128.0
func RenderCacheStoreSupportsSetIfPresent(store RenderCacheStore) bool
func RenderCacheStoreSupportsTagInvalidation ¶ added in v0.69.0
func RenderCacheStoreSupportsTagInvalidation(store RenderCacheStore) bool
func RequestContext ¶ added in v0.32.0
RequestContext returns the request context when available and falls back to a background context for detached helpers and tests.
func ResolveErrorTemplate ¶
func ResolveErrorTemplate(cfg ResolvedSiteViewConfig, code string, status int) string
ResolveErrorTemplate resolves template selection in the required order: code-specific, status-specific, and finally generic fallback.
func ResolveErrorTemplateCandidates ¶
func ResolveErrorTemplateCandidates(cfg ResolvedSiteViewConfig, code string, status int) []string
ResolveErrorTemplateCandidates returns a de-duplicated chain of templates in priority order for rendering error pages.
func ResolveSitePublicPath ¶ added in v0.114.0
func ResolveSitePublicPath(cfg ResolvedSiteConfig, canonicalPath, locale string) string
ResolveSitePublicPath converts a canonical site path into the locale- and base-path-aware public URL path used by delivery routes.
func ResolveSiteThemeTemplateDiagnostics ¶ added in v0.36.0
func SetLocalePathBridgeDiagnosticSink ¶ added in v0.36.0
func SetLocalePathBridgeDiagnosticSink(record func(LocalePathBridgeDiagnostic)) func()
func SetRenderCacheHandlerTags ¶ added in v0.127.4
SetRenderCacheHandlerTags publishes bounded response dependencies from a wrapped miss handler. Repeated calls merge and deduplicate tags.
func ShouldReloadTemplates ¶
func ShouldReloadTemplates(viewCfg ResolvedSiteViewConfig, environment string) bool
ShouldReloadTemplates reports template reload behavior for the current environment.
func SiteReservedPrefixesForAdminConfig ¶ added in v0.36.0
SiteReservedPrefixesForAdminConfig returns the structural reserved prefixes that should be protected from site fallback for the provided admin config.
func SiteReservedPrefixesForAdminConfigWithStaticInput ¶ added in v0.48.0
func SiteReservedPrefixesForAdminConfigWithStaticInput(cfg admin.Config, input staticprefixes.Input) []string
SiteReservedPrefixesForAdminConfigWithStaticInput returns the structural reserved prefixes using the provided static mount input. Hosts that customize static asset route prefixes should derive both the static mounts and site fallback reservations from the same input.
func StripSupportedLocalePrefix ¶
StripSupportedLocalePrefix removes a locale segment prefix from path when it matches one of the configured locales.
func TemplateFSStack ¶
func TemplateFSStack(viewCfg ResolvedSiteViewConfig, defaults ...fs.FS) []fs.FS
TemplateFSStack returns a deterministic template overlay stack. Entries from viewCfg.TemplateFS have higher precedence than the host defaults.
func ValidateRenderCachePolicy ¶ added in v0.128.1
func ValidateRenderCachePolicy(policy RenderCachePolicy) error
ValidateRenderCachePolicy validates public policy values that must be rejected during startup rather than converted into request-time bypasses.
func ValidateSiteConfig ¶ added in v0.117.0
func ValidateSiteConfig(_ admin.Config, input SiteConfig) error
ValidateSiteConfig validates explicit optional policies before route registration. ResolveSiteConfig intentionally remains normalization-only for source compatibility.
func ValidateSiteFallbackPolicy ¶ added in v0.36.0
func ValidateSiteFallbackPolicy(policy SiteFallbackPolicy) error
func ViewContextFromRequest ¶
func ViewContextFromRequest(c router.Context) router.ViewContext
ViewContextFromRequest returns site view context prepared by site middleware.
func ViewEngineOptions ¶ added in v0.36.0
func ViewEngineOptions(cfg admin.Config, siteCfg SiteConfig) []quickstart.ViewEngineOption
ViewEngineOptions converts site runtime view settings into quickstart view-engine options. The base host filesystem must still be provided directly to quickstart.NewViewEngine.
func ViewEngineOptionsResolved ¶ added in v0.36.0
func ViewEngineOptionsResolved(siteCfg ResolvedSiteConfig) []quickstart.ViewEngineOption
ViewEngineOptionsResolved converts a resolved site config into quickstart view-engine options.
func WithSiteThemeSelection ¶ added in v0.36.0
func WithSiteThemeSelection(ctx context.Context, selector SiteThemeSelector) context.Context
WithSiteThemeSelection stores a site-scoped selector on the request context.
func WrapRenderCacheHandler ¶ added in v0.127.4
func WrapRenderCacheHandler(runtime *RenderCacheRuntime, handler router.HandlerFunc, options RenderCacheHandlerOptions) router.HandlerFunc
WrapRenderCacheHandler applies the shared public HTML render-cache lifecycle to an arbitrary router handler. Hits skip handler execution. GET and HEAD use one representation key; HEAD misses execute once and never populate storage.
Types ¶
type CanonicalRedirectMode ¶
type CanonicalRedirectMode string
CanonicalRedirectMode controls which locale is used when computing canonical redirects.
const ( // CanonicalRedirectResolvedLocale keeps existing behavior: // canonical URL locale follows the resolved record locale. CanonicalRedirectResolvedLocale CanonicalRedirectMode = "resolved_locale_canonical" // CanonicalRedirectRequestedLocaleSticky preserves the requested locale prefix // when fallback content is served. CanonicalRedirectRequestedLocaleSticky CanonicalRedirectMode = "requested_locale_sticky" )
type ContentDeliveryPathInput ¶ added in v0.111.0
type ContentDeliveryPathInput struct {
SiteConfig ResolvedSiteConfig
Content admin.CMSContent
ContentType admin.CMSContentType
Locale string
ContentChannel string
IncludeBase bool
IncludeLocale bool
}
ContentDeliveryPathInput describes the content record and site scope used to compute the same delivery path shape used by the public-site runtime.
type ContentDeliveryPathResult ¶ added in v0.111.0
type ContentDeliveryPathResult struct {
CanonicalPath string `json:"canonical_path"`
PublicPath string `json:"public_path"`
Locale string `json:"locale"`
ContentChannel string `json:"content_channel"`
PublicRoutable bool `json:"public_routable"`
}
ContentDeliveryPathResult is the canonical delivery path plus optional public path shape for host-owned redirect capture and migration tools.
func ResolveContentDeliveryPath ¶ added in v0.111.0
func ResolveContentDeliveryPath(_ context.Context, input ContentDeliveryPathInput) (ContentDeliveryPathResult, error)
ResolveContentDeliveryPath computes the effective delivery path for a content record using the same content type delivery capability rules as runtime delivery resolution.
type ContentURLRedirect ¶ added in v0.111.0
type ContentURLRedirect struct {
SourcePath string `json:"source_path"`
TargetPath string `json:"target_path"`
StatusCode int `json:"status_code"`
Active bool `json:"active"`
SiteKey string `json:"site_key"`
ContentID string `json:"content_id"`
ContentTypeSlug string `json:"content_type_slug"`
Locale string `json:"locale"`
ContentChannel string `json:"content_channel"`
Metadata map[string]any `json:"metadata,omitempty"`
}
ContentURLRedirect is a host-owned historical URL redirect record.
type ContentURLRedirectBulkCaptureInput ¶ added in v0.111.0
type ContentURLRedirectBulkCaptureInput struct {
BeforeSiteConfig ResolvedSiteConfig
AfterSiteConfig ResolvedSiteConfig
Items []ContentURLRedirectBulkItem
Recorder ContentURLRedirectRecorder
ChainUpdater ContentURLRedirectChainUpdater
SourceOwnerLookup ContentURLRedirectSourceOwnerLookupService
Mode ContentURLRedirectBulkMode
IncludeBase bool
IncludeLocale bool
StatusCode int
Reason string
SiteKey string
ContentChannel string
BeforeContentChannel string
AfterContentChannel string
Metadata map[string]any
PathShape ContentURLRedirectPathShape
ChainPolicy ContentURLRedirectChainPolicy
ContinueOnRecorderError bool
}
ContentURLRedirectBulkCaptureInput configures route-affecting bulk capture.
type ContentURLRedirectBulkCaptureResult ¶ added in v0.111.0
type ContentURLRedirectBulkCaptureResult struct {
Items []ContentURLRedirectBulkItemResult `json:"items"`
Recorded int `json:"recorded"`
Skipped int `json:"skipped"`
Failed int `json:"failed"`
Processed int `json:"processed"`
}
ContentURLRedirectBulkCaptureResult reports aggregate and per-record outcomes.
func CaptureContentURLRedirectBulk ¶ added in v0.111.0
func CaptureContentURLRedirectBulk(ctx context.Context, input ContentURLRedirectBulkCaptureInput) (ContentURLRedirectBulkCaptureResult, error)
CaptureContentURLRedirectBulk compares many old/new resolver contexts and records historical redirects for each valid public URL move.
type ContentURLRedirectBulkItem ¶ added in v0.111.0
type ContentURLRedirectBulkItem struct {
OldContent admin.CMSContent `json:"old_content"`
NewContent admin.CMSContent `json:"new_content"`
OldContentType admin.CMSContentType `json:"old_content_type"`
NewContentType admin.CMSContentType `json:"new_content_type"`
Locale string `json:"locale"`
SiteKey string `json:"site_key"`
ContentChannel string `json:"content_channel"`
OldContentChannel string `json:"old_content_channel,omitempty"`
NewContentChannel string `json:"new_content_channel,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
PathShape ContentURLRedirectPathShape `json:"path_shape,omitempty"`
IncludeBase *bool `json:"include_base,omitempty"`
IncludeLocale *bool `json:"include_locale,omitempty"`
StatusCode int `json:"status_code"`
Reason string `json:"reason"`
ChainPolicy ContentURLRedirectChainPolicy `json:"chain_policy,omitempty"`
}
ContentURLRedirectBulkItem describes one affected record for route-affecting bulk capture.
type ContentURLRedirectBulkItemResult ¶ added in v0.111.0
type ContentURLRedirectBulkItemResult struct {
Index int `json:"index"`
Status string `json:"status"`
Result ContentURLRedirectCaptureResult `json:"result"`
Error error `json:"-"`
SkipReason string `json:"skip_reason,omitempty"`
}
ContentURLRedirectBulkItemResult reports the capture outcome for one item.
type ContentURLRedirectBulkMode ¶ added in v0.111.0
type ContentURLRedirectBulkMode string
ContentURLRedirectBulkMode controls whether bulk capture stops at the first record failure or returns per-record outcomes.
const ( ContentURLRedirectBulkFailFast ContentURLRedirectBulkMode = "fail_fast" ContentURLRedirectBulkBestEffort ContentURLRedirectBulkMode = "best_effort" )
type ContentURLRedirectCaptureInput ¶ added in v0.111.0
type ContentURLRedirectCaptureInput struct {
SiteConfig ResolvedSiteConfig
OldContent admin.CMSContent
NewContent admin.CMSContent
ContentType admin.CMSContentType
Locale string
SiteKey string
ContentChannel string
PathShape ContentURLRedirectPathShape
IncludeBase bool
IncludeLocale bool
StatusCode int
Reason string
Metadata map[string]any
Recorder ContentURLRedirectRecorder
ChainUpdater ContentURLRedirectChainUpdater
ChainPolicy ContentURLRedirectChainPolicy
SourceOwnerLookup ContentURLRedirectSourceOwnerLookupService
ContinueOnRecorderError bool
AllowContentChannelMove bool
}
ContentURLRedirectCaptureInput configures single-record redirect capture for host content update flows.
type ContentURLRedirectCaptureResult ¶ added in v0.111.0
type ContentURLRedirectCaptureResult struct {
OldPath ContentDeliveryPathResult `json:"old_path"`
NewPath ContentDeliveryPathResult `json:"new_path"`
Change *ContentURLRedirectChange `json:"change,omitempty"`
Redirect *ContentURLRedirect `json:"redirect,omitempty"`
Recorded bool `json:"recorded"`
Skipped bool `json:"skipped"`
SkipReason string `json:"skip_reason,omitempty"`
RecordError error `json:"-"`
ChainError error `json:"-"`
ChainStatus string `json:"chain_status,omitempty"`
SourceOwner *ContentURLRedirectSourceOwner
}
ContentURLRedirectCaptureResult reports whether a change was recorded or why it was skipped.
func CaptureContentURLRedirect ¶ added in v0.111.0
func CaptureContentURLRedirect(ctx context.Context, input ContentURLRedirectCaptureInput) (ContentURLRedirectCaptureResult, error)
CaptureContentURLRedirect compares old and new effective delivery paths for a single content record and records a historical redirect when the public path changed.
type ContentURLRedirectChainPolicy ¶ added in v0.111.0
type ContentURLRedirectChainPolicy string
ContentURLRedirectChainPolicy controls whether capture may record a redirect when chain-flattening support is unavailable.
const ( ContentURLRedirectChainOptional ContentURLRedirectChainPolicy = "optional" ContentURLRedirectChainRequired ContentURLRedirectChainPolicy = "required" )
type ContentURLRedirectChainUpdater ¶ added in v0.111.0
type ContentURLRedirectChainUpdater interface {
FlattenContentURLRedirectChain(context.Context, ContentURLRedirectChange) error
}
ContentURLRedirectChainUpdater lets stores flatten existing chains after a content move is recorded.
type ContentURLRedirectChange ¶ added in v0.111.0
type ContentURLRedirectChange struct {
ContentID string `json:"content_id"`
ContentTypeSlug string `json:"content_type_slug"`
Locale string `json:"locale"`
SiteKey string `json:"site_key"`
ContentChannel string `json:"content_channel"`
OldContentChannel string `json:"old_content_channel,omitempty"`
NewContentChannel string `json:"new_content_channel,omitempty"`
OldPath string `json:"old_path"`
NewPath string `json:"new_path"`
StatusCode int `json:"status_code"`
Reason string `json:"reason"`
Metadata map[string]any `json:"metadata,omitempty"`
}
ContentURLRedirectChange describes a public content URL move that a host application may persist as a historical redirect.
type ContentURLRedirectLookup ¶ added in v0.111.0
type ContentURLRedirectLookup struct {
Path string `json:"path"`
Method string `json:"method"`
Locale string `json:"locale"`
DefaultLocale string `json:"default_locale"`
SiteKey string `json:"site_key"`
Host string `json:"host"`
ContentChannel string `json:"content_channel"`
BasePath string `json:"base_path"`
WantsJSON bool `json:"wants_json"`
}
ContentURLRedirectLookup describes a public-site request that did not resolve to current content and may have a host-owned historical URL redirect.
type ContentURLRedirectPathShape ¶ added in v0.111.0
type ContentURLRedirectPathShape string
ContentURLRedirectPathShape controls whether capture stores runtime-public paths or caller-specified explicit path shapes.
const ( ContentURLRedirectPathRuntimePublic ContentURLRedirectPathShape = "runtime_public" ContentURLRedirectPathExplicit ContentURLRedirectPathShape = "explicit" )
type ContentURLRedirectRecorder ¶ added in v0.111.0
type ContentURLRedirectRecorder interface {
RecordContentURLRedirect(context.Context, ContentURLRedirectChange) (*ContentURLRedirect, error)
}
ContentURLRedirectRecorder records host-owned historical URL redirects.
type ContentURLRedirectSourceOwner ¶ added in v0.111.0
type ContentURLRedirectSourceOwner struct {
ContentID string `json:"content_id"`
ContentTypeSlug string `json:"content_type_slug"`
Locale string `json:"locale"`
ContentChannel string `json:"content_channel"`
}
ContentURLRedirectSourceOwner describes active content that currently owns a path in the same site scope.
type ContentURLRedirectSourceOwnerLookup ¶ added in v0.111.0
type ContentURLRedirectSourceOwnerLookup struct {
Path string `json:"path"`
SiteKey string `json:"site_key"`
ContentChannel string `json:"content_channel"`
Locale string `json:"locale"`
}
ContentURLRedirectSourceOwnerLookup identifies the source path being checked for active content ownership.
type ContentURLRedirectSourceOwnerLookupService ¶ added in v0.111.0
type ContentURLRedirectSourceOwnerLookupService interface {
LookupContentURLRedirectSourceOwner(context.Context, ContentURLRedirectSourceOwnerLookup) (*ContentURLRedirectSourceOwner, error)
}
ContentURLRedirectSourceOwnerLookupService checks whether a redirect source path is already owned by active content.
type ContentURLRedirectStore ¶ added in v0.111.0
type ContentURLRedirectStore interface {
LookupContentURLRedirect(context.Context, ContentURLRedirectLookup) (*ContentURLRedirect, error)
}
ContentURLRedirectStore lets host applications provide historical URL redirect lookup without go-admin owning persistence or migrations.
type DeliveryProvenance ¶ added in v0.115.1
type DeliveryProvenance struct {
RouteFamily string `json:"route_family,omitempty"`
OwnerKind string `json:"owner_kind,omitempty"`
Mode string `json:"mode,omitempty"`
RequestedTemplate string `json:"requested_template,omitempty"`
SelectedTemplate string `json:"selected_template,omitempty"`
TemplateAttempts []DeliveryTemplateAttempt `json:"template_attempts,omitempty"`
FallbackUsed bool `json:"fallback_used"`
CacheStatus string `json:"cache_status,omitempty"`
RenderVersion string `json:"render_version,omitempty"`
SemanticIdentity string `json:"semantic_identity,omitempty"`
TextCode string `json:"text_code,omitempty"`
}
DeliveryProvenance describes how a public-site response was resolved and rendered. It is safe for operational diagnostics and contains no content payload or record identifiers.
func ParseDeliveryProvenanceHeaders ¶ added in v0.115.3
func ParseDeliveryProvenanceHeaders(headers http.Header) (DeliveryProvenance, error)
ParseDeliveryProvenanceHeaders decodes the sanitized delivery transport contract. Malformed attempt data is returned as an error instead of being silently discarded by host diagnostics.
func (DeliveryProvenance) ValidateFinalized ¶ added in v0.115.3
func (p DeliveryProvenance) ValidateFinalized() error
ValidateFinalized verifies that a finalized delivery observation contains enough information to be authoritative. Render failures may omit a selected template, but successful observations must identify the selected attempt.
type DeliveryTemplateAttempt ¶ added in v0.115.1
type DeliveryTemplateAttempt struct {
Template string `json:"template"`
Outcome string `json:"outcome"`
}
DeliveryTemplateAttempt is a sanitized record of one template attempt. It intentionally excludes rendered data, filesystem paths, and raw errors.
type LocalePathBridgeDiagnostic ¶ added in v0.36.0
type LocalePrefixMode ¶
type LocalePrefixMode string
LocalePrefixMode controls locale path prefix behavior.
const ( LocalePrefixNonDefault LocalePrefixMode = "non_default" LocalePrefixAlways LocalePrefixMode = "always" )
type RenderCacheBackendDescriber ¶ added in v0.67.0
type RenderCacheBackendDescriber interface {
RenderCacheBackendKind() string
}
RenderCacheBackendDescriber lets host stores declare whether they are memory or shared backends without quickstart/site importing a concrete cache package.
type RenderCacheBypassPredicate ¶ added in v0.66.0
type RenderCacheBypassPredicate func(c router.Context, state RequestState) (bool, string)
RenderCacheBypassPredicate lets host applications block caching when they know about auth, session, or personalization state that quickstart/site does not own.
type RenderCacheConfig ¶ added in v0.69.0
type RenderCacheConfig struct {
Enabled bool
Backend string
// AllowProcessLocalFence explicitly authorizes a process-local generation
// store for single-process development and tests. Hosts must leave this false
// whenever more than one serving instance can handle public requests.
AllowProcessLocalFence bool
FreshTTL time.Duration
StaleTTL time.Duration
ExpirationMode RenderCacheExpirationMode
RenderVersion string
Namespace string
DebugHeaders bool
DebugKeys bool
FailClosed bool
RequireTagIndex bool
MaxCaptureBodySize int64
Valkey RenderCacheValkeyConfig
}
type RenderCacheDebugCachedResponse ¶ added in v0.69.0
type RenderCacheDebugCachedResponse struct {
Timestamp time.Time `json:"timestamp"`
Status int `json:"status"`
ContentType string `json:"content_type,omitempty"`
BodySize int `json:"body_size"`
HeaderCount int `json:"header_count"`
TagCount int `json:"tag_count"`
FreshUntil *time.Time `json:"fresh_until,omitempty"`
StaleUntil *time.Time `json:"stale_until,omitempty"`
TTLSeconds int64 `json:"ttl_seconds,omitempty"`
TTLClass string `json:"ttl_class,omitempty"`
Key *RenderCacheDebugKey `json:"key,omitempty"`
}
type RenderCacheDebugCapabilities ¶ added in v0.69.0
type RenderCacheDebugCapabilities struct {
ConditionalUpdate bool `json:"conditional_update"`
TagInvalidation bool `json:"tag_invalidation"`
PrefixInvalidation bool `json:"prefix_invalidation"`
Close bool `json:"close"`
BackendDescriptor bool `json:"backend_descriptor"`
AppWideTagClearPreferred bool `json:"app_wide_tag_clear_preferred"`
ProcessLocalObservedKeys bool `json:"process_local_observed_keys"`
BackendKeyScanningEnabled bool `json:"backend_key_scanning_enabled"`
}
func RenderCacheDebugCapabilitiesForStore ¶ added in v0.69.0
func RenderCacheDebugCapabilitiesForStore(store RenderCacheStore) RenderCacheDebugCapabilities
type RenderCacheDebugCommand ¶ added in v0.69.0
type RenderCacheDebugConfig ¶ added in v0.69.0
type RenderCacheDebugConfig struct {
Enabled bool `json:"enabled"`
Backend string `json:"backend"`
FreshTTL string `json:"fresh_ttl"`
StaleTTL string `json:"stale_ttl"`
ExpirationMode RenderCacheExpirationMode `json:"expiration_mode"`
RenderVersion string `json:"render_version"`
Namespace string `json:"namespace"`
DebugHeaders bool `json:"debug_headers"`
DebugKeys bool `json:"debug_keys"`
FailClosed bool `json:"fail_closed"`
RequireTagIndex bool `json:"require_tag_index"`
MaxCaptureBodySize int64 `json:"max_capture_body_size"`
Valkey RenderCacheValkeyDebugCfg `json:"valkey"`
}
type RenderCacheDebugCounters ¶ added in v0.69.0
type RenderCacheDebugCounters struct {
Lookups int64 `json:"lookups"`
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
Writes int64 `json:"writes"`
Deletes int64 `json:"deletes"`
Invalidations int64 `json:"invalidations"`
Errors int64 `json:"errors"`
Clears int64 `json:"clears"`
HitRatio *float64 `json:"hit_ratio,omitempty"`
}
type RenderCacheDebugError ¶ added in v0.69.0
type RenderCacheDebugKey ¶ added in v0.69.0
type RenderCacheDebugObservedStore ¶ added in v0.69.0
type RenderCacheDebugObservedStore interface {
RenderCacheDebugObserver() *RenderCacheDebugObserver
}
type RenderCacheDebugObserver ¶ added in v0.69.0
type RenderCacheDebugObserver struct {
// contains filtered or unexported fields
}
func NewRenderCacheDebugObserver ¶ added in v0.69.0
func NewRenderCacheDebugObserver(store RenderCacheStore, cfg RenderCacheConfig) *RenderCacheDebugObserver
func (*RenderCacheDebugObserver) ClearAll ¶ added in v0.69.0
func (s *RenderCacheDebugObserver) ClearAll(ctx context.Context) RenderCacheDebugCommand
func (*RenderCacheDebugObserver) Delete ¶ added in v0.69.0
func (s *RenderCacheDebugObserver) Delete(ctx context.Context, key string) error
func (*RenderCacheDebugObserver) Get ¶ added in v0.69.0
func (s *RenderCacheDebugObserver) Get(ctx context.Context, key string) (RenderedSiteResponse, bool, error)
func (*RenderCacheDebugObserver) ObserveRenderCacheRequest ¶ added in v0.127.3
func (s *RenderCacheDebugObserver) ObserveRenderCacheRequest(_ context.Context, observation RenderCacheRequestObservation)
ObserveRenderCacheRequest records bounded request-level cache decisions while store operations continue to be recorded by the decorated RenderCacheStore.
func (*RenderCacheDebugObserver) RenderCacheDebugObserver ¶ added in v0.69.0
func (s *RenderCacheDebugObserver) RenderCacheDebugObserver() *RenderCacheDebugObserver
func (*RenderCacheDebugObserver) Set ¶ added in v0.69.0
func (s *RenderCacheDebugObserver) Set(ctx context.Context, key string, value RenderedSiteResponse, ttl time.Duration) error
func (*RenderCacheDebugObserver) Snapshot ¶ added in v0.69.0
func (s *RenderCacheDebugObserver) Snapshot(runtime *RenderCacheRuntime) RenderCacheDebugSnapshot
type RenderCacheDebugOperation ¶ added in v0.69.0
type RenderCacheDebugOperation struct {
Timestamp time.Time `json:"timestamp"`
Operation string `json:"operation"`
Backend string `json:"backend"`
Outcome string `json:"outcome"`
Key *RenderCacheDebugKey `json:"key,omitempty"`
TTLSeconds int64 `json:"ttl_seconds,omitempty"`
TargetCount int `json:"target_count,omitempty"`
Mode string `json:"mode,omitempty"`
Message string `json:"message,omitempty"`
}
type RenderCacheDebugRequestCounters ¶ added in v0.127.3
type RenderCacheDebugRequestCounters struct {
Evaluated int64 `json:"evaluated"`
Eligible int64 `json:"eligible"`
Bypassed int64 `json:"bypassed"`
Terminal int64 `json:"terminal"`
ServedHits int64 `json:"served_hits"`
ServedStale int64 `json:"served_stale"`
StoredResponses int64 `json:"stored_responses"`
RenderedUncached int64 `json:"rendered_uncached"`
Failed int64 `json:"failed"`
BypassReasons map[string]int64 `json:"bypass_reasons"`
ReasonCounts map[string]int64 `json:"reason_counts"`
Surfaces map[string]RenderCacheDebugSurfaceCounters `json:"surfaces"`
}
RenderCacheDebugRequestCounters describes request-level public HTML cache decisions. It is separate from RenderCacheDebugCounters because bypassed requests intentionally perform no backend operation.
type RenderCacheDebugSnapshot ¶ added in v0.69.0
type RenderCacheDebugSnapshot struct {
Configured bool `json:"configured"`
Active bool `json:"active"`
Backend string `json:"backend"`
Status string `json:"status"`
Scope string `json:"scope"`
ObservedBy string `json:"observed_by"`
Engagement string `json:"engagement"`
StartupError *RenderCacheStartupError `json:"startup_error,omitempty"`
Config RenderCacheDebugConfig `json:"config"`
Capabilities RenderCacheDebugCapabilities `json:"capabilities"`
Counters RenderCacheDebugCounters `json:"counters"`
RequestCounters RenderCacheDebugRequestCounters `json:"request_counters"`
LatestCached *RenderCacheDebugCachedResponse `json:"latest_cached,omitempty"`
ObservedKeys []RenderCacheDebugKey `json:"observed_keys"`
RecentOperations []RenderCacheDebugOperation `json:"recent_operations"`
RecentErrors []RenderCacheDebugError `json:"recent_errors"`
LastCommand *RenderCacheDebugCommand `json:"last_command,omitempty"`
}
type RenderCacheDebugSurfaceCounters ¶ added in v0.129.0
type RenderCacheDebugSurfaceCounters struct {
Evaluated int64 `json:"evaluated"`
Eligible int64 `json:"eligible"`
Bypassed int64 `json:"bypassed"`
Terminal int64 `json:"terminal"`
ServedHits int64 `json:"served_hits"`
ServedStale int64 `json:"served_stale"`
StoredResponses int64 `json:"stored_responses"`
RenderedUncached int64 `json:"rendered_uncached"`
Failed int64 `json:"failed"`
BypassReasons map[string]int64 `json:"bypass_reasons"`
ReasonCounts map[string]int64 `json:"reason_counts"`
}
RenderCacheDebugSurfaceCounters contains the same request lifecycle totals for one bounded static surface. Backend operation totals intentionally remain in RenderCacheDebugCounters rather than being inferred from these values.
type RenderCacheExpirationMode ¶ added in v0.128.0
type RenderCacheExpirationMode string
RenderCacheExpirationMode controls whether fresh cache hits retain their original deadline or renew it.
const ( RenderCacheExpirationFixed RenderCacheExpirationMode = "fixed" RenderCacheExpirationSliding RenderCacheExpirationMode = "sliding" )
type RenderCacheGenerationStore ¶ added in v0.127.4
type RenderCacheGenerationStore interface {
ReadGeneration(ctx context.Context, scope string) (uint64, error)
AdvanceGeneration(ctx context.Context, scope string) (uint64, error)
}
RenderCacheGenerationStore provides the mutation generation used to keep an in-flight pre-mutation fill from becoming visible after a mutation completes. Shared reports whether every serving process can observe the same generation.
type RenderCacheHandlerDecision ¶ added in v0.127.4
type RenderCacheHandlerDecision struct {
Cacheable bool
Reason string
Surface string
CanonicalPath string
CanonicalQuery string
FreshTTLOverride time.Duration
DisableStale bool
// FenceScopes participates in the representation identity and is re-read
// before a captured miss is stored. FenceScope remains the compatible
// single-scope alias and is merged into this bounded set.
FenceScopes []string
FenceScope string
RequireFence bool
// AllowProcessLocalFence is intended only for explicit single-process
// development and tests. Production hosts should leave it false.
AllowProcessLocalFence bool
State RequestState
}
RenderCacheHandlerDecision is the host-owned, pre-handler cache decision. CanonicalPath and CanonicalQuery are hashed before entering the backend key.
type RenderCacheHandlerOptions ¶ added in v0.127.4
type RenderCacheHandlerOptions struct {
Decide func(router.Context) (RenderCacheHandlerDecision, error)
ResolveTags func(router.Context) ([]string, error)
ObservationSurface func(router.Context) string
}
RenderCacheHandlerOptions configures arbitrary public HTML handler caching. Decide must be cheap and deterministic. ResolveTags runs only after a safe GET miss has executed and may inspect request locals populated by the handler.
type RenderCachePolicy ¶ added in v0.66.0
type RenderCachePolicy struct {
Enabled bool `json:"enabled"`
SchemaVersion string `json:"schema_version"`
ApplicationNamespace string `json:"application_namespace"`
EnvironmentNamespace string `json:"environment_namespace"`
SiteNamespace string `json:"site_namespace"`
RenderVersion string `json:"render_version"`
FreshTTL time.Duration `json:"fresh_ttl"`
StaleTTL time.Duration `json:"stale_ttl"`
ExpirationMode RenderCacheExpirationMode `json:"expiration_mode"`
CacheableMethods []string `json:"cacheable_methods"`
CacheableStatuses []int `json:"cacheable_statuses"`
QueryAllowlist []string `json:"query_allowlist"`
HeaderAllowlist []string `json:"header_allowlist"`
AuthCookieNames []string `json:"auth_cookie_names"`
DebugHeaders bool `json:"debug_headers"`
DebugKeys bool `json:"debug_keys"`
FailClosed bool `json:"fail_closed"`
// RequireTagIndex makes page storage depend on production-safe tag indexing.
// When enabled, stores must implement RenderCacheTagInvalidator and must not
// be a memory backend. This is intended for production invalidation rollout.
RequireTagIndex bool `json:"require_tag_index"`
MaxCaptureBodySize int64 `json:"max_capture_body_size"`
TemplateRenderer RenderCacheTemplateRenderer `json:"-"`
BypassPredicates []RenderCacheBypassPredicate `json:"-"`
// HostBypassReasonAllowlist contains static host-owned reason tokens that may
// be exposed to request diagnostics. Unlisted predicate reasons collapse to
// host_bypass so request-derived values cannot create unbounded telemetry.
HostBypassReasonAllowlist []string `json:"-"`
StaleRevalidator RenderCacheStaleRevalidator `json:"-"`
}
RenderCachePolicy controls public-site rendered HTML caching.
type RenderCachePrefixInvalidator ¶ added in v0.66.0
type RenderCachePrefixInvalidator interface {
DeleteByKeyPrefix(ctx context.Context, prefix string) error
}
RenderCachePrefixInvalidator is implemented by stores that can delete keys by prefix.
type RenderCacheRequestObservation ¶ added in v0.127.3
type RenderCacheRequestObservation struct {
Surface string `json:"surface"`
Phase RenderCacheRequestPhase `json:"phase"`
Outcome RenderCacheRequestOutcome `json:"outcome"`
Reason string `json:"reason,omitempty"`
}
RenderCacheRequestObservation contains bounded, privacy-safe request cache diagnostics. It deliberately excludes paths, queries, keys, cookies, headers, bodies, and content identifiers.
type RenderCacheRequestObserver ¶ added in v0.127.3
type RenderCacheRequestObserver interface {
ObserveRenderCacheRequest(context.Context, RenderCacheRequestObservation)
}
RenderCacheRequestObserver observes public HTML cache request decisions and terminal outcomes. Implementations must return quickly. Panics are isolated from visitor responses and from other observers.
type RenderCacheRequestOutcome ¶ added in v0.127.3
type RenderCacheRequestOutcome string
RenderCacheRequestOutcome is a bounded request-level cache outcome. These outcomes intentionally describe delivery rather than individual store calls.
const ( RenderCacheRequestOutcomeEligible RenderCacheRequestOutcome = "eligible" RenderCacheRequestOutcomeBypassed RenderCacheRequestOutcome = "bypassed" RenderCacheRequestOutcomeHit RenderCacheRequestOutcome = "hit" RenderCacheRequestOutcomeStale RenderCacheRequestOutcome = "stale" RenderCacheRequestOutcomeStored RenderCacheRequestOutcome = "stored" RenderCacheRequestOutcomeRenderedUncached RenderCacheRequestOutcome = "rendered_uncached" RenderCacheRequestOutcomeFailed RenderCacheRequestOutcome = "failed" )
type RenderCacheRequestPhase ¶ added in v0.127.3
type RenderCacheRequestPhase string
RenderCacheRequestPhase identifies where an observation was emitted in the public HTML cache request lifecycle.
const ( RenderCacheRequestPhaseEvaluated RenderCacheRequestPhase = "evaluated" RenderCacheRequestPhaseTerminal RenderCacheRequestPhase = "terminal" )
type RenderCacheRevalidationRequest ¶ added in v0.67.0
type RenderCacheRevalidationRequest struct {
Key string
RequestPath string
State RequestState
Response RenderedSiteResponse
}
RenderCacheRevalidationRequest describes a stale cache hit that can be refreshed by a host-owned background worker.
type RenderCacheRuntime ¶ added in v0.69.0
type RenderCacheRuntime struct {
Config RenderCacheConfig
Store RenderCacheStore
Generations RenderCacheGenerationStore
Policy RenderCachePolicy
Diagnostic RenderCacheStartupDiagnostic
Observer *RenderCacheDebugObserver
RequestObservers []RenderCacheRequestObserver
}
func NewRenderCacheRuntime ¶ added in v0.69.0
func NewRenderCacheRuntime(ctx context.Context, cfg RenderCacheConfig, policy RenderCachePolicy) (*RenderCacheRuntime, error)
type RenderCacheSetIfPresentStore ¶ added in v0.128.0
type RenderCacheSetIfPresentStore interface {
SetIfPresent(ctx context.Context, key string, value RenderedSiteResponse, ttl time.Duration) (bool, error)
}
RenderCacheSetIfPresentStore conditionally replaces a live entry. It is structurally compatible with go-cache's optional SetIfPresentCache contract.
type RenderCacheStaleRevalidator ¶ added in v0.67.0
type RenderCacheStaleRevalidator func(ctx context.Context, request RenderCacheRevalidationRequest)
RenderCacheStaleRevalidator is called asynchronously after a stale response is replayed. Hosts should use it to schedule safe background regeneration.
type RenderCacheStartupDiagnostic ¶ added in v0.69.0
type RenderCacheStartupError ¶ added in v0.69.0
type RenderCacheStore ¶ added in v0.66.0
type RenderCacheStore interface {
Get(ctx context.Context, key string) (RenderedSiteResponse, bool, error)
Set(ctx context.Context, key string, value RenderedSiteResponse, ttl time.Duration) error
Delete(ctx context.Context, key string) error
}
RenderCacheStore is the local public-site render cache contract. It matches go-cache-style typed stores without coupling quickstart/site to a backend.
func NewRenderCacheDebugObservedStore ¶ added in v0.69.0
func NewRenderCacheDebugObservedStore(observer *RenderCacheDebugObserver) RenderCacheStore
type RenderCacheTagInvalidator ¶ added in v0.66.0
type RenderCacheTagInvalidator interface {
AddTagsForKey(ctx context.Context, key string, tags []string) error
InvalidateTags(ctx context.Context, tags []string) error
}
RenderCacheTagInvalidator is implemented by stores that can associate and invalidate cache keys by tag.
type RenderCacheTemplateRenderer ¶ added in v0.66.0
type RenderCacheTemplateRenderer interface {
RenderSiteTemplate(ctx context.Context, templateName string, viewCtx router.ViewContext) (RenderedTemplate, error)
}
RenderCacheTemplateRenderer captures a site template render without writing through router.Context.Render.
type RenderCacheValkeyConfig ¶ added in v0.69.0
type RenderCacheValkeyDebugCfg ¶ added in v0.69.0
type RenderCacheValkeyDebugCfg struct {
Address string `json:"address,omitempty"`
Namespace string `json:"namespace,omitempty"`
URLConfigured bool `json:"url_configured"`
UsernameSet bool `json:"username_set"`
PasswordSet bool `json:"password_set"`
DB int `json:"db"`
TLSEnabled bool `json:"tls_enabled"`
TLSSkipVerify bool `json:"tls_skip_verify"`
}
type RenderedSiteResponse ¶ added in v0.66.0
type RenderedSiteResponse struct {
Status int `json:"status"`
ContentType string `json:"content_type"`
Headers map[string][]string `json:"headers"`
Body []byte `json:"body"`
CreatedAt time.Time `json:"created_at"`
FreshUntil time.Time `json:"fresh_until"`
StaleUntil time.Time `json:"stale_until"`
Tags []string `json:"tags"`
Provenance DeliveryProvenance `json:"provenance"`
}
RenderedSiteResponse is the serializable rendered-page cache value.
type RenderedTemplate ¶ added in v0.66.0
type RenderedTemplate struct {
ContentType string `json:"content_type"`
Headers map[string][]string `json:"headers"`
Body []byte `json:"body"`
}
RenderedTemplate is the controlled output from RenderCacheTemplateRenderer.
type RequestState ¶
type RequestState struct {
Locale string `json:"locale"`
DefaultLocale string `json:"default_locale"`
SupportedLocales []string `json:"supported_locales"`
Environment string `json:"environment"`
ContentChannel string `json:"content_channel"`
AllowLocaleFallback bool `json:"allow_locale_fallback"`
PreviewTokenPresent bool `json:"preview_token_present"`
PreviewTokenValid bool `json:"preview_token_valid"`
IsPreview bool `json:"is_preview"`
PreviewToken string `json:"preview_token"`
PreviewEntityType string `json:"preview_entity_type"`
PreviewContentID string `json:"preview_content_id"`
ThemeName string `json:"theme_name"`
ThemeVariant string `json:"theme_variant"`
Theme map[string]map[string]string `json:"theme"`
SiteTheme map[string]any `json:"site_theme"`
BasePath string `json:"base_path"`
AssetBasePath string `json:"asset_base_path"`
ActivePath string `json:"active_path"`
ViewContext router.ViewContext `json:"view_context"`
}
RequestState is the normalized per-request site runtime state.
func RequestStateFromContext ¶
func RequestStateFromContext(ctx context.Context) (RequestState, bool)
RequestStateFromContext reads request state from context.
func RequestStateFromRequest ¶
func RequestStateFromRequest(c router.Context) (RequestState, bool)
RequestStateFromRequest reads request state from request locals/context.
func ResolveRequestState ¶
func ResolveRequestState( requestCtx context.Context, c router.Context, adm *admin.Admin, _ admin.Config, siteCfg ResolvedSiteConfig, modules []SiteModule, ) (context.Context, RequestState)
ResolveRequestState computes the normalized request context + view context.
type ResolvedSiteConfig ¶
type ResolvedSiteConfig struct {
BasePath string `json:"base_path"`
DefaultLocale string `json:"default_locale"`
SupportedLocales []string `json:"supported_locales"`
AllowLocaleFallback bool `json:"allow_locale_fallback"`
LocalePrefixMode LocalePrefixMode `json:"locale_prefix_mode"`
Environment string `json:"environment"`
ContentChannel string `json:"content_channel"`
InternalOps ResolvedSiteInternalOpsConfig `json:"internal_ops"`
Views ResolvedSiteViewConfig `json:"views"`
Search SiteSearchConfig `json:"search"`
Modules []SiteModule `json:"modules"`
Features ResolvedSiteFeatures `json:"features"`
Theme ResolvedSiteThemeConfig `json:"theme"`
ThemeProvider SiteThemeProvider `json:"-"`
Fallback SiteFallbackPolicy `json:"fallback"`
}
ResolvedSiteConfig is a normalized SiteConfig with concrete defaults.
func ResolveSiteConfig ¶
func ResolveSiteConfig(cfg admin.Config, input SiteConfig) ResolvedSiteConfig
ResolveSiteConfig normalizes runtime defaults for site registration.
type ResolvedSiteFeatures ¶
type ResolvedSiteFeatures struct {
EnablePreview bool `json:"enable_preview"`
EnableI18N bool `json:"enable_i18_n"`
EnableSearch bool `json:"enable_search"`
EnableTheme bool `json:"enable_theme"`
EnableMenuDraftPreview bool `json:"enable_menu_draft_preview"`
EnableCanonicalRedirect bool `json:"enable_canonical_redirect"`
CanonicalRedirectMode CanonicalRedirectMode `json:"canonical_redirect_mode"`
StrictLocalizedPaths bool `json:"strict_localized_paths"`
}
ResolvedSiteFeatures contains concrete runtime feature flags.
type ResolvedSiteInternalOpsConfig ¶ added in v0.36.0
type ResolvedSiteInternalOpsConfig struct {
EnableHealthz bool `json:"enable_healthz"`
EnableStatus bool `json:"enable_status"`
HealthzPath string `json:"healthz_path"`
StatusPath string `json:"status_path"`
}
ResolvedSiteInternalOpsConfig contains normalized internal-ops paths used for fallback reserved-prefix derivation.
type ResolvedSiteThemeConfig ¶ added in v0.36.0
type ResolvedSiteThemeConfig struct {
Name string `json:"name"`
Variant string `json:"variant"`
BaselineVariant *string `json:"baseline_variant"`
AllowRequestNameOverride bool `json:"allow_request_name_override"`
AllowRequestVariantOverride bool `json:"allow_request_variant_override"`
}
ResolvedSiteThemeConfig contains normalized site theme defaults and request override policy.
type ResolvedSiteViewConfig ¶
type ResolvedSiteViewConfig struct {
// TemplateFS contains overlay/override template filesystems with higher
// precedence than the base host template filesystem when building a view engine.
TemplateFS []fs.FS `json:"template_fs"`
BaseTemplate string `json:"base_template"`
ErrorTemplate string `json:"error_template"`
ErrorTemplatesByStatus map[int]string `json:"error_templates_by_status"`
ErrorTemplatesByCode map[string]string `json:"error_templates_by_code"`
ErrorPolicy SiteErrorTemplatePolicy `json:"error_policy"`
AssetBasePath string `json:"asset_base_path"`
Reload bool `json:"reload"`
ReloadInDevelopment bool `json:"reload_in_development"`
}
ResolvedSiteViewConfig contains normalized view/runtime defaults.
type ResolvedTemplateSource ¶ added in v0.36.0
type SiteConfig ¶
type SiteConfig struct {
BasePath string `json:"base_path"`
DefaultLocale string `json:"default_locale"`
SupportedLocales []string `json:"supported_locales"`
AllowLocaleFallback *bool `json:"allow_locale_fallback"`
LocalePrefixMode LocalePrefixMode `json:"locale_prefix_mode"`
Environment string `json:"environment"`
ContentChannel string `json:"content_channel"`
InternalOps SiteInternalOpsConfig `json:"internal_ops"`
Views SiteViewConfig `json:"views"`
Search SiteSearchConfig `json:"search"`
Modules []SiteModule `json:"modules"`
Features SiteFeatures `json:"features"`
Theme SiteThemeConfig `json:"theme"`
ThemeProvider SiteThemeProvider `json:"-"`
Fallback SiteFallbackPolicy `json:"fallback"`
}
SiteConfig controls quickstart/site registration behavior.
type SiteErrorContextProvider ¶ added in v0.114.0
type SiteErrorContextProvider interface {
ErrorViewContext(ctx context.Context, request SiteErrorContextRequest, in router.ViewContext) router.ViewContext
}
SiteErrorContextProvider allows a site module to add safe, request-scoped error view fields without rerunning its normal ViewContext lifecycle.
type SiteErrorContextRequest ¶ added in v0.114.0
type SiteErrorContextRequest struct {
Error SiteRuntimeError `json:"error"`
State RequestState `json:"state"`
}
SiteErrorContextRequest contains normalized error identity and request state for optional error-specific context projection.
type SiteErrorRenderEvent ¶ added in v0.114.0
type SiteErrorRenderEvent struct {
Code string `json:"code"`
Status int `json:"status"`
Source string `json:"source"`
ThemeKey string `json:"theme_key,omitempty"`
Template string `json:"template,omitempty"`
Outcome string `json:"outcome"`
Attempt int `json:"attempt"`
IsFallback bool `json:"is_fallback"`
}
SiteErrorRenderEvent describes a sanitized template render attempt or selection. It intentionally contains no view data or rendered bytes.
type SiteErrorRenderObserver ¶ added in v0.114.0
type SiteErrorRenderObserver interface {
ObserveSiteErrorRender(context.Context, SiteErrorRenderEvent)
}
SiteErrorRenderObserver receives sanitized error render diagnostics.
type SiteErrorRenderRequest ¶ added in v0.114.0
type SiteErrorRenderRequest struct {
Error SiteRuntimeError `json:"error"`
State RequestState `json:"state"`
ViewContext router.ViewContext `json:"view_context"`
}
SiteErrorRenderRequest contains the normalized error identity, request state, and optional safe host view fields for HTML error rendering.
type SiteErrorRenderResult ¶ added in v0.114.0
type SiteErrorRenderResult struct {
Template string `json:"template,omitempty"`
Source string `json:"source,omitempty"`
Attempts int `json:"attempts"`
}
SiteErrorRenderResult reports sanitized selection provenance to callers.
func RenderSiteErrorHTML ¶ added in v0.114.0
func RenderSiteErrorHTML( c router.Context, cfg ResolvedSiteConfig, request SiteErrorRenderRequest, ) (SiteErrorRenderResult, error)
RenderSiteErrorHTML atomically renders the first successful error candidate and commits only that captured response. Host applications retain ownership of JSON negotiation and payloads.
Example ¶
ExampleRenderSiteErrorHTML demonstrates a host-owned JSON schema with the shared quickstart HTML renderer used only for browser responses.
package main
import (
"net/http"
"github.com/goliatone/go-admin/quickstart/site"
router "github.com/goliatone/go-router"
)
func main() {
renderHostError := func(c router.Context, cfg site.ResolvedSiteConfig, wantsJSON bool) error {
siteErr := site.SiteRuntimeError{Code: "not_found", Status: http.StatusNotFound}
if wantsJSON {
return c.JSON(http.StatusNotFound, map[string]any{
"code": siteErr.Code,
})
}
_, err := site.RenderSiteErrorHTML(c, cfg, site.SiteErrorRenderRequest{
Error: siteErr,
})
return err
}
_ = renderHostError
}
Output:
type SiteErrorTemplateCandidate ¶ added in v0.114.0
type SiteErrorTemplateCandidate struct {
Template string `json:"template"`
Source string `json:"source"`
ThemeKey string `json:"theme_key,omitempty"`
IsFallback bool `json:"is_fallback"`
}
SiteErrorTemplateCandidate is a resolved, safe render candidate with sanitized provenance for diagnostics.
func ResolveSiteErrorTemplateCandidates ¶ added in v0.114.0
func ResolveSiteErrorTemplateCandidates( cfg ResolvedSiteViewConfig, code string, status int, viewCtx router.ViewContext, ) []SiteErrorTemplateCandidate
ResolveSiteErrorTemplateCandidates resolves the configured policy after request theme context is available. Invalid and duplicate render names are skipped without suppressing later fallbacks.
type SiteErrorTemplatePolicy ¶ added in v0.114.0
type SiteErrorTemplatePolicy struct {
ByCode map[string][]SiteTemplateRef `json:"by_code,omitempty"`
ByStatus map[int][]SiteTemplateRef `json:"by_status,omitempty"`
Fallback []SiteTemplateRef `json:"fallback,omitempty"`
}
SiteErrorTemplatePolicy defines ordered error template references by error code, HTTP status, and generic fallback.
type SiteFallbackMode ¶ added in v0.36.0
type SiteFallbackMode string
const ( SiteFallbackModeDisabled SiteFallbackMode = "disabled" SiteFallbackModePublicContentOnly SiteFallbackMode = "public_content_only" SiteFallbackModeExplicitPathsOnly SiteFallbackMode = "explicit_paths_only" DefaultSiteFallbackMode SiteFallbackMode = SiteFallbackModePublicContentOnly )
type SiteFallbackPolicy ¶ added in v0.36.0
type SiteFallbackPolicy struct {
Mode SiteFallbackMode `json:"mode"`
AllowRoot bool `json:"allow_root"`
AllowedMethods []router.HTTPMethod `json:"allowed_methods,omitempty"`
AllowedExactPaths []string `json:"allowed_exact_paths,omitempty"`
AllowedPathPrefixes []string `json:"allowed_path_prefixes,omitempty"`
ReservedPrefixes []string `json:"reserved_prefixes,omitempty"`
StaticInput quickstart.SiteStaticPrefixInput `json:"static_input"`
}
func DefaultSiteFallbackPolicy ¶ added in v0.36.0
func DefaultSiteFallbackPolicy() SiteFallbackPolicy
func NormalizeSiteFallbackPolicy ¶ added in v0.36.0
func NormalizeSiteFallbackPolicy(policy SiteFallbackPolicy) SiteFallbackPolicy
func ResolveSiteFallbackPolicy ¶ added in v0.36.0
func ResolveSiteFallbackPolicy(policy SiteFallbackPolicy) SiteFallbackPolicy
type SiteFeatures ¶
type SiteFeatures struct {
EnablePreview *bool `json:"enable_preview"`
EnableI18N *bool `json:"enable_i18_n"`
EnableSearch *bool `json:"enable_search"`
EnableTheme *bool `json:"enable_theme"`
EnableMenuDraftPreview *bool `json:"enable_menu_draft_preview"`
EnableCanonicalRedirect *bool `json:"enable_canonical_redirect"`
CanonicalRedirectMode CanonicalRedirectMode `json:"canonical_redirect_mode"`
StrictLocalizedPaths *bool `json:"strict_localized_paths"`
}
SiteFeatures controls runtime feature gates.
type SiteInternalOpsConfig ¶ added in v0.36.0
type SiteInternalOpsConfig struct {
EnableHealthz bool `json:"enable_healthz"`
EnableStatus bool `json:"enable_status"`
HealthzPath string `json:"healthz_path"`
StatusPath string `json:"status_path"`
}
SiteInternalOpsConfig describes host-owned internal-ops endpoints that the public-site fallback must reserve when enabled.
type SiteModule ¶
type SiteModule interface {
ID() string
RegisterRoutes(ctx SiteModuleContext) error
ViewContext(ctx context.Context, in router.ViewContext) router.ViewContext
}
SiteModule allows host modules to contribute routes and view context.
type SiteModuleContext ¶
type SiteModuleContext struct {
Admin *admin.Admin `json:"admin"`
Router SiteRouter `json:"router"`
BasePath string `json:"base_path"`
DefaultLocale string `json:"default_locale"`
ThemeEnabled bool `json:"theme_enabled"`
SearchProvider admin.SearchProvider `json:"search_provider"`
SearchOps *admin.GoSearchOperations `json:"search_ops"`
}
SiteModuleContext contains stable dependencies for module route registration.
type SiteNavigationConfig ¶
type SiteNavigationConfig struct {
}
SiteNavigationConfig defines site menu defaults.
type SiteOption ¶
type SiteOption func(*siteRegisterOptions)
SiteOption customizes RegisterSiteRoutes behavior.
func WithAllowedExactPaths ¶ added in v0.36.0
func WithAllowedExactPaths(paths ...string) SiteOption
func WithAllowedFallbackMethods ¶ added in v0.36.0
func WithAllowedFallbackMethods(methods ...router.HTTPMethod) SiteOption
func WithAllowedPathPrefixes ¶ added in v0.36.0
func WithAllowedPathPrefixes(prefixes ...string) SiteOption
func WithContentHandler ¶
func WithContentHandler(handler router.HandlerFunc) SiteOption
WithContentHandler overrides the default catch-all site content handler.
func WithContentURLRedirectSiteKey ¶ added in v0.111.0
func WithContentURLRedirectSiteKey(siteKey string) SiteOption
WithContentURLRedirectSiteKey sets the stable host-owned site scope included in historical URL redirect lookup and capture contracts.
func WithContentURLRedirectStore ¶ added in v0.111.0
func WithContentURLRedirectStore(store ContentURLRedirectStore) SiteOption
WithContentURLRedirectStore registers a host-owned historical URL redirect lookup store for public-site content delivery.
func WithDeliveryServices ¶
func WithDeliveryServices(contentSvc admin.CMSContentService, contentTypeSvc admin.CMSContentTypeService) SiteOption
WithDeliveryServices sets explicit content/content-type services for capability-driven site delivery handlers.
func WithFallbackPolicy ¶ added in v0.36.0
func WithFallbackPolicy(policy SiteFallbackPolicy) SiteOption
func WithRenderCache ¶ added in v0.66.0
func WithRenderCache(store RenderCacheStore, policy RenderCachePolicy) SiteOption
WithRenderCache configures public-site rendered response caching. The policy remains disabled unless policy.Enabled is true.
func WithRenderCacheRequestObservers ¶ added in v0.127.3
func WithRenderCacheRequestObservers(observers ...RenderCacheRequestObserver) SiteOption
WithRenderCacheRequestObservers appends request-lifecycle observers to the currently configured render cache. It is useful for hosts that keep using the legacy store/policy option while adopting production metrics.
func WithRenderCacheRuntime ¶ added in v0.127.3
func WithRenderCacheRuntime(runtime *RenderCacheRuntime) SiteOption
WithRenderCacheRuntime configures public-site rendered response caching from the complete runtime, preserving request observers independently of store wrappers. The runtime is read during route registration and is not retained.
func WithReservedPrefixes ¶ added in v0.36.0
func WithReservedPrefixes(prefixes ...string) SiteOption
func WithSearchHandlers ¶
func WithSearchHandlers(pageHandler, apiHandler router.HandlerFunc) SiteOption
WithSearchHandlers overrides default search page/api handlers.
func WithSearchOperations ¶ added in v0.27.0
func WithSearchOperations(ops *admin.GoSearchOperations) SiteOption
WithSearchOperations exposes optional search operations to site modules.
func WithSearchProvider ¶
func WithSearchProvider(provider admin.SearchProvider) SiteOption
WithSearchProvider sets the search provider for optional search route wiring.
func WithSiteTheme ¶ added in v0.36.0
func WithSiteTheme(selector gotheme.ThemeSelector) SiteOption
WithSiteTheme wires a go-theme selector into the site runtime without coupling it to admin theme resolution.
func WithSiteThemeProvider ¶ added in v0.36.0
func WithSiteThemeProvider(provider SiteThemeProvider) SiteOption
WithSiteThemeProvider wires an explicit provider into the site runtime.
func WithSuggestHandler ¶
func WithSuggestHandler(handler router.HandlerFunc) SiteOption
WithSuggestHandler overrides the default search suggest handler.
type SiteRouter ¶ added in v0.27.0
type SiteRouter interface {
admin.AdminRouter
Group(prefix string) SiteRouter
Mount(prefix string) SiteRouter
WithGroup(path string, cb func(SiteRouter)) SiteRouter
Use(m ...router.MiddlewareFunc) SiteRouter
}
SiteRouter exposes grouped routing helpers for site modules.
type SiteRoutingOwnershipContext ¶ added in v0.36.0
type SiteRoutingOwnershipContext struct {
Admin *admin.Admin `json:"admin"`
SiteConfig ResolvedSiteConfig `json:"site_config"`
SearchProvider admin.SearchProvider `json:"search_provider"`
SearchOperations *admin.GoSearchOperations `json:"search_ops"`
}
SiteRoutingOwnershipContext contains stable inputs for modules that declare planner-visible public-site ownership.
type SiteRoutingOwnershipProvider ¶ added in v0.36.0
type SiteRoutingOwnershipProvider interface {
RoutingOwnership(ctx SiteRoutingOwnershipContext) []routing.ManifestEntry
}
SiteRoutingOwnershipProvider allows site modules to expose exact public-site and public-api routes to the shared routing planner without mutating the router.
type SiteRuntimeError ¶
type SiteRuntimeError struct {
Code string `json:"code"`
Status int `json:"status"`
Message string `json:"message"`
RequestedLocale string `json:"requested_locale"`
AvailableLocales []string `json:"available_locales"`
ContentType string `json:"content_type"`
SlugOrPath string `json:"slug_or_path"`
Cause error `json:"-"`
}
SiteRuntimeError carries normalized site error metadata used by HTML and API responses.
func (SiteRuntimeError) Error ¶
func (e SiteRuntimeError) Error() string
func (SiteRuntimeError) Unwrap ¶ added in v0.115.1
func (e SiteRuntimeError) Unwrap() error
type SiteSearchConfig ¶
type SiteSearchConfig struct {
Route string `json:"route"`
Endpoint string `json:"endpoint"`
Indexes []string `json:"indexes,omitempty"`
Collections []string `json:"collections"`
VariantPolicy *SiteSearchVariantPolicy `json:"variant_policy,omitempty"`
PageSizePolicy *SiteSearchPageSizePolicy `json:"page_size_policy,omitempty"`
FilterOnlyPolicy *SiteSearchFilterOnlyPolicy `json:"filter_only_policy,omitempty"`
FacetExpansionPolicy *SiteSearchFacetExpansionPolicy `json:"facet_expansion_policy,omitempty"`
}
SiteSearchConfig controls optional site search routes.
type SiteSearchFacetExpansionPolicy ¶ added in v0.117.0
type SiteSearchFacetExpansionPolicy struct {
Fields []string `json:"fields"`
}
type SiteSearchFilterInjector ¶
type SiteSearchFilterInjector interface {
SearchFilters(ctx context.Context, c router.Context, req SiteSearchFilterRequest) map[string][]string
}
SiteSearchFilterInjector allows modules to inject additional filter values into search and suggest provider requests.
type SiteSearchFilterOnlyPolicy ¶ added in v0.117.0
type SiteSearchFilterOnlyPolicy struct {
Enabled bool `json:"enabled"`
EligibleFilterFields []string `json:"eligible_filter_fields"`
EligibleRangeFields []string `json:"eligible_range_fields"`
EligibleLandingConstraints []string `json:"eligible_landing_constraints"`
MaxPage int `json:"max_page"`
MaxPageSize int `json:"max_page_size"`
MaxCandidates int `json:"max_candidates"`
}
type SiteSearchFilterRequest ¶
type SiteSearchFilterRequest struct {
Query string `json:"query"`
Locale string `json:"locale"`
Filters map[string][]string `json:"filters"`
Ranges []admin.SearchRange `json:"ranges,omitempty"`
IsSuggest bool `json:"is_suggest"`
}
SiteSearchFilterRequest describes the current search request state that module filter injectors can inspect before returning extra filters.
type SiteSearchPageSizePolicy ¶ added in v0.117.0
type SiteSearchVariantPolicy ¶ added in v0.117.0
type SiteSearchVariantPolicy struct {
QueryParameter string `json:"query_parameter"`
Default admin.SearchVariant `json:"default,omitempty"`
Allowed []admin.SearchVariant `json:"allowed"`
IncludeInSuggestions bool `json:"include_in_suggestions"`
}
type SiteTemplatePrecedenceDiagnostic ¶ added in v0.36.0
type SiteTemplatePrecedenceDiagnostic struct {
Key string `json:"key"`
Template string `json:"template"`
Winner *ResolvedTemplateSource `json:"winner,omitempty"`
Shadowed []ResolvedTemplateSource `json:"shadowed,omitempty"`
Missing bool `json:"missing,omitempty"`
WinnerIsPackaged bool `json:"winner_is_packaged_theme,omitempty"`
PackagedThemeShadowed bool `json:"packaged_theme_shadowed,omitempty"`
}
type SiteTemplateRef ¶ added in v0.114.0
type SiteTemplateRef struct {
Template string `json:"template,omitempty"`
ThemeKey string `json:"theme_key,omitempty"`
DefaultTemplate string `json:"default_template,omitempty"`
}
SiteTemplateRef identifies a concrete template or a public-theme manifest template key with an optional stable concrete default.
type SiteThemeConfig ¶
type SiteThemeConfig struct {
Name string `json:"name"`
Variant string `json:"variant"`
BaselineVariant *string `json:"baseline_variant"`
AllowRequestNameOverride *bool `json:"allow_request_name_override"`
AllowRequestVariantOverride *bool `json:"allow_request_variant_override"`
}
SiteThemeConfig controls site-level theme defaults.
type SiteThemeProvider ¶ added in v0.36.0
type SiteThemeProvider func(ctx context.Context, request SiteThemeRequest) (*admin.ThemeSelection, error)
SiteThemeProvider resolves site-scoped theme selections without coupling site requests to admin theme resolution.
func ThemeProviderFromSelector ¶ added in v0.36.0
func ThemeProviderFromSelector(selector gotheme.ThemeSelector) SiteThemeProvider
ThemeProviderFromSelector adapts a go-theme selector into the site theme provider contract.
type SiteThemeRequest ¶ added in v0.36.0
type SiteThemeRequest struct {
Configured SiteThemeSelector `json:"configured"`
Requested SiteThemeSelector `json:"requested"`
Selector SiteThemeSelector `json:"selector"`
}
SiteThemeRequest carries configured and request-scoped site theme selectors.
type SiteThemeSelector ¶ added in v0.36.0
SiteThemeSelector describes a site-scoped theme/variant selection.
func SiteThemeSelectorFromContext ¶ added in v0.36.0
func SiteThemeSelectorFromContext(ctx context.Context) SiteThemeSelector
SiteThemeSelectorFromContext extracts site-scoped theme overrides from context.
type SiteViewConfig ¶
type SiteViewConfig struct {
// TemplateFS contains overlay/override template filesystems. The host application's
// base template filesystem is still passed separately to quickstart.NewViewEngine.
TemplateFS []fs.FS `json:"template_fs"`
BaseTemplate string `json:"base_template"`
ErrorTemplate string `json:"error_template"`
ErrorTemplatesByStatus map[int]string `json:"error_templates_by_status"`
ErrorTemplatesByCode map[string]string `json:"error_templates_by_code"`
ErrorPolicy SiteErrorTemplatePolicy `json:"error_policy"`
AssetBasePath string `json:"asset_base_path"`
Reload *bool `json:"reload"`
ReloadInDevelopment *bool `json:"reload_in_development"`
}
SiteViewConfig controls template contract defaults.
type SiteViewRuntime ¶
SiteViewRuntime captures resolved template loading + reload behavior.
func ResolveViewRuntime ¶
func ResolveViewRuntime(viewCfg ResolvedSiteViewConfig, environment string, defaults ...fs.FS) SiteViewRuntime
ResolveViewRuntime resolves template stack + reload behavior for a given environment.
type TemplateSourceKind ¶ added in v0.36.0
type TemplateSourceKind string
const ( TemplateSourceUnknown TemplateSourceKind = "unknown" TemplateSourceHostOverlay TemplateSourceKind = "host_overlay" TemplateSourcePackagedTheme TemplateSourceKind = "packaged_theme" TemplateSourceHostBase TemplateSourceKind = "host_base" TemplateSourceBuiltIn TemplateSourceKind = "built_in" )
type TemplateSourceMeta ¶ added in v0.36.0
type TemplateSourceMeta struct {
Label string `json:"label"`
Kind TemplateSourceKind `json:"kind"`
}
Source Files
¶
- config.go
- config_normalization_runtime.go
- config_resolution_flow.go
- content_cache.go
- content_delivery_path.go
- content_loader.go
- content_template_context.go
- content_url_redirect.go
- content_url_redirect_capture.go
- context.go
- context_preview_runtime.go
- context_request_runtime.go
- context_resolution_flow.go
- context_resolution_runtime.go
- context_state_runtime.go
- delivery_alias_resolution_support.go
- delivery_capability_contract_runtime.go
- delivery_capability_support.go
- delivery_handler_runtime.go
- delivery_kind_matching_runtime.go
- delivery_locale_resolution_support.go
- delivery_preview_resolution_runtime.go
- delivery_provenance.go
- delivery_render_runtime.go
- delivery_render_support.go
- delivery_request_runtime.go
- delivery_resolution_matching_runtime.go
- delivery_resolution_runtime.go
- delivery_runtime.go
- delivery_runtime_bootstrap.go
- delivery_runtime_flow.go
- delivery_support_runtime.go
- doc.go
- error_context_clone.go
- error_runtime.go
- fallback_policy.go
- fallback_policy_config.go
- fallback_runtime_support.go
- locale_path_diagnostics.go
- locale_path_support.go
- locale_switcher_context.go
- locale_switcher_runtime.go
- module.go
- navigation_context_flow.go
- navigation_contribution_locale_runtime.go
- navigation_generated_fallback.go
- navigation_generated_fallback_support.go
- navigation_menu_resolution_flow.go
- navigation_projection_flow.go
- navigation_projection_runtime.go
- navigation_projection_support.go
- navigation_read_options_runtime.go
- navigation_request_support_runtime.go
- navigation_resolution_runtime.go
- navigation_runtime.go
- navigation_runtime_bootstrap.go
- navigation_runtime_flow.go
- preview_scope.go
- register.go
- register_entrypoint_runtime.go
- register_options_runtime.go
- register_route_support.go
- register_router_adapter.go
- register_runtime_flow.go
- render_cache_eligibility.go
- render_cache_generation.go
- render_cache_handler.go
- render_cache_key.go
- render_cache_observer.go
- render_cache_policy.go
- render_cache_renderer.go
- render_cache_response.go
- render_cache_runtime.go
- render_cache_service.go
- render_cache_tags.go
- response_runtime.go
- routing_ownership.go
- search_api_response.go
- search_handler_entrypoint_runtime.go
- search_handler_page_runtime.go
- search_handler_response_runtime.go
- search_metadata.go
- search_page_flow_runtime.go
- search_page_render_flow.go
- search_policy_validation.go
- search_query_parsing.go
- search_query_state.go
- search_request_execution_runtime.go
- search_request_translation_support.go
- search_result_envelope.go
- search_result_normalization.go
- search_result_support.go
- search_route_support.go
- search_runtime.go
- search_runtime_bootstrap.go
- search_suggest_flow_runtime.go
- search_view_projection.go
- shared_helpers.go
- template_diagnostics.go
- template_render_adapter.go
- theme_contract.go
- theme_provider.go
- view_context_runtime.go
- view_engine_options.go
- view_runtime.go