Documentation
¶
Overview ¶
Package static exports a Fletch (or plain router) app as a static site.
Every page of a Fletch app is an http.Handler, so the exporter renders the app in process, captures the responses, and writes them out with the host files a static host needs: redirects, headers, and a 404 page. Per-request CSP nonces become SHA-256 hashes, and static-safety checks (S001 to S016) catch pages that cannot work without a server.
The package does not import the root fletch module; it takes any App, which *fletch.App satisfies.
Index ¶
- Constants
- Variables
- func BasePath(ctx context.Context) string
- func Describe(ctx context.Context, opts ...PageOpt)
- func Drafts(ctx context.Context) bool
- func Exporting(ctx context.Context) bool
- func FromFS(fsys fs.FS) http.Handler
- func InvalidateOn(ctx context.Context, sub Subscriber, pre *Prerenderer) (cancel func(), err error)
- func NetlifyConfig(dir string) string
- func PagesWorkflow(outDir string) string
- func Preview(fsys fs.FS, o PreviewOptions) (http.Handler, error)
- func WranglerAssets(dir string, slash SlashPolicy) string
- func WriteNetlifyConfig(projectDir, outDir string) (file string, created bool, err error)
- func WritePagesWorkflow(projectDir, outDir string) (file string, created bool, err error)
- func WriteWranglerConfig(projectDir, name, compatDate, outDir string, slash SlashPolicy) (file string, created bool, err error)
- type App
- type Built
- type Check
- type Diagnostic
- type ExportOptions
- type File
- type FileReport
- type Header
- type HeaderRule
- type Invalidation
- type Limits
- type Option
- func Assets(dir string) Option
- func Base(path string) Option
- func CSPStrict() Option
- func Checks(checks ...Check) Option
- func Exclude(globs ...string) Option
- func NotFound(path string) Option
- func Page(path string) Option
- func Paths(route string, fn PathsFunc) Option
- func Public(dir string) Option
- func Redirect(from, to string, status int) Option
- func Search(opts ...search.Option) Option
- func TrailingSlash(p SlashPolicy) Option
- func URL(u string) Option
- type PageOpt
- type PageReport
- type Params
- type PathsFunc
- type PrerenderError
- type PrerenderOption
- func Revalidate(d time.Duration) PrerenderOption
- func Routes(globs ...string) PrerenderOption
- func SkipCookies(names ...string) PrerenderOption
- func SkipRequest(fn func(*http.Request) bool) PrerenderOption
- func Warm(m WarmMode) PrerenderOption
- func WithErrorReporter(fn func(path string, err error)) PrerenderOption
- type Prerenderer
- type PreviewOptions
- type RedirectRule
- type Report
- type Site
- type SlashPolicy
- type Subscriber
- type Target
- type Timings
- type WarmMode
Constants ¶
const ( CodeLive = "S001" // a Live route or data-f-live markup CodeCSRF = "S002" // a same-origin POST form with a CSRF field CodeSetCookie = "S003" // Set-Cookie on a response CodeStatus = "S004" // an unexpected status or a bad 404 probe CodeBrokenLink = "S005" // a broken link or a missing #fragment CodeNondeterministic = "S006" // two renders differ (--verify) CodeInlineHandler = "S007" // on*= or style= under a hash CSP CodeScriptOrigin = "S008" // a cross-origin script origin was allowlisted CodePrivateCache = "S009" // private/no-store or Vary: Cookie CodeBaseLiteral = "S010" // a root-relative URL in inline JS with Base set CodePathCollision = "S011" // two URLs on one output file CodeHostLimit = "S012" // a host limit or a host-file merge conflict CodeNonceReuse = "S013" // the nonce appears outside nonce attributes CodeHeaderLost = "S014" // the target cannot express a header CodeContentType = "S015" // Content-Type and file extension disagree CodeNotPublic = "S016" // an exported or linked page needs auth or is excluded )
Diagnostic codes. Each is documented in docs/static.md.
const ( CSPNone = "none" CSPGlobal = "global" CSPPerPath = "per-path" CSPMeta = "meta" )
CSP emission strategies, recorded in the Report.
const LastExportFile = ".fletch/static/last-export.json"
LastExportFile is where the export command keeps a copy of its Report, outside the output directory, for the dev dashboard and agents.
Variables ¶
var ErrExport = errors.New("static: export has errors")
ErrExport is wrapped by the error Export returns when an error diagnostic not named in ExportOptions.Allow was found. The Report lists them.
var TargetNames = []string{"cloudflare", "vercel", "netlify", "github-pages", "plain"}
TargetNames lists the built-in targets in the order commands show them.
Functions ¶
func BasePath ¶
BasePath returns the export's base path, such as "/repo", or "" outside an export. Code that builds URLs inside inline scripts uses it, because the base rewrite only reaches HTML attributes and CSS.
func Describe ¶
Describe records facts about the page being rendered for the sitemap and diagnostics. Outside an export it does nothing.
func Exporting ¶
Exporting reports whether ctx belongs to a request made by an export, so a handler can skip side effects such as analytics counters.
func FromFS ¶
FromFS serves an export written by the plain target (fletch export --target plain), usually embedded in the binary:
//go:embed all:dist
var dist embed.FS
site, _ := fs.Sub(dist, "dist")
mux.Handle("/", static.FromFS(site))
It reads static-manifest.json for clean URLs, redirects and header rules, answers 404 with 404.html, sends a strong ETag with 304 on a match, and serves Brotli or gzip from a .br/.gz sibling or compressed once in memory. Without a manifest it maps /x to x, x.html or x/index.html. FromFS panics if the manifest is not valid JSON, as the embedded export is fixed at build time.
func InvalidateOn ¶
func InvalidateOn(ctx context.Context, sub Subscriber, pre *Prerenderer) (cancel func(), err error)
InvalidateOn calls pre.Invalidate for every message sub delivers, so a publish on one node drops the snapshots on all of them. It runs until cancel is called or ctx is done.
func NetlifyConfig ¶
NetlifyConfig is the netlify.toml snippet for an export into dir.
func PagesWorkflow ¶
PagesWorkflow is the GitHub Actions workflow that exports the site with Go alone and deploys it to GitHub Pages.
func Preview ¶
Preview returns a handler that serves an export the way its host would: Cloudflare and Netlify run _redirects, _headers and their URL handling; Vercel runs .vercel/output/config.json (or vercel.json); GitHub Pages serves files, clean .html URLs and the redirect stubs; plain serves files. All answer misses with 404.html. It is the production behavior, not a plain file server.
func WranglerAssets ¶
func WranglerAssets(dir string, slash SlashPolicy) string
WranglerAssets is the wrangler.jsonc assets block for an export into dir.
func WriteNetlifyConfig ¶
WriteNetlifyConfig creates projectDir/netlify.toml with the publish directory. It never overwrites a file: created is false when one exists.
func WritePagesWorkflow ¶
WritePagesWorkflow creates projectDir/.github/workflows/pages.yml. It never overwrites a file: created is false when one exists.
func WriteWranglerConfig ¶
func WriteWranglerConfig(projectDir, name, compatDate, outDir string, slash SlashPolicy) (file string, created bool, err error)
WriteWranglerConfig creates projectDir/wrangler.jsonc with the assets block. It never overwrites a file: created is false when one exists.
Types ¶
type App ¶
App is what the exporter renders. *fletch.App satisfies it, and so does any type that wraps a *router.Router.
type Built ¶
type Built struct {
URL string `json:"url"`
Base string `json:"base,omitempty"`
Slash SlashPolicy `json:"-"`
Files []File `json:"files"`
Redirects []RedirectRule `json:"redirects"`
Headers []HeaderRule `json:"headers"`
// CNAME is the custom domain a GitHub Pages export writes to CNAME.
CNAME string `json:"cname,omitempty"`
// HostFiles holds public/_redirects and public/_headers, which a target
// merges with its generated rules or copies verbatim.
HostFiles map[string][]byte `json:"-"`
}
Built is a finished export, ready for a Target.
type Check ¶
type Check func(ctx context.Context, s *Built) []Diagnostic
Check is an extra check run over the finished export, such as an SEO preset. Its diagnostics are reported like the built-in ones.
type Diagnostic ¶
type Diagnostic struct {
ax.Diagnostic
// Route is the route name and pattern, such as "docs.show /docs/{slug...}".
Route string `json:"route,omitempty"`
// Path is the URL path the problem was found on.
Path string `json:"path,omitempty"`
// Allowed marks an error that --allow turned into a non-failing one.
Allowed bool `json:"allowed,omitempty"`
}
Diagnostic is an ax.Diagnostic with the route and URL path it is about.
func (Diagnostic) Failing ¶
func (d Diagnostic) Failing() bool
Failing reports whether d fails an export.
type ExportOptions ¶
type ExportOptions struct {
// Out is the output directory. Default "dist".
Out string
// Target writes the host files. Default Cloudflare().
Target Target
// URL overrides the URL option and APP_URL.
URL string
// Base overrides the Base option.
Base string
// Host exports the routes of this Host group too, and sends it as the
// request Host.
Host string
// Drafts makes Drafts(ctx) true in handlers.
Drafts bool
// NoIndex writes a Disallow robots.txt and an X-Robots-Tag header, for
// preview deploys.
NoIndex bool
// Verify renders everything twice and reports differences (S006).
Verify bool
// Allow lists codes whose errors do not fail the export.
Allow []string
// DryRun builds and checks but writes nothing.
DryRun bool
// PageTimeout bounds one render. Default 30s.
PageTimeout time.Duration
// Workers is the number of concurrent renders. Default GOMAXPROCS.
Workers int
// VercelJSON makes the vercel target write plain files and a
// vercel.json, for projects that Vercel builds from Git, instead of the
// Build Output API layout.
VercelJSON bool
// CNAME is the custom domain the github-pages target writes to CNAME.
// Default: the host of the site URL, unless it is a github.io, localhost
// or loopback address.
CNAME string
// Pagefind runs the pagefind binary, which must be on PATH, over the
// written site before it replaces the previous export. It writes its own
// index to /pagefind/, next to any static.Search index.
Pagefind bool
}
ExportOptions are the per-run settings, usually from the export command's flags. Zero values take the Site's options or the defaults.
type File ¶
type File struct {
// Path is slash-separated and relative to the output root, such as
// "docs/intro.html".
Path string `json:"path"`
// URL is the URL path the file answers, such as "/docs/intro".
URL string `json:"url"`
ContentType string `json:"content_type,omitempty"`
// Kind is "page", "file", "asset", "public", "generated" or "404".
Kind string `json:"kind"`
Route string `json:"route,omitempty"`
Data []byte `json:"-"`
}
File is one exported file.
type FileReport ¶
type FileReport struct {
Path string `json:"path"`
Kind string `json:"kind"`
Bytes int `json:"bytes"`
SHA256 string `json:"sha256"`
}
FileReport is one written file.
type HeaderRule ¶
HeaderRule sets headers on every URL that matches Path; a * matches the rest of the path.
type Invalidation ¶
type Invalidation struct {
Paths []string `json:"paths"`
}
Invalidation is the message InvalidateOn acts on.
type Limits ¶
type Limits struct {
// Headers reports whether the host sets response headers from a file.
Headers bool `json:"headers"`
// Redirects reports whether the host runs redirect rules from a file.
Redirects bool `json:"redirects"`
MaxStaticRedirects int `json:"max_static_redirects,omitempty"`
MaxDynamicRedirects int `json:"max_dynamic_redirects,omitempty"`
MaxRedirectLine int `json:"max_redirect_line,omitempty"`
MaxHeaderRules int `json:"max_header_rules,omitempty"`
MaxHeaderLine int `json:"max_header_line,omitempty"`
// RedirectPages reports whether the host gets redirects as HTML stub
// pages instead of rules.
RedirectPages bool `json:"redirect_pages,omitempty"`
// MaxTotalRules is a budget shared by every redirect and header rule.
MaxTotalRules int `json:"max_total_rules,omitempty"`
}
Limits describe what a host can express. A zero count means no limit.
type Option ¶
type Option func(*config)
Option configures a Site.
func Base ¶
Base serves the site under a path prefix, such as "/repo" for a GitHub project page. Root-relative URLs in HTML and CSS are prefixed.
func CSPStrict ¶
func CSPStrict() Option
CSPStrict makes a cross-origin script that the nonce allowed an error (S008) instead of adding its origin to script-src.
func Exclude ¶
Exclude leaves out every path that matches one of globs. A glob ending in /* matches everything below it; otherwise * stays inside one segment.
func NotFound ¶
NotFound names the path whose response becomes 404.html. By default the exporter requests a path no app serves and keeps the app's own 404 page.
func Paths ¶
Paths lists the parameter sets of a route with path parameters. route is a route name, or a pattern such as "/blog/{slug}".
func Search ¶
Search builds a full-text search index of the exported pages: the index in /_search/index.json (sharded above 1 MiB) and the browser client in /_search/client.js. Pages marked noindex are left out; opts narrow it further, such as search.Include("/docs/*"). See package search.
func TrailingSlash ¶
func TrailingSlash(p SlashPolicy) Option
TrailingSlash sets the canonical URL form and file layout. Default Never.
func URL ¶
URL sets the site's public URL, such as "https://fletch.page". It sets the Host and scheme of every rendered request, so absolute URLs, canonical tags and the sitemap come out right. --url and ExportOptions.URL override it; APP_URL is the fallback.
type PageOpt ¶
type PageOpt func(*pageMeta)
PageOpt describes the page being rendered; see Describe.
type PageReport ¶
type PageReport struct {
URL string `json:"url"`
File string `json:"file"`
Route string `json:"route,omitempty"`
Source string `json:"source"`
}
PageReport is one exported HTML page.
type Params ¶
Params is one set of path parameters for a route, keyed by parameter name. It is an alias so a plain map[string]string, such as the one a content collection builds, needs no conversion.
type PathsFunc ¶
PathsFunc lists the parameter sets of a route with path parameters. A plain func(context.Context) ([]map[string]string, error) is assignable to it.
type PrerenderError ¶
type PrerenderError struct {
Diagnostics []Diagnostic
}
PrerenderError lists the safety checks a prerender failed.
func (*PrerenderError) Error ¶
func (e *PrerenderError) Error() string
func (*PrerenderError) Unwrap ¶
func (e *PrerenderError) Unwrap() error
Unwrap makes errors.Is(err, ErrExport) true, as for a failed export.
type PrerenderOption ¶
type PrerenderOption interface {
// contains filtered or unexported methods
}
PrerenderOption configures a Prerenderer. Every Option is one too, so Paths, Page, Exclude, URL and CSPStrict work the same as for New.
func Revalidate ¶
func Revalidate(d time.Duration) PrerenderOption
Revalidate re-renders a snapshot older than d in the background while the old one is still served. Zero, the default, keeps snapshots until Invalidate or Refresh.
func Routes ¶
func Routes(globs ...string) PrerenderOption
Routes limits prerendering to the planned paths that match one of globs, such as "/pricing" or "/blog/*". Without it the whole plan is served from memory.
func SkipCookies ¶
func SkipCookies(names ...string) PrerenderOption
SkipCookies names the session cookies whose presence sends a request to the live handler, replacing the default "fletch_session" and "session".
func SkipRequest ¶
func SkipRequest(fn func(*http.Request) bool) PrerenderOption
SkipRequest sends every request for which fn returns true to the live handler.
func Warm ¶
func Warm(m WarmMode) PrerenderOption
Warm picks when the plan is rendered. Default AtBoot.
func WithErrorReporter ¶
func WithErrorReporter(fn func(path string, err error)) PrerenderOption
WithErrorReporter receives the renders that failed or could not be cached after Warm: a failed re-render (the stale snapshot is kept), or a page that looks per-user and is served live.
type Prerenderer ¶
type Prerenderer struct {
// contains filtered or unexported fields
}
Prerenderer serves pages of a dynamic app from in-memory snapshots made by the export engine: the same plan, render, CSP hash pass and safety checks.
func Prerender ¶
func Prerender(app App, opts ...PrerenderOption) *Prerenderer
Prerender returns a Prerenderer for app. Install its Middleware inside secure.New and call Warm at startup:
pre := static.Prerender(app, static.Routes("/", "/pricing", "/blog/*"))
app.Use(pre.Middleware())
app.OnStart(pre.Warm)
func (*Prerenderer) Invalidate ¶
func (p *Prerenderer) Invalidate(paths ...string)
Invalidate drops the snapshots of paths; each renders again on its next cacheable request. A path not yet planned that matches Routes, such as a new blog post, joins the plan.
func (*Prerenderer) Middleware ¶
func (p *Prerenderer) Middleware() func(http.Handler) http.Handler
Middleware serves planned paths from their snapshots. Requests that are not GET or HEAD, carry a query string, Authorization or a session cookie, and the engine's own renders go to next.
type PreviewOptions ¶
type PreviewOptions struct {
// Target is the host to emulate: "cloudflare" (default), "vercel",
// "netlify", "github-pages" or "plain".
Target string
// Base is the path prefix the site is served under.
Base string
// Slash is the export's policy; it picks Cloudflare's html_handling.
Slash SlashPolicy
}
PreviewOptions configure Preview.
type RedirectRule ¶
type RedirectRule struct {
From string `json:"from"`
To string `json:"to"`
Status int `json:"status"`
}
RedirectRule is one redirect rule. From may end in /* to match everything below it; a * at the end of To is replaced by the matched rest.
type Report ¶
type Report struct {
Target string `json:"target"`
URL string `json:"url"`
Base string `json:"base,omitempty"`
Out string `json:"out"`
DryRun bool `json:"dry_run,omitempty"`
Pages []PageReport `json:"pages"`
Files []FileReport `json:"files"`
Redirects []RedirectRule `json:"redirects"`
Headers []HeaderRule `json:"headers"`
CSP string `json:"csp"`
Diagnostics []Diagnostic `json:"diagnostics"`
Notes []string `json:"notes,omitempty"`
Timings Timings `json:"timings"`
}
Report describes one export: what was written, the rules, the CSP strategy, every diagnostic, and timings. --json prints it.
type Site ¶
type Site struct {
// contains filtered or unexported fields
}
Site is a configured exporter for one app.
type SlashPolicy ¶
type SlashPolicy int
SlashPolicy picks the canonical form of page URLs and the file layout.
const ( // Never serves /pricing from pricing.html. It is the default and serves // the same URL with no redirect on every supported host. Never SlashPolicy = iota // Always serves /pricing/ from pricing/index.html. Always )
func (SlashPolicy) String ¶
func (p SlashPolicy) String() string
String returns "never" or "always".
type Subscriber ¶
type Subscriber interface {
Subscribe(ctx context.Context, fn func(Invalidation)) (cancel func(), err error)
}
Subscriber delivers Invalidation messages. A pubsub.TypedTopic of Invalidation satisfies it, so this package needs no pubsub import:
topic := pubsub.Bind(bus, pubsub.NewTopic[static.Invalidation]("static.invalidate"))
cancel, err := static.InvalidateOn(ctx, topic, pre)
// on publish, from any node:
topic.Publish(ctx, static.Invalidation{Paths: []string{"/blog", "/blog/new-post"}})
type Target ¶
type Target interface {
Name() string
// Limits are the host's rule budgets and capabilities.
Limits() Limits
// Write writes s into out.
Write(ctx context.Context, s *Built, out *os.Root) error
}
Target writes an export for one kind of host.
func Cloudflare ¶
func Cloudflare() Target
Cloudflare returns the target for Cloudflare Workers Static Assets and Pages: _redirects, _headers and 404.html.
func GitHubPages ¶
func GitHubPages() Target
GitHubPages returns the target for GitHub Pages: .nojekyll, 404.html, a CNAME file for a custom domain, and HTML stub pages for redirects, because the host has no redirect or header rules. Page policies go into <meta>.
func Netlify ¶
func Netlify() Target
Netlify returns the target for Netlify: _redirects, _headers and 404.html. Netlify documents no rule-count limit, so S012 covers only conflicts with public/_redirects and public/_headers.
func Plain ¶
func Plain() Target
Plain returns the target for hosts with no rule files (S3, nginx, Caddy): the files, 404.html, and static-manifest.json listing redirects and headers for a custom pipeline.
func TargetByName ¶
TargetByName returns a built-in target: "cloudflare", "vercel", "netlify", "github-pages" (or "gh-pages") or "plain".
func Vercel ¶
func Vercel() Target
Vercel returns the target for Vercel. It writes the Build Output API v3 layout, .vercel/output/static and .vercel/output/config.json, which `vercel deploy --prebuilt` uploads without framework detection. Set ExportOptions.VercelJSON to write plain files and a vercel.json instead, for projects that Vercel builds from Git.
type Timings ¶
type Timings struct {
PlanMS float64 `json:"plan_ms"`
RenderMS float64 `json:"render_ms"`
WriteMS float64 `json:"write_ms"`
TotalMS float64 `json:"total_ms"`
}
Timings are in milliseconds.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
content
module
|
|
|
highlight
module
|
|
|
deploy
|
|
|
cloudflare
Package cloudflare uploads an exported static site to Cloudflare Workers Static Assets with the direct-upload API, using only the standard library.
|
Package cloudflare uploads an exported static site to Cloudflare Workers Static Assets with the direct-upload API, using only the standard library. |
|
netlify
Package netlify uploads an exported static site to Netlify with the file-digest Deploy API, using only the standard library.
|
Package netlify uploads an exported static site to Netlify with the file-digest Deploy API, using only the standard library. |
|
Package feed renders RSS 2.0, Atom 1.0 and JSON Feed 1.1 documents and serves them as http handlers.
|
Package feed renders RSS 2.0, Atom 1.0 and JSON Feed 1.1 documents and serves them as http handlers. |
|
og
module
|
|
|
Package search builds a static full-text search index from exported HTML pages and ships a small client script that queries it in the browser.
|
Package search builds a static full-text search index from exported HTML pages and ships a small client script that queries it in the browser. |
|
Package seo checks the search-engine and social metadata of an export.
|
Package seo checks the search-engine and social metadata of an export. |
|
Package statictest exports an app inside a test and asserts on the result: files, headers and redirects as the host's preview serves them, and diagnostics.
|
Package statictest exports an app inside a test and asserts on the result: files, headers and redirects as the host's preview serves them, and diagnostics. |