Documentation
¶
Overview ¶
Package core is the application orchestrator: it owns one instance of every subsystem — the template engine, the render engine, the cache, the dependency tracker, the router, the plugin registry, and observability — and exposes them through a single App with a server lifecycle.
This package must never import pkg/collage. The dependency points the other way: pkg/collage converts its public Config into this package's Config and calls New, then aliases App so users call these methods directly. Config below is the internal mirror of pkg/collage.Config and the two must be kept field-aligned.
Index ¶
- Constants
- Variables
- type App
- func (a *App) ActionURL(name, locale string, params map[string]string) (string, error)
- func (a *App) Actions() []*types.Action
- func (a *App) BaseURL() string
- func (a *App) BuildFinished(ctx context.Context, ev *plugin.BuildFinishedEvent) error
- func (a *App) BuildID() string
- func (a *App) CSRFMarker() string
- func (a *App) CaptureResponses(ctx context.Context, paths []string) (map[string]types.CapturedResponse, error)
- func (a *App) Check() []types.Finding
- func (a *App) Commands() []plugin.Command
- func (a *App) DefaultLocale() string
- func (a *App) DevMode() bool
- func (a *App) Documents() []*types.Document
- func (a *App) FragmentURL(page, fragment, locale string, params map[string]string) (string, error)
- func (a *App) Handle(prefix string, handler http.Handler, opts ...HandleOption) error
- func (a *App) Handler() http.Handler
- func (a *App) HasBuildFinishedHook() bool
- func (a *App) Inspect() Inspection
- func (a *App) InvalidateTags(ctx context.Context, tags ...string) error
- func (a *App) InvalidateTagsN(ctx context.Context, tags ...string) (int, error)
- func (a *App) ListenAndServe() error
- func (a *App) Locales() (string, []string)
- func (a *App) Logger() *slog.Logger
- func (a *App) Mount(prefix string, fsys fs.FS, opts ...asset.Option) error
- func (a *App) Mounts() []*asset.Mount
- func (a *App) OpenMounted(urlPath string) (fs.File, error)
- func (a *App) OriginFor(ctx context.Context, host string) string
- func (a *App) Page(name string) (*types.Page, bool)
- func (a *App) PageRouted(name string) bool
- func (a *App) PageURLs(ctx context.Context, name string) (urls []plugin.PageURL, err error)
- func (a *App) Pages() []*types.Page
- func (a *App) PluginRedirects() ([]plugin.BuiltRedirect, error)
- func (a *App) PrefixDefault() bool
- func (a *App) PurgeTags(ctx context.Context, tags ...string) error
- func (a *App) Register(items ...types.Registrable) error
- func (a *App) RegisterAction(action *types.Action) error
- func (a *App) RegisterCommand(cmd plugin.Command) error
- func (a *App) RegisterDocument(doc *types.Document) error
- func (a *App) RegisterErrorPage(p *types.Page) error
- func (a *App) RegisterNotFoundPage(p *types.Page) error
- func (a *App) RegisterPage(p *types.Page) error
- func (a *App) RegisterPlugin(p plugin.Plugin) error
- func (a *App) RenderDocumentPath(ctx context.Context, path, locale string, params map[string]string) (*render.DocumentResult, error)
- func (a *App) RenderFragment(r *http.Request, req plugin.FragmentRequest) (*plugin.FragmentRender, error)
- func (a *App) RenderNotFound(ctx context.Context, locale string) (*render.Result, error)
- func (a *App) RenderPath(ctx context.Context, path, locale string, params map[string]string) (*render.Result, error)
- func (a *App) ServeStatus(w http.ResponseWriter, r *http.Request, status int)
- func (a *App) Shutdown(ctx context.Context) error
- func (a *App) Start() error
- func (a *App) URL(name, locale string, params map[string]string) (string, error)
- func (a *App) Use(middleware func(http.Handler) http.Handler) error
- type CacheConfig
- type Config
- type HandleOption
- type InspectedAction
- type InspectedDocument
- type InspectedField
- type InspectedFragment
- type InspectedFragmentPath
- type InspectedMethod
- type InspectedMount
- type InspectedPage
- type InspectedPlugin
- type InspectedType
- type Inspection
- type LocaleConfig
- type ObservabilityConfig
- type SecurityConfig
- type ServerConfig
- type TemplateConfig
Constants ¶
const ( // RuleUnknownRoute is a link to a page, document, action or fragment path // that is not registered. RuleUnknownRoute = "unknown-route" // RuleRouteParams is a link whose parameters do not fill its route's pattern. RuleRouteParams = "route-params" // RuleUnreachableLocale is a link into a locale no URL can carry. RuleUnreachableLocale = "unreachable-locale" // RuleNoPathInLocale is a link into a locale the route has no path in. RuleNoPathInLocale = "no-path-in-locale" )
The rules Check reports under.
const InspectionVersion = 1
InspectionVersion is the version of the Inspection format. It changes when a field is removed or its meaning changes; a field may be added without it.
Variables ¶
var ErrAppStarted = errors.New("collage: application already started")
ErrAppStarted is returned by every registration method once the application has started — once Handler has built the HTTP handler, which is also what ListenAndServe does first. Registration is a startup-time activity: plugin Init has already run and already seen the registered pages, so a page, plugin, or error page added afterwards would be invisible to every plugin that asked.
RegisterCommand is deliberately exempt: plugins register their commands from inside Init, which by definition runs after the application has started.
var ErrCSRFDisabled = errors.New("collage: csrfToken used but request-forgery protection is disabled")
ErrCSRFDisabled reports a template asking for a forgery token in an application that turned the protection off.
var ErrConfigurerRegisteredLate = errors.New("collage: plugin needs Configure and must be supplied in Config.Plugins")
ErrConfigurerRegisteredLate is returned by RegisterPlugin for a plugin implementing plugin.Configurer. Configure runs inside New, before templates are parsed, and RegisterPlugin is called afterwards — so such a plugin belongs in Config.Plugins. Skipping its Configure silently would leave a plugin that registered a template function wondering why no template can call it.
var ErrDocumentNotFound = errors.New("collage: no document at path")
ErrDocumentNotFound is returned by RenderDocumentPath when path resolves to no document — either nothing matched, what matched is a page rather than a document, or what matched is a redirect. All three mean the same thing to the caller: there is no document to render at that path. It mirrors ErrPageNotFound for the same reason RenderDocumentPath mirrors RenderPath.
var ErrDuplicateAction = errors.New("collage: duplicate action")
ErrDuplicateAction reports two actions registered under one name.
var ErrDuplicateCommand = errors.New("collage: duplicate command name")
ErrDuplicateCommand is returned by RegisterCommand when a command with the same Name is already registered.
var ErrDuplicateDocument = errors.New("collage: duplicate document name")
ErrDuplicateDocument is returned when a document is registered under a name another document already holds. It is deliberately its own sentinel rather than ErrDuplicatePage: pages and documents are named in separate registries, reached through Page/Pages and Documents respectively, so a page and a document may share a name without conflict — only two documents colliding on Name is an error.
var ErrDuplicatePage = errors.New("collage: duplicate page name")
ErrDuplicatePage is returned when a page is registered under a name another page already holds.
var ErrEmptyActionName = errors.New("collage: action has no name")
ErrEmptyActionName reports an action with no name. Every registration error names what failed, and an unnamed action leaves nothing to name.
var ErrEmptyCommandName = errors.New("collage: empty command name")
ErrEmptyCommandName is returned by RegisterCommand when the command's Name is empty.
var ErrEmptyTemplateRoot = errors.New("collage: empty template root")
ErrEmptyTemplateRoot is returned by New when Config.Template.Root is empty.
var ErrInvalidCacheType = errors.New("collage: invalid cache type")
ErrInvalidCacheType is returned by New when Config.Cache.Enabled is true, Config.Cache.Store is nil, and Config.Cache.Type names an implementation this package cannot build. pkg/collage exports it as ErrInvalidCacheType.
var ErrInvalidCommandName = errors.New("collage: invalid command name")
ErrInvalidCommandName is returned by RegisterCommand for a name no command line can carry as one argument: whitespace or a control character in it, a leading "-" that flag parsing takes, a shell metacharacter.
var ErrLocaleUnreachable = types.ErrLocaleUnreachable
ErrLocaleUnreachable is returned by URL for a locale no URL can reach: one the application does not support, or any locale but the default when path locales are off. Registering a path in one fails with it too.
var ErrMountConflict = errors.New("collage: mount prefixes overlap")
ErrMountConflict reports that two mounts claim overlapping prefixes: one prefix begins with the other, so a request under the shorter prefix could be claimed by either mount depending on registration order.
var ErrMountShadowsRoute = errors.New("collage: mount shadows a route")
ErrMountShadowsRoute reports that a mount prefix would swallow a URL path the router already answers to — a page path, a document path, or a redirect source — making that route unreachable. It is reported by buildHandler, not by Mount, so it fires whichever of the mount and the route was registered first — see checkMountsDoNotShadow.
var ErrNilAction = errors.New("collage: nil action")
ErrNilAction reports a nil action passed to RegisterAction.
var ErrNilFragmentPath = errors.New("collage: fragment path has no fragment")
ErrNilFragmentPath reports a fragment path declared with no fragment to render.
var ErrNilHandler = errors.New("collage: nil handler")
ErrNilHandler reports a Handle or Use call given nothing to run.
var ErrNilPage = errors.New("collage: nil page")
ErrNilPage is returned by the page registration methods when passed a nil page.
var ErrNilRegistrable = errors.New("collage: nil passed to Register")
ErrNilRegistrable reports a nil passed to Register, where a page, a document or an action was expected.
var ErrNoActionHandler = types.ErrNoActionHandler
ErrNoActionHandler reports an action with nothing to run.
var ErrNoActionPaths = errors.New("collage: action has no paths")
ErrNoActionPaths reports an action with no path to reach it by.
var ErrNoMountForAsset = errors.New("collage: no mount serves that asset")
ErrNoMountForAsset reports that a template asked for an asset URL under a prefix no mount claims.
var ErrNoRequest = errors.New("collage: no request to render for")
ErrNoRequest is returned by RenderFragment when it is given no request to render for.
var ErrPageNotFound = errors.New("collage: no page at path")
ErrPageNotFound is returned by RenderPath when the path resolves to no page — either nothing matched, or what matched is a redirect rather than a page. Both mean the same thing to the caller: there is nothing at that path to render.
var ErrTemplateNotFound = template.ErrTemplateNotFound
ErrTemplateNotFound is returned by the page registration methods when one of a page's fragments names a template the engine has not loaded. It is deliberately the same sentinel the template engine reports at render time, not a second one for the same condition: "this template does not exist" is one failure mode, and registering it here only moves the moment it is detected from the first request back to startup, which is the point.
var ErrUnregisteredErrorPage = errors.New("collage: error page not registered")
ErrUnregisteredErrorPage is returned when the application starts and a registered page references a NotFoundPage or ErrorPage that was never registered itself. See App.checkErrorPagesRegistered for why that has to be a startup failure.
Functions ¶
This section is empty.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App owns every subsystem and the server lifecycle. It is the type users hold: pkg/collage aliases it, so the methods here are the framework's public surface.
An App is safe for concurrent use. Registration is expected at startup, from one goroutine, but the Host methods a plugin may call at any time — Pages, Page, InvalidateTags, Logger, RegisterCommand — are all safe to call while requests are being served.
func New ¶
New builds an App from a validated configuration. cfg is expected to have been defaulted and validated already — pkg/collage.New does both before converting — so New applies only the fallbacks it needs to construct working subsystems: an empty Template.Extension becomes ".html" and an empty Locale.Default becomes "en". It returns ErrEmptyTemplateRoot for an empty Template.Root, ErrInvalidCacheType for an enabled cache of an unknown type, and a wrapped template error when the template root cannot be loaded.
Everything is constructed here, once: New never starts a goroutine and never touches the network, so building an App is safe in a test.
func (*App) ActionURL ¶ added in v0.36.0
ActionURL returns the path of the action registered as name, in locale, with params filling its pattern — what a form's action attribute holds:
app.ActionURL("logout", "tr", nil) // "/tr/cikis"
app.ActionURL("vote", "", map[string]string{"id": "42"}) // "/stories/42/vote"
It is URL's twin for actions, kept apart because an action is often named after the page its form is on — a "login" page and a "login" action — and one namespace would make that name ambiguous. A page's own action is under the name it was registered with: "story:POST" when WithAction gave it none. It is as strict as URL: an unknown name is ErrUnknownRoute, a locale the action has no path in is ErrNoPathInLocale, and params that do not fill the pattern exactly are ErrRouteParams.
Templates reach it through {{actionURL}}.
func (*App) Actions ¶
Actions returns every registered action in registration order, as a copy of the slice. The actions themselves are the application's own, not copies, and must not be modified.
func (*App) BaseURL ¶ added in v0.39.0
BaseURL returns the site's public origin without a trailing slash, or "" when the application set none. It is the one place a plugin building an absolute URL — a sitemap, a feed, a canonical link — should read it from, rather than taking its own copy.
func (*App) BuildFinished ¶ added in v0.21.0
BuildFinished hands a finished static build to the plugins that check one; see plugin.BuildFinishedHook. The builder calls it once every file is written.
func (*App) BuildID ¶ added in v0.24.0
BuildID names the build of the program serving: Config.Cache.Version when set, otherwise a fingerprint of the executable — the value the disk cache is namespaced by — and, when neither can be had, the moment the process started, which is at least never the same for two builds. A plugin versioning something a browser keeps — a service worker's caches, an asset's query string — reads it through Host.BuildID.
func (*App) CSRFMarker ¶
CSRFMarker is the placeholder a rendered page carries where a request-forgery token goes, or the empty string when this application has no forgery protection.
It is exported for the static builder, which refuses to write a page containing it: a built site has no server to replace it with a reader's own token, and none to submit the form to either.
func (*App) CaptureResponses ¶ added in v0.52.0
func (a *App) CaptureResponses(ctx context.Context, paths []string) (map[string]types.CapturedResponse, error)
CaptureResponses asks the application's handler for each path twice, in process, as a static export would be asked for it — GET, no cookies, no Accept-Encoding, the host of Config.BaseURL or "localhost", over HTTPS when Config.BaseURL's scheme is https — and keeps the headers both responses agree on, as they were when the status was written. A header the two responses disagree on, or that only one of them carries, is named in Unstable instead.
Each request's context is marked with types.WithCapture: it renders outside any reader's shared render, nothing is written to the response cache for it, and a plugin can tell it from a reader's. Each is bounded by captureTimeout, and a path not answered within it is recorded with an Err wrapping types.ErrCaptureTimeout; a handler that ignores its context is left running past that deadline, on a goroutine of its own, until it returns. After captureMaxTimeouts such paths in a row the rest are not asked for, and the error wraps types.ErrCaptureStopped and names how many were left. The bodies are discarded.
It starts the application, as Handler does, and returns the error startup produced rather than capturing a 503 for every path. It returns ctx's error when ctx ends, with what it captured so far. The paths are asked for one at a time.
func (*App) Check ¶ added in v0.40.0
Check reports what is wrong with the application that can be told without rendering it, as findings: a template linking by name — {{pageURL "post"}}, {{actionURL "logout"}}, {{fragmentURL "home" "clock"}} — to something not registered, into a locale no URL reaches or the route has no path in, or with parameters its pattern does not take. Each of those is an error when the template renders, on the one page that reaches it; Check finds them all at once, in every template, before anything renders.
It reads only what is written as a string literal. A name given by a field or a variable is not known until the template renders, and is not checked; a parameter value never is, since it only fills a pattern. A link with no locale of its own is checked the way it renders: it is fine when the route can be built in any locale, as a render falls back to the default one.
A started application is checked as it will serve; Check before Start sees what has been registered so far.
func (*App) Commands ¶
Commands returns the CLI subcommands plugins contributed, in registration order, as a copy: appending to or reordering the returned slice does not affect the application.
func (*App) DefaultLocale ¶
DefaultLocale returns the locale served without a path prefix. A static build reads it to decide which locale occupies the bare output path and which get a directory of their own; see internal/build.
func (*App) DevMode ¶
DevMode reports whether the application is running in development mode, as Config.DevMode said at New.
func (*App) Documents ¶
Documents returns every registered document, in registration order, as a copy of the slice: appending to or reordering the returned slice does not affect the application.
Unlike Pages, the documents themselves are handed back by the same pointer they were registered with rather than defensively copied. Pages defends against a plugin writing through Page's mutable maps and slices because Pages is part of plugin.Host; Documents is not — nothing outside this package reaches it except the static builder, which only reads it — and types.Document carries no framework-owned state analogous to a page's bound layout for a copy to protect.
The returned documents must not be modified: they are the application's own.
func (*App) FragmentURL ¶ added in v0.18.0
FragmentURL returns the path page opened for its fragment named fragment with WithFragmentPath, in locale, with params filling its pattern — the URL a script fetches to refresh that part of the page:
app.FragmentURL("home", "cpu-usage", "en", nil) // "/live/cpu"
app.FragmentURL("post", "comments", "en", map[string]string{"slug": "hello"}) // "/posts/hello/comments"
It is URL's twin and as strict: an unknown page is ErrUnknownRoute, a fragment the page never opened is ErrUnknownFragmentPath, a locale it opened the fragment in no path for is ErrNoPathInLocale, one fragment opened at two paths in the locale is ErrAmbiguousFragmentPath, and params that do not fill the pattern are ErrRouteParams. The link is built by name so a renamed path cannot leave a page fetching the old one.
Templates reach it through {{fragmentURL}} and {{fragmentURLIn}}.
func (*App) Handle ¶
Handle mounts an http.Handler of the application's own under prefix: an API written with any router, a gRPC gateway, a webhook receiver. A prefix ending in "/" claims every path beneath it; one without is a single exact path — "/metrics", "/webhooks/stripe".
Collage passes the request on unchanged — the handler sees the full path, so wrap it in http.StripPrefix if it expects otherwise — and does nothing to it: no forgery check, no body limit, no cache. What it does is what it does before any request is routed: the plugins' request hooks, the span, the metrics, the panic guard, the clean-path redirect (and the 404 for an encoded slash in a path that needed cleaning), the baseline security headers, and draining it on shutdown. An encoded slash in an otherwise clean path reaches the handler: its r.URL.Path holds the decoded "/", as it would under net/http alone.
No middleware runs for it — neither what Use added nor any plugin's, a session, a rate limit, a basicauth, a compressor. The handler is the application's, and so is what wraps it: an API that wants its own auth or its own rate limit wraps itself in them, and is not handed the site's session cookie, consent banner or HTML toolbar on the way. Which requests those are is decided on the path as it is once the pre-routing checks have passed it, by the same match routing uses, so a request it lets past the middleware is one only this handler answers. WithMiddleware puts one mount inside the chain, as a page is; a middleware that rewrites a request's path into prefix reaches the handler only then. A plugin's Host.Handle always runs inside the chain.
A prefix that overlaps a page, a document, an action, a redirect or a mount is reported when the handler is built, whichever was registered first. It returns ErrAppStarted once the server has started.
func (*App) Handler ¶
Handler returns the application's http.Handler, building it — and running every registered plugin's Init — on the first call and memoising it thereafter. It is usable without a server, which is what makes an App testable through httptest.NewServer or a bare ServeHTTP call.
The first call closes registration: RegisterPage, RegisterNotFoundPage, RegisterErrorPage, and RegisterPlugin all return ErrAppStarted afterwards, because plugin Init has by then already seen the pages that were registered.
Handler has no error return because http.Handler is what its callers need. When the build fails — a plugin's Init failing, or a page referencing an unregistered error page — the failure is logged once, at error level, and Handler returns a memoised handler that answers every request with 503. ListenAndServe surfaces the same failure as a returned error instead, so a program that starts a server never loses it.
func (*App) HasBuildFinishedHook ¶ added in v0.52.0
HasBuildFinishedHook reports whether a registered plugin checks a finished static build. Without one the build skips its header capture, which only such a plugin reads.
func (*App) Inspect ¶ added in v0.27.0
func (a *App) Inspect() Inspection
Inspect describes the application as registered. Call it after registration; it starts nothing and serves nothing. Plugins' pages and documents are included once the application has started, since plugins register them in Init.
func (*App) InvalidateTags ¶
InvalidateTags invalidates every cache entry associated with any of tags. It is InvalidateTagsN with the count discarded, and is the form plugin.Host requires.
func (*App) InvalidateTagsN ¶
InvalidateTagsN invalidates every cache entry associated with any of tags and returns how many were invalidated.
When the store keeps entries past invalidation (cache.StaleCache, which every built-in store does) pages are marked stale rather than removed: they are not served as fresh, and a good render replaces them, but one that fails is answered with the stale copy. Any other store drops them, as described below. PurgeTags removes pages outright.
The dependency tracker is the authority: it resolves tags to the cache keys built from them, each key is dropped from the cache, plugins are told through OnCacheInvalidate, the keys are forgotten so they cannot resolve again, and the count is reported to Metrics.Invalidation. An empty tags invalidates nothing and is not an error. collage.Cached values are not removed but marked stale: they are served until a fetch replaces them, so an upstream that is down costs freshness, not pages. PurgeTags removes them.
When the store also implements cache.TaggedCache, its Invalidate is called with the tags as well. That is not redundant with the tracker walk, and it is the only thing that makes a shared store invalidatable at all. The tracker is per process and in memory: it knows the keys this instance wrote and nothing else, so with a store shared between instances — a Redis, say — instance A's tracker cannot name the keys instance B wrote, and a restart leaves every key written before it permanently unreachable by tag. A store that indexes tags itself, which is exactly what TaggedCache declares, can resolve them for the keys the tracker never saw. SetTagged already hands it those tags on every write; this is the call that finally reads them back.
A store that is a cache.SharedCache goes further: the per-key walk and the tag-level call are replaced by one DropTags, which marks stale (or, for PurgeTags, removes) every page and collage.Cached value under the tags on the store, and advances each tag's generation so a render or fetch any instance had under way as it ran is not stored as fresh. It returns the pages it reached, with what each was written with, so the keys every instance wrote — not only this one's — are counted, named in the plugin event (a CDN purge covers a page only another instance served) and warmed here, as far as Cache.WarmLimit goes. The tracker's keys and the store's are merged, each key once.
The count is the number of keys the tracker resolved from tags and the cache accepted an invalidation for — not a count of entries that were live at the time, and not a count of what the store's own tag index dropped, since TaggedCache.Invalidate reports no count and inventing one would make the number mean different things for different caches. Cache.InvalidateKey is documented to succeed on a key that holds no entry, and reports no distinction either way, so a key whose entry had already expired is counted like any other. The count is therefore exactly what the tag reached according to the authority on that question, and an upper bound on live entries removed. With a SharedCache the store's index is that authority too, and it keeps an invalidated page under its tags until it is re-rendered or expires, so a second invalidation before then counts it again. A DropTags that fails dropped nothing, and counts nothing.
A key that the cache fails to drop is not counted and does not stop the rest: every other key is still invalidated and the failures are joined into the returned error, because a partial invalidation that reports success is how stale pages survive a deploy.
func (*App) ListenAndServe ¶
ListenAndServe builds the handler, starts an HTTP server on Config.Server's host and port, and blocks until the server stops. It sets all five of ServerConfig's timeouts — ReadTimeout, ReadHeaderTimeout (ReadTimeout when unset, so a slow-header client cannot hold a connection open indefinitely), WriteTimeout, IdleTimeout, and ShutdownTimeout, the last as the deadline for the graceful shutdown below.
It traps SIGINT and SIGTERM and shuts down gracefully on either, and returns nil on a clean shutdown rather than http.ErrServerClosed: a server that stopped because it was asked to stop did not fail. A failure to bind the port, or a plugin Init that failed, is returned as an error.
Once the port is bound it calls OnServe on every ServeHook plugin, with a ctx the drain cancels.
On the first signal it drains: DrainHook plugins are told, keep-alives are turned off, and the server goes on serving for ServerConfig.DrainDelay. A second signal ends that wait at once. Only then does ShutdownTimeout start, so the drain does not eat into the time in-flight requests get.
The goroutine that serves sends to a buffered channel and exits as soon as the server stops; the one that waits for a second signal exits when this call returns. Neither can outlive it.
func (*App) Locales ¶ added in v0.21.0
Locales returns the default locale and every supported one, the default included, in the order they were configured.
func (*App) Mount ¶
Mount serves fsys under prefix, alongside the application's pages and documents. prefix must begin and end with "/" and must not be "/" alone, or asset.New's ErrInvalidPrefix is returned; a nil fsys returns asset.ErrNilFS.
It returns ErrAppStarted after the server has started, exactly like RegisterPage and RegisterDocument. A prefix that would shadow a registered page path, document path, or redirect source is not rejected here: that check runs in buildHandler, once registration is closed, so it catches the conflict whichever of the mount and the route was registered first. See checkMountsDoNotShadow. In development every mount is given asset.WithDevMode, which stops it remembering a file's content hash: a name derived once from a file somebody is editing keeps pointing at what that file used to be, and the page goes on linking it. See asset.WithDevMode.
func (*App) Mounts ¶
Mounts returns every mounted asset file system, in registration order, as a copy of the slice: appending to or reordering the returned slice does not affect the application. The static builder is what consumes it.
func (*App) OpenMounted ¶ added in v0.68.0
OpenMounted opens the file the URL path urlPath is served from, through the mount whose prefix it is under — what a request for it would be answered with, read without a request. No mount, or no such file, is fs.ErrNotExist.
func (*App) OriginFor ¶ added in v0.42.0
OriginFor returns the public origin URLs for host are absolute against: the first OriginResolver plugin's that knows host, else Config.BaseURL — "" when that is unset too. host is matched lower-cased and without a port; an IPv6 literal without its brackets, with a port or without one.
func (*App) Page ¶
Page returns the page registered under name, as a defensive copy on the same terms as Pages, and whether one was found.
func (*App) PageRouted ¶ added in v0.52.0
PageRouted reports whether the page registered under name is a route — was registered with RegisterPage — rather than only the not-found or error page, which the router reaches by failing to match and whose paths and redirects it never serves.
func (*App) PageURLs ¶ added in v0.21.0
PageURLs returns every URL the page registered as name answers: one per locale for a fixed path, one per locale and parameter set for a pattern whose WithStaticParams lists them. A pattern without WithStaticParams answers URLs nobody can enumerate, and contributes none. It is what a sitemap is made of, and it builds each URL as App.URL does, prefix and trailing slash included.
func (*App) Pages ¶
Pages returns every registered page, in registration order, each a defensive copy as plugin.Host requires. See copyPage for exactly what is copied and what stays shared.
func (*App) PluginRedirects ¶ added in v0.52.0
func (a *App) PluginRedirects() ([]plugin.BuiltRedirect, error)
PluginRedirects returns every RedirectSource plugin's redirects, for the static build.
func (*App) PrefixDefault ¶ added in v0.14.0
PrefixDefault reports whether the default locale's pages carry its prefix, as every other locale's do: "/en/about" rather than "/about".
func (*App) PurgeTags ¶ added in v0.62.0
PurgeTags removes every cache entry associated with any of tags: pages outright, never kept to be served stale, and collage.Cached values outright, on disk too, rather than keeping them to serve stale. The pages count and the errors are InvalidateTagsN's.
A page that InvalidateTags already marked stale is reached through the store's own tag index (cache.TaggedCache), since the tracker has forgotten it. A custom cache.StaleCache that is not also a TaggedCache therefore cannot have such pages purged by tag; every built-in store can, and so does every cache.SharedCache, whose DropTags purges what any instance wrote.
func (*App) Register ¶ added in v0.40.0
func (a *App) Register(items ...types.Registrable) error
Register registers each of items in order — a page through RegisterPage, a document through RegisterDocument, an action through RegisterAction — and stops at the first one refused, returning its error wrapped with its kind and name:
if err := app.Register(
pages.Home(),
pages.About(),
documents.Health(),
actions.Logout(),
); err != nil {
return err // "register page "about": collage: duplicate page ..."
}
It is the loop a project's routes.go would otherwise write once per kind. Each item goes through exactly the checks its own Register method makes; what was registered before a refusal stays registered, as it does for those methods, so a refusal is a startup failure to abort on.
The not-found and error pages are not among them: they are reached by failing to match rather than by a path, and RegisterNotFoundPage and RegisterErrorPage say which is which.
func (*App) RegisterAction ¶
RegisterAction validates action and adds it to the router.
An action may share a path with a page — that is what an HTML form needs, since a form's action is the page it sits on — but not a method with another action.
func (*App) RegisterCommand ¶
RegisterCommand registers cmd as a CLI subcommand, rejecting an empty name (ErrEmptyCommandName), a name that is not one shell word (ErrInvalidCommandName), a "collage-" name — DispatchCommands answers "collage-check" and "collage-inspect" itself, and the prefix is kept for its own — and a name another command already holds (both ErrDuplicateCommand).
It is closed by ErrAppStarted like the other registration methods, but later: plugins contribute their commands from inside Init, which runs as part of starting the application, and the application is started only once every Init has returned. A command registered after that would never be dispatched: DispatchCommands has started the application before it looks.
func (*App) RegisterDocument ¶
RegisterDocument validates doc and adds it to the router. It returns ErrAppStarted after the server has started, ErrNilDocument for a nil document, ErrDuplicateDocument for a repeated name, ErrDuplicateRoute when a path collides with a page or another document, and the document's own validation error otherwise — always naming the document.
It mirrors RegisterPage's prepare exactly, minus the layout binding and the template-existence check: a document has no template and no layout, so types.Document.Validate alone is enough to catch every registration-time mistake.
func (*App) RegisterErrorPage ¶
RegisterErrorPage registers p as the page served when rendering fails. p goes through exactly the same validation, binding, and template checks as RegisterPage; like the not-found page it is not given routes of its own.
func (*App) RegisterNotFoundPage ¶
RegisterNotFoundPage registers p as the page served when a request resolves to no content. p goes through exactly the same validation, binding, and template checks as RegisterPage; it is not given routes of its own, since it is reached by failing to match rather than by matching.
func (*App) RegisterPage ¶
RegisterPage validates p, binds its content fragment into its layout, checks that every template it names exists, and registers its paths and redirects with the router.
This is where the framework's "no silent failures" invariant is enforced. A page that would fail at render time fails here instead, at startup, with an error naming the page and the specific problem:
- a page that does not pass types.Page.Validate — an empty name, no content fragment, a path that does not start with "/", an incoherent strategy and TTL combination, a required slot with nothing bound to it, a fragment cycle;
- a fragment naming a template the engine has not loaded (ErrTemplateNotFound), which turns a typo in a template path from a first-request 500 into a startup error;
- a fragment bound into a slot its template never calls (ErrUnknownSlot), a fill that could never render — usually a typo on one side of the binding;
- a name another page already holds (ErrDuplicatePage);
- registration after the application has started (ErrAppStarted).
The templates of the page's own NotFoundPage and ErrorPage are checked here too. Those pages are reached straight off the Page's fields, whether or not they were ever registered in their own right, and a typo in a 500 page's template would otherwise surface only once the site is already failing — the worst possible moment to discover it. Only their templates are checked: they get no routes of their own here, and their own error pages are not recursed into.
The order of those checks is deliberate. Binding happens before Validate because a layout that declares its content slot Required — which is the idiomatic way to write one — does not validate until the content fragment is actually in it.
A rejected registration is not rolled back: a page whose paths were accepted for one locale and refused for another leaves the accepted routes in the router. A failed RegisterPage is a startup failure the embedding program is expected to abort on, not something to recover from and carry on serving with.
func (*App) RegisterPlugin ¶
RegisterPlugin registers p with the application's plugin registry. Plugins must be registered before the application starts, since Init runs once, at startup, in registration order; afterwards this returns ErrAppStarted.
func (*App) RenderDocumentPath ¶
func (a *App) RenderDocumentPath(ctx context.Context, path, locale string, params map[string]string) (*render.DocumentResult, error)
RenderDocumentPath renders the document registered at path, outside the HTTP request path and bypassing the cache entirely, and returns the raw execution result. It is RenderPath's sibling for documents, and follows the same rules:
The document is resolved through the router, from a synthetic GET request for path, so a path reaches exactly the document it would reach over HTTP. A non-empty locale is a *request* for that locale, offered to the router the same way RenderPath offers one — see syntheticRequest.
The locale the document actually executes for is whatever the router resolved, not the argument: match.Locale, never locale. RenderPath was corrected on exactly this point — a caller-supplied locale that disagrees with the matched route must not execute one document's handler while telling it a different locale — and RenderDocumentPath follows the same rule for the same reason.
params overlay the path parameters the router captured, exactly as in RenderPath.
It returns ErrDocumentNotFound when path resolves to no document, including when it resolves to a page or a redirect, and the handler's own error when execution fails.
func (*App) RenderFragment ¶ added in v0.18.0
func (a *App) RenderFragment(r *http.Request, req plugin.FragmentRequest) (*plugin.FragmentRender, error)
RenderFragment renders one fragment a page opened at its own URL with WithFragmentPath, for r, and returns it in parts: the markup, what it hoisted, the tags it depended on, and whether one render can serve every reader.
It is the render a request to the fragment's path gets, without the response: a plugin pushing fragments over an event stream or a WebSocket calls it for each fragment an invalidation touched, and sends the parts in a message of its own. Only a fragment the page opened is rendered — the same set of fragments HTTP reaches — so a stream cannot be used to read a part of a page nobody published. Values read through collage.Cached are fresh: the render waits for the upstream rather than be built from a stale value, and fails when it is down.
Equivalent to that request, not merely like it, because r is usually not one for the fragment at all: it is the stream's, which the stream's own path let through. So the render is made for a GET to the fragment's URL, carrying r's host, client address, headers and cookies, and nothing else of r's — not its path values, its body, its method or its context's values (see fragmentContext) — and that request goes through what a request to the URL goes through:
- the application's and every plugin's middleware, in ServeHTTP's order, for the fragment's path. One that answers instead of passing the request on — a basicauth's 401, a rate limit's 429, a redirect to a login page — refuses the reader: ErrGuardRefused, naming the status, and what it wrote goes nowhere. What it puts in the context, the guard and the render read. The headers and cookies it sets are dropped: the caller's response is its own.
- the route's parameters, on the request as r.PathValue, for the guards.
- the page's and the fragment's guards.
- the reader's forgery token, then every PersonaliseHook, on the markup and on each item it hoisted. A render a hook made personal is not Shared.
The request hooks are not run, nor the span and metrics: no request reached the server.
A Shared render is kept, after this reader's chain and guards have passed, and handed to the next reader they pass: see fragmentMemo. The token and the hooks run on each reader's copy.
It starts the application if nothing has yet, as Handler does, and refuses to render while a start is running — from a plugin's Init, say — since the middleware chain does not exist until it has finished.
Plugins reach it through Host.RenderFragment.
func (*App) RenderNotFound ¶
RenderNotFound renders the registered not-found page for locale, or reports that there is none with a nil result and a nil error.
A not-found page is reached by failing to match, so it has no path and RenderPath cannot reach it. A static build needs it anyway: a static host answers an unknown URL with the site's own 404.html, and a site exported without one answers with whatever the host's default is.
The page's render strategy is deliberately not consulted. Whether a page is worth caching and whether it belongs in a static export are different questions, and a not-found page declared Dynamic — which is the usual declaration, since it is never worth caching — would otherwise have no 404.html at all.
func (*App) RenderPath ¶
func (a *App) RenderPath(ctx context.Context, path, locale string, params map[string]string) (*render.Result, error)
RenderPath renders the page registered at path, outside the HTTP request path and bypassing the cache entirely, and returns the raw render result. It is the seam the static site builder consumes through its own narrow interface.
The page is resolved through the router, from a synthetic GET request for path, so a path reaches exactly the page it would reach over HTTP. A non-empty locale is a *request* for that locale: a path carrying no locale prefix is given the locale's own prefix, which is the URL that reaches it over HTTP.
The locale the page actually renders for is whatever the router resolved, not the argument, and the two are the same thing whenever the argument had any effect. It matters when they differ: "/tr/blog" resolves to the tr page whatever the caller asked for, and rendering it with a RenderContext.Locale of "en" would put every locale-dependent fragment on that page into the wrong language. The router picked the page; the page's locale is the router's to report.
params overlay the path parameters the router captured, so a caller that already knows the concrete values (a static build enumerating slugs) does not depend on the pattern re-capturing them.
It returns ErrPageNotFound when path resolves to no page, including when it resolves to a redirect, and the render engine's own error when the render fails.
func (*App) ServeStatus ¶ added in v0.24.0
ServeStatus answers r with status and the page the application shows for it: its not-found page for 404 and 410, its error page otherwise. Plugins reach it through Host.ServeStatus. Before the handler is built it writes the status text alone.
func (*App) Shutdown ¶
Shutdown drains, then stops the running server, then waits for the data cache's background refreshes and disk writes, then stops the plugin registry, joining whatever errors any produced. The drain cancels the ServeHook ctx, tells DrainHook plugins, turns keep-alives off and, with a server serving, a ServerConfig.DrainDelay and not in development mode, keeps serving for DrainDelay. ctx bounds the drain's wait and the server's wait for in-flight requests and the data cache's wait together; ListenAndServe's own signal handler drains first and then bounds the rest with ServerConfig.ShutdownTimeout.
It is idempotent: the work runs exactly once and every caller — including one racing another — observes the same result. Calling it before ListenAndServe has started a server shuts the plugins down and prevents a later ListenAndServe from serving, and a later Start fail without initialising any plugin. Calling it while Start is still running plugins' Init waits for Start to finish, then shuts every plugin down once.
func (*App) Start ¶
Start builds the application's HTTP handler and runs every registered plugin's Init, returning the error that startup produced — a plugin's Init failing, or a page referencing an unregistered error page — or nil.
It is what Handler and ListenAndServe each do first, memoised the same way: calling it more than once, or calling it and then either of them, runs the work exactly once and every caller sees the same outcome. Like them it closes registration, so RegisterPage, RegisterNotFoundPage, RegisterErrorPage, and RegisterPlugin return ErrAppStarted afterwards.
It exists because plugins register their CLI commands from inside Init, so Commands is empty until Init has run — and Handler, which has to return an http.Handler, cannot hand back the reason it did not. A program that wants to dispatch a plugin command, or simply wants startup failures before it does anything else, calls this.
func (*App) URL ¶ added in v0.6.0
URL returns the path of the page or document registered as name, in locale, with params filling its pattern — the URL a reader follows to reach it, locale prefix included:
app.URL("about", "tr", nil) // "/tr/hakkinda"
app.URL("blog-post", "en", map[string]string{"slug": "hello"}) // "/blog/hello"
An empty locale is the default one. It is strict: a name nothing was registered under is ErrUnknownRoute, a locale the route has no path in is ErrNoPathInLocale, and params that do not fill the pattern exactly are ErrRouteParams — a link that cannot be built is a failure, not a guess.
Templates reach it through {{pageURL}}, {{pageURLIn}} and {{localeURL}}; the URL of a page's fragment path is FragmentURL.
func (*App) Use ¶
Use adds middleware around the handling of every request, in the standard net/http shape. The first registered is the outermost, and a plugin's middleware counts as registered where the plugin was: the plugins in Config.Plugins are outside everything Use adds, so middleware here reads what they put in the request's context — a session, a flash message — and a plugin registered with RegisterPlugin is inside the middleware added before it.
It runs before routing, so it sees every request — pages, documents, actions, mounts, a plugin's handlers and a handler mounted WithMiddleware — but one for a handler the application mounted with Handle alone, which is answered without the chain: that handler brings its own middleware. It runs inside the framework's span, metrics and panic guard, which a wrapper around app.Handler() does not. A middleware may answer the request itself, or pass on a request of its own; whatever it puts in that request's context is what data handlers read from rc.Context().
A static build renders without a request, so no middleware runs for its renders. It then asks for each file's path through the handler to record its response headers (see CaptureResponses), and middleware runs for those requests: a header it sets is one the built file is deployed with.
type CacheConfig ¶
type CacheConfig struct {
// Enabled turns caching on. A disabled cache is a nil cache: every request
// renders and nothing is ever stored. It is the master switch, so a Store set
// alongside Enabled false is not used.
Enabled bool
// Store is a caller-supplied cache implementation. When non-nil it is used as
// it stands and Type is ignored.
Store cache.Cache
// Type selects a built-in cache implementation when Store is nil. Only
// "memory" is built in.
Type string
// DefaultTTL is the cache entry lifetime used when a page sets none.
DefaultTTL time.Duration
// MaxEntries caps the number of cache entries.
MaxEntries int
// MaxBytes caps the total size of a built-in cache's content. Zero means the
// cache type's own default; negative, unlimited.
MaxBytes int64
// WarmLimit caps how many keys one invalidation warms. Zero means 1000;
// negative turns warming off. See pkg/collage.CacheConfig.WarmLimit.
WarmLimit int
// Dir is where a "disk" cache stores its entries.
Dir string
// Version identifies the build whose output a "disk" cache holds. Entries live
// under a subdirectory named for it, so a new build reads a fresh cache rather
// than the previous binary's HTML.
Version string
}
CacheConfig is internal/core's mirror of pkg/collage.CacheConfig.
type Config ¶
type Config struct {
// DevMode enables development-mode behaviour across the framework; see
// App.DevMode.
DevMode bool
// DevWatch lists directories whose changes reload a development page.
DevWatch []string
// BaseURL is the site's public origin, without a trailing slash, for the
// absolute URLs a render cannot otherwise know. Empty when the application set
// none. It is reported to plugins through Host.BaseURL. The public Config
// validates and normalises it before it arrives here.
BaseURL string
// Security configures request-forgery protection.
Security SecurityConfig
// Logger is the structured logger the framework writes through and hands to
// plugins via Host.Logger. A nil Logger means the framework picks one: a
// terminal-friendly handler when the output is a terminal and nothing has
// replaced slog's own default, and slog.Default() otherwise. See
// defaultLogger.
Logger *slog.Logger
// Server configures the HTTP server.
Server ServerConfig
// Template configures template loading and rendering.
Template TemplateConfig
// Plugins are registered and configured while the App is built.
//
// A plugin implementing plugin.Configurer must arrive here rather than through
// RegisterPlugin: Configure runs before templates are parsed, and RegisterPlugin
// is called after New has already parsed them. RegisterPlugin refuses such a
// plugin by name rather than silently skipping its Configure.
Plugins []plugin.Plugin
// PluginConfig is each plugin's own configuration, keyed by plugin name.
//
// The framework does not read a file: the application loads this however it
// likes — JSON, YAML, environment — so no format is imposed on it. A key
// matching no registered plugin is a startup error, because the alternative is
// an operator certain a plugin was configured while it ran on defaults.
PluginConfig map[string]json.RawMessage
// Cache configures the render output cache.
Cache CacheConfig
// Locale configures locale resolution.
Locale LocaleConfig
// TrailingSlash makes a page's URL end in "/"; see pkg/collage.Config.
TrailingSlash bool
// Observability configures metrics and tracing.
Observability ObservabilityConfig
}
Config is internal/core's mirror of pkg/collage.Config. The two structs are kept field-aligned on purpose: pkg/collage owns the defaults and the validation, then converts its Config into this one and calls New, so that internal/core never imports pkg/collage. A field added to one must be added to the other.
New expects an already-defaulted, already-validated Config — the state pkg/collage.New hands it. It applies only the few fallbacks it needs to build a working App at all (see New), and does not re-run pkg/collage's defaulting.
type HandleOption ¶ added in v0.67.0
type HandleOption func(*httpx.HandlerMount)
HandleOption configures a handler mounted with Handle. See WithMiddleware.
It is a function over the mount rather than a struct of fields so that the set can grow without an application's call changing shape, as asset.Option does for Mount; what it sets is not the application's to read back.
func WithMiddleware ¶ added in v0.67.0
func WithMiddleware() HandleOption
WithMiddleware runs the mounted handler inside the middleware chain — what Use added and every plugin's — as a page is, in the same order. Use it for a handler that relies on the site's middleware: a basicauth or rate limit registered to guard it, the session it reads, a middleware rewriting requests into its prefix.
type InspectedAction ¶ added in v0.27.0
type InspectedAction struct {
Name string `json:"name"`
Paths map[string]string `json:"paths"`
Methods []string `json:"methods"`
// Guarded reports a guard of the action's own, set with WithGuard; the
// guards of a page it is on are the page's.
Guarded bool `json:"guarded,omitempty"`
}
InspectedAction is one registered action a page or the application declared.
type InspectedDocument ¶ added in v0.27.0
type InspectedDocument struct {
Name string `json:"name"`
Paths map[string]string `json:"paths"`
Params []string `json:"params,omitempty"`
ContentType string `json:"contentType"`
}
InspectedDocument is one registered document.
type InspectedField ¶ added in v0.49.0
type InspectedField struct {
Name string `json:"name"`
Type string `json:"type"`
Embedded bool `json:"embedded,omitempty"`
}
InspectedField is one exported field, promoted ones included. An embedded field is listed too, as a template reaches it by its type's name ({{.Base}}), and marked Embedded.
type InspectedFragment ¶ added in v0.27.0
type InspectedFragment struct {
Name string `json:"name"`
Template string `json:"template"`
// Slots are the slots it declares or has fragments bound into.
Slots []string `json:"slots,omitempty"`
Handler bool `json:"handler,omitempty"`
Static bool `json:"static,omitempty"`
// Inline reports a template given as text with NewInlineFragment; Template
// is then empty.
Inline bool `json:"inline,omitempty"`
// DataType is the Go type the template sees as dot: "blog.Post", "nil"
// when the fragment has no data, null when the type is unknown.
DataType *string `json:"dataType"`
// TypeCheck is false when the fragment was built WithoutTypeCheck.
TypeCheck *bool `json:"typeCheck,omitempty"`
}
InspectedFragment is one fragment some registered page renders.
type InspectedFragmentPath ¶ added in v0.27.0
type InspectedFragmentPath struct {
Fragment string `json:"fragment"`
Locale string `json:"locale"`
Pattern string `json:"pattern"`
Params []string `json:"params,omitempty"`
}
InspectedFragmentPath is one fragment a page opened at a URL of its own.
type InspectedMethod ¶ added in v0.49.0
type InspectedMethod struct {
Name string `json:"name"`
Args int `json:"args"`
Returns string `json:"returns"`
}
InspectedMethod is one exported method a template can call.
type InspectedMount ¶ added in v0.27.0
type InspectedMount struct {
Prefix string `json:"prefix"`
// Files are the URL paths it serves — "/static/app.css" — up to
// maxInspectedFiles, sorted; Truncated says there were more.
Files []string `json:"files"`
Truncated bool `json:"truncated,omitempty"`
}
InspectedMount is one mounted file system and the URLs of its files.
type InspectedPage ¶ added in v0.27.0
type InspectedPage struct {
Name string `json:"name"`
// Paths are its patterns by locale, as registered.
Paths map[string]string `json:"paths"`
// Params are the placeholders its patterns name, in order of appearance.
Params []string `json:"params,omitempty"`
Strategy string `json:"strategy"`
// Layouts are the page's layout chain, outermost first, by fragment name.
Layouts []string `json:"layouts,omitempty"`
// Guards are the spine fragments carrying a guard, in the order they are
// asked: the chain outermost first, then the content fragment.
Guards []string `json:"guards,omitempty"`
Content string `json:"content,omitempty"`
FragmentPaths []InspectedFragmentPath `json:"fragmentPaths,omitempty"`
}
InspectedPage is one registered page.
type InspectedPlugin ¶ added in v0.27.0
InspectedPlugin is one registered plugin.
type InspectedType ¶ added in v0.49.0
type InspectedType struct {
Kind string `json:"kind"`
Key string `json:"key,omitempty"`
Elem string `json:"elem,omitempty"`
Fields []InspectedField `json:"fields,omitempty"`
Methods []InspectedMethod `json:"methods,omitempty"`
// Ambiguous marks a name two distinct types share; it carries no more.
Ambiguous bool `json:"ambiguous,omitempty"`
}
InspectedType is the shape of a type a fragment's template can reach, for an editor completing {{.}}: its exported fields and the exported methods of it and its pointer. A named pointer, slice, array, map or chan also names what it holds: Elem, and Key for a map.
Two packages of one name (a/models, b/models) both name a type "models.User": the entry is then Ambiguous, with only its Kind (empty if they differ), and a consumer treats it as unknown.
type Inspection ¶ added in v0.27.0
type Inspection struct {
Version int `json:"version"`
TemplateRoot string `json:"templateRoot"`
TemplateExtension string `json:"templateExtension"`
DefaultLocale string `json:"defaultLocale"`
Locales []string `json:"locales"`
Pages []InspectedPage `json:"pages"`
Fragments []InspectedFragment `json:"fragments"`
Documents []InspectedDocument `json:"documents"`
Actions []InspectedAction `json:"actions"`
TemplateFuncs []string `json:"templateFuncs"`
Plugins []InspectedPlugin `json:"plugins"`
Mounts []InspectedMount `json:"mounts"`
// Types describes the named types the fragments' data reaches, by Go name.
Types map[string]InspectedType `json:"types,omitempty"`
}
Inspection is what an application is made of, as a tool outside it — an editor's completion, a linter — needs to know it: every page, fragment, document and action by name, the slots each template fills, the template functions, the plugins and the files the mounts serve. It is plain data, encodable as JSON; `go run . collage-inspect` prints it.
type LocaleConfig ¶
type LocaleConfig struct {
// Default is the locale of a URL with no locale prefix.
Default string
// Supported lists the locales the application serves.
Supported []string
// PrefixDefault gives Default's pages a prefix; see pkg/collage.LocaleConfig.
PrefixDefault bool
}
LocaleConfig is internal/core's mirror of pkg/collage.LocaleConfig.
type ObservabilityConfig ¶
type ObservabilityConfig struct {
// Metrics receives framework counters and timings. nil means no-op.
Metrics observability.Metrics
// Tracer starts spans around framework operations. nil means no-op.
Tracer observability.Tracer
}
ObservabilityConfig is internal/core's mirror of pkg/collage.ObservabilityConfig.
type SecurityConfig ¶
type SecurityConfig struct {
// CSRFKey signs forgery tokens. It should be at least 32 random bytes, kept
// with the application's other secrets, and the same on every instance.
//
// An empty key is not an error: one is generated and the application logs that
// it did. That is the right default for a first run and the wrong thing to
// deploy, because a generated key is different in every process — so a token
// issued before a restart is refused after it, and a token issued by one
// instance is refused by the next.
CSRFKey []byte
// CSRFCookieName overrides the cookie a token is carried in.
CSRFCookieName string
// CSRFFieldName overrides the form field a token is submitted in, both in
// what {{csrfToken}} renders and in what the verifier reads.
CSRFFieldName string
// CSRFHeaderName overrides the header a token may be submitted in.
CSRFHeaderName string
// CSRFTrustedOrigins are other origins whose forms may post to this
// application, each "scheme://host[:port]". A request the browser marks as
// coming from any other origin is refused even with a valid token.
CSRFTrustedOrigins []string
// DisableCSRF turns forgery checking off for the whole application.
//
// It is for an application that has no browser-submitted forms at all — a pure
// API behind its own authentication. On anything a browser posts to, it gives
// the protection away, which is why it is a field rather than the absence of a
// key.
DisableCSRF bool
// CSRFTokenTTL is how long a forgery token stays valid after it is issued.
// Zero selects the default (csrf.DefaultMaxAge); a negative value disables
// expiry, keeping a token valid for as long as its signature verifies.
CSRFTokenTTL time.Duration
// FrameOptions is the X-Frame-Options header value sent on every response.
// Empty means the default "SAMEORIGIN"; "-" sends none; anything else is sent
// verbatim. See baselineHeaders.
FrameOptions string
// DisableNoSniff stops X-Content-Type-Options: nosniff, which is otherwise sent
// on every response. See baselineHeaders.
DisableNoSniff bool
}
SecurityConfig configures the framework's request-forgery protection.
type ServerConfig ¶
type ServerConfig struct {
// Host is the address the server listens on.
Host string
// Port is the TCP port the server listens on.
Port int
// ReadTimeout bounds how long reading a request may take.
ReadTimeout time.Duration
// ReadHeaderTimeout bounds how long reading a request's headers may take.
// Zero falls back to ReadTimeout.
ReadHeaderTimeout time.Duration
// WriteTimeout bounds how long writing a response may take.
WriteTimeout time.Duration
// IdleTimeout bounds how long a keep-alive connection may sit idle.
IdleTimeout time.Duration
// MaxBodyBytes bounds an action's request body when the action declares no
// bound of its own. Zero selects the framework's default of four megabytes;
// negative means unbounded, which is a decision worth making deliberately,
// because an unbounded body is memory an anonymous caller chooses the size of.
MaxBodyBytes int64
// ShutdownTimeout bounds how long graceful shutdown waits for in-flight
// requests.
ShutdownTimeout time.Duration
// DrainDelay is how long the server keeps serving after a shutdown starts,
// so a load balancer can see readiness fail and stop sending traffic before
// the port closes. Plugins implementing DrainHook are told when it starts.
// It comes before ShutdownTimeout, which then bounds the in-flight requests,
// so a stop can take DrainDelay + ShutdownTimeout. Zero, the default, does
// not wait. It is ignored in development mode.
DrainDelay time.Duration
// TrustedProxies are the proxies whose X-Forwarded-For collage.ClientIP
// believes, parsed from pkg/collage's strings. Empty trusts none. The
// forgery guard believes X-Forwarded-Proto only from them when it is set.
TrustedProxies []netip.Prefix
}
ServerConfig is internal/core's mirror of pkg/collage.ServerConfig.
type TemplateConfig ¶
type TemplateConfig struct {
// FS, when non-nil, is the filesystem templates are loaded from, and Root names
// a directory within it rather than on disk.
FS fs.FS
// Root is the directory templates are loaded from: a path on disk when FS is
// nil, otherwise a path within FS, where empty means the root of FS.
Root string
// Extension is the file extension that identifies template files under Root.
Extension string
// Timeout is the default data handler timeout used when a fragment sets none.
// It is also the only bound on a document handler, which has no per-route
// Timeout field of its own. See pkg/collage.TemplateConfig.Timeout.
Timeout time.Duration
// Funcs is merged over the template engine's built-in function map at
// construction, so an entry under a built-in name replaces that built-in.
Funcs htmltemplate.FuncMap
}
TemplateConfig is internal/core's mirror of pkg/collage.TemplateConfig.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
inspecttest
|
|
|
a/models
Package models is a test fixture: it shares its name, and a type name, with its sibling under b, to collide in the inspect type table.
|
Package models is a test fixture: it shares its name, and a type name, with its sibling under b, to collide in the inspect type table. |
|
b/models
Package models is a test fixture: see ../../a/models.
|
Package models is a test fixture: see ../../a/models. |