Extending102 min read
Using plugins
What a plugin can do, how to register and configure one, and the forty-six published plugins, grouped by what they are for.
A plugin is an ordinary Go value that you construct and hand to your application. It can watch what the application does and change some of what it produces, but it cannot reach into the router, the cache or the template set: it gets a narrow set of capabilities and nothing more.
There is no plugin loader and no registry to publish to. A plugin is a Go module you import, and it is compiled into your binary like any other dependency.
What a plugin can do
Everything a plugin does goes through a hook it opts into or a capability it is handed at startup. Between them, a plugin can:
- rewrite what was rendered — the HTML of a page, the body of a sitemap or a JSON document — before it is served and cached. A minifier works this way.
- contribute to the page before it renders, by hoisting into the head: a structured-data block, a meta tag, a preload hint.
- add template functions, which every template can then call.
- transform every mounted filesystem, so the files a mount serves are, for instance, already minified.
- register pages, documents and mounts of its own. An image optimiser serves the resized images it links to from its own mount.
- serve a handler of its own — an event stream, a WebSocket — and render a page's fragment paths to push over it.
- hear about invalidations — the tags whose cached pages were just invalidated, to purge a CDN's copies or push a fresh fragment.
- observe failures, with the stage of the pipeline they happened in.
- wrap every request with middleware of its own. A plugin in
Config.Pluginsis outside everythingapp.Useadds, in list order, so your middleware reads what it put in the request's context; one registered withRegisterPluginis inside the middleware added before it. A handler the application mounts with plainapp.Handleis the exception: no plugin's middleware runs for it. See Middleware and your own API. - check the output and report findings — shown over the page in development, listed in a static build's report, failing the build at error level.
- add commands that your program runs —
go run . <command>in a scaffolded project; see The collage CLI.
Here is where those hooks sit on the way a page request travels, and the two that fire outside a request:
What each of these looks like from the plugin's side is in Writing a plugin. Writing one that collage plugin add can install is on the repository contract.
Registering a plugin
Add a plugin with one command, from the project's directory:
collage plugin add elagoht/minimizer
elagoht/minimizer means github.com/Elagoht/collage-minimizer. The command fetches the module, adds the import and the constructor call to plugins.go, in the place the plugin asks for, and adds an empty section "elagoht/minimizer": {} to plugins-config.json: the defaults. It adds first any plugin this one needs. Then it prints what the plugin still needs from you: its setup note, the template functions it adds and the address of its documentation — with several plugins, together at the end, under "What each plugin needs from you".
A failure leaves every file as it was. Taking one out is the same in reverse, and the settings its section held are printed so they are not lost:
collage plugin del elagoht/minimizer
Several go in one command, each on its own: one that fails is put back, and the others stay. A bundle, written with @, is a set of them under one name, and collage new takes the same with --with:
collage plugin add elagoht/session elagoht/flash elagoht/validate
collage plugin add @prod
collage new mysite --with @blog,@prod
The bundles (@prod, @site, @blog, @forms, @live, @ops) and what each holds are in the CLI reference.
A project made by collage new has plugins.go already, and main.go passes it to the application:
func plugins() []collage.Plugin {
return []collage.Plugin{
minimizer.New(minimizer.Options{}),
}
}
app, err := collage.New(&collage.Config{
Template: collage.TemplateConfig{Root: "templates"},
Plugins: plugins(),
})
The file is yours to edit: reorder it, or give a plugin its options in Go (sitemap.New(sitemap.Options{...})); add and del only insert and remove whole entries. An older project gets the file from its first add, and the command prints the Plugins: plugins(), line to put in main.go.
A plugin by anyone else is added the same way, by its module path: collage plugin add gitlab.com/you/stamp. What a repository must hold to be added is on the plugin authors' page, and the command is in the CLI reference.
Wiring one by hand
The command writes nothing you cannot write yourself, and that stays the way to do it for a project that builds its plugin list some other way. A plugin is a separate module. Add it, construct it, and put it in Config.Plugins:
go get github.com/Elagoht/collage-minimizer
import minimizer "github.com/Elagoht/collage-minimizer"
app, err := collage.New(&collage.Config{
Template: collage.TemplateConfig{Root: "templates"},
Plugins: []collage.Plugin{minimizer.New(minimizer.Options{})},
})
Add its section to plugins-config.json yourself, if it takes settings.
There is a second way, app.RegisterPlugin, called after New:
if err := app.RegisterPlugin(jsonld.New(jsonld.Options{})); err != nil {
log.Fatal(err)
}
Prefer Config.Plugins. Some plugins have to act while the application is being built — to add a template function, or to wrap the mounted filesystems — and New is where that happens. Such a plugin implements an optional Configure phase, and RegisterPlugin refuses it by name with collage.ErrConfigurerRegisteredLate rather than accepting it and silently skipping the part that mattered.
Config.Plugins works for every plugin, so it is the one to reach for.
RegisterPlugin also refuses:
| Error | When |
|---|---|
ErrAppStarted | The application has already started — Handler, ListenAndServe, Start, DispatchCommands or a render ran. That includes any start that failed, in a plugin's Init or for any other reason. |
ErrDuplicatePlugin | Another plugin already has the same name. |
A nil plugin, or one whose Name() is empty, is refused too, with an error that says so; neither has a sentinel of its own. A plugin in Config.Plugins is checked the same way, and New returns the error.
Order matters
Plugins run in the order they were registered: Config.Plugins in slice order, then any RegisterPlugin calls in call order. For hooks that change output, each plugin sees what the one before it produced. A plugin that adds to the page should usually come before one that compacts it, so the addition is compacted too.
Four published plugins say where they go: elagoht/compress before any plugin that rewrites response bodies, elagoht/health before any plugin that can refuse or answer a request, elagoht/jobs after the plugins its work uses, and elagoht/devtoolbar last.
The plugins that guard the door have an order of their own. Middleware wraps a request in the order the plugins are listed, the first outermost, so a site using them lists elagoht/accesslog (it only observes, and listed first it logs every refusal in full), then elagoht/health, then elagoht/fail2ban, then elagoht/ratelimit, then elagoht/basicauth, so a refused password guess is counted before its bcrypt check is paid for. collage plugin add does not reorder them.
Configuring plugins
A plugin that takes settings reads them from Config.PluginConfig, a map[string]json.RawMessage keyed by the plugin's name. Names read like module paths — elagoht/minimizer — so the key and the plugin are one identifier.
The common case is a JSON file next to your program. A project scaffolded by collage new has an empty plugins-config.json and already loads it, with env.PluginConfig(files): the file in the working directory when there is one, otherwise the copy the binary embeds, so a binary deployed without the file keeps its settings. Outside a scaffolded project, LoadPluginConfig reads the file alone:
{
"elagoht/minimizer": { "js": true },
"elagoht/jsonld": { "siteName": "The Wire" }
}
pluginConfig, err := collage.LoadPluginConfig("plugins-config.json")
if err != nil {
log.Fatal(err)
}
app, err := collage.New(&collage.Config{
Template: collage.TemplateConfig{Root: "templates"},
Plugins: []collage.Plugin{minimizer.New(minimizer.Options{}), jsonld.New(jsonld.Options{})},
PluginConfig: pluginConfig,
})
LoadPluginConfig returns a nil map, and no error, when the file does not exist: a deployment that configures nothing should not need an empty file to say so. A file that exists but cannot be read or is not a JSON object is an error.
Nothing about this is tied to JSON files. LoadPluginConfig is a convenience the framework itself never calls; you can fill PluginConfig from YAML, the environment, or Go constants:
PluginConfig: map[string]json.RawMessage{
"elagoht/minimizer": json.RawMessage(`{"js": true}`),
},
Five rules hold whichever way you fill it:
- No section means defaults. A plugin with no entry runs exactly as its constructor set it up.
- A section is decoded over the defaults.
{"js": true}turns one setting on and leaves the rest as they were. A list in the section replaces the default list whole, rather than being merged into it element by element, and a map adds its entries to the default's. How a particular plugin merges is in its README. - A key the plugin does not know stops the application from starting:
collage: elagoht/robots: unknown key "dissallow" in plugins-config.json. A misspelt key, or one a plugin has renamed, would otherwise be ignored and the option left at its default. Keys still match case-insensitively. Remove the key the error names, or rename it to the one the plugin's README documents. - A duration is a string,
"10s"or"1h30m", astime.ParseDurationreads it. A bare number is refused with an error naming its key —"banTime": write a duration as a string such as "10s", not 3600— where it would otherwise have been read as nanoseconds. - A key that names no registered plugin stops the application from starting, with
collage.ErrUnknownPluginConfig. A typo like"elagoht/minimzer"would otherwise leave the plugin on its defaults and you certain it was configured. The check runs when the application starts rather than inNew, becauseRegisterPlugincan still add plugins afterNew.
A section that is present but does not decode — a string where the plugin expects a boolean — is also an error, raised when the plugin reads it, and the message names the key whose value failed.
The published plugins
Forty-six plugins are published alongside the framework, grouped below by what they are for. Each is its own module, with its own README that is the full reference; what follows is enough to set one up.
| Group | Plugins |
|---|---|
| SEO and discovery | jsonld, meta, ogimage, sitemap, robots, feed, redirects, indexnow |
| Content | markdown, highlight, toc, search, i18n |
| Forms and state | validate, honeypot, flash, session, uploads |
| Security | secure, ratelimit, basicauth, oauth, fail2ban, consent |
| Live updates | live, websocket, client |
| Assets and delivery | minimizer, opti-image, bundle, favicon, compress, cdnpurge, offline, deploy |
| Operations and development | htmlcheck, devtoolbar, accesslog, prometheus, otel, analytics, tenant, errortrack, health, jobs, gesso |
Libraries that are not plugins are listed after the groups.
Most sites start from what they are, not from a group. Three common starting points, each plugin linked to its section below:
| You are building | Start with | What they do for it |
|---|---|---|
| A blog | markdown, highlight, toc, feed, sitemap, robots, meta, jsonld, ogimage, search | Posts written in Markdown with highlighted code and a table of contents, a feed for readers, what search engines and link previews read, and search on a statically built site. @blog adds toc, feed, ogimage and the search-engine ones in one command; add markdown, highlight and search yourself. |
| A product catalogue | jsonld, meta, sitemap, opti-image, i18n, cdnpurge, compress, minimizer | Product structured data, resized product images served from the plugin's own mount, translations per locale, and a CDN's copies purged when a product's tags are invalidated. |
| A multi-user web app with roles | session, oauth, validate, flash, honeypot, uploads, secure, ratelimit, fail2ban, live | Sign-in through an identity provider, the signed-in user kept in a session, forms checked and answered, uploads checked by their content, abuse limited or banned, and parts of a page kept current. The roles are yours: a middleware added with app.Use reads the session the plugin put in the request's context, as Plugins' middleware and yours shows. |
@prod adds what any of them wants in production; the bundles are in the CLI reference.
SEO and discovery
What a search engine, a feed reader or a link preview reads: structured data, the tags a page is shared by, the sitemap and robots.txt, feeds, old addresses and where they went, and telling search engines what changed.
elagoht/jsonld
github.com/Elagoht/collage-jsonld emits schema.org structured data into the document head.
import "github.com/Elagoht/collage-jsonld"
Plugins: []collage.Plugin{jsonld.New(jsonld.Options{})},
{
"elagoht/jsonld": {
"siteName": "The Wire",
"searchURL": "https://thewire.example/search?q={query}"
}
}
Registering it emits a site-wide WebSite node on every page — once siteName is set, with the application's origin (collage.BaseURL) as its url — and nothing else, because the plugin cannot know what a page is about. The page says so from the data handler that fetched the article:
func loadArticle(ctx context.Context, rc *collage.RenderContext) (*Article, []string, error) {
article, err := client.Article(ctx, rc.Param("slug"))
if err != nil {
return nil, nil, err
}
jsonld.Emit(rc, jsonld.Article{
Headline: article.Title,
DatePublished: article.PublishedAt,
AuthorName: article.Author,
})
return article, []string{"article:" + article.Slug}, nil
}
- It has no
Configurephase, soRegisterPluginaccepts it too. v0.3.0 removedsiteURL: set the application'sBaseURLinstead. Emitappends and works whether or not the plugin is registered. Nodes are keyed by schema.org type and theirKeyfield, so a nested fragment'sArticlereplaces one declared further out, and nodes of different types all appear.- Several nodes of one type need a
Keyeach (v0.4.0), never written to the page:jsonld.Emit(rc, jsonld.Person{Key: p.Slug, Name: p.Name})in a loop keeps every person. Without aKey, a laterPersonreplaces the earlier one.IDis separate: it is written as"@id", so set it only to a real IRI. - Typed nodes cover every feature in Google Search's structured data gallery (v0.6.0): pages (
WebSite,WebPageand its kinds,ProfilePage,BreadcrumbList,ItemList), writing (Article,NewsArticle,BlogPosting,Blog,DiscussionForumPosting,QAPage,FAQPage), people and organizations (Person,Organization,LocalBusiness,EmployerAggregateRating),Event, commerce (Productwith shipping and returns,SoftwareApplication,VacationRental,Review,AggregateRating), media (VideoObject,ImageObject,Movie,Recipe,HowTo) and learning and data (Course,Quiz,MathSolver,Dataset,JobPosting). Shared parts —Agent,Offer,Money,Rating,PostalAddress,GeoCoordinates— mean the same in every node.jsonld.Rawis the escape hatch for anything else, and refuses invalid JSON. - An
Event's location is aPlace, anOnlineURL, or both for a mixed event. Its times are written with their own offset: read a wall-clock time withtime.ParseInLocationin the event's zone, nottime.Parse, which means UTC. - A node that cannot be marshalled is skipped rather than failing the page, with a warning in the log naming its type.
It needs {{hoist "head"}} in your layout — see below.
elagoht/meta
github.com/Elagoht/collage-meta writes the tags a page is shared and indexed by into its head: Open Graph, Twitter cards, the canonical URL, the meta description and the page's translations.
import "github.com/Elagoht/collage-meta"
BaseURL: "https://example.com",
Plugins: []collage.Plugin{meta.New(meta.Options{
SiteName: "The blog",
DefaultImage: "/static/share.png",
})},
meta.Set(rc, meta.Page{
Title: article.Title,
Description: article.Dek,
Image: article.Cover,
Type: meta.Article,
Published: article.PublishedAt,
})
{
"elagoht/meta": {
"siteName": "The blog",
"defaultImage": "/static/share.png",
"twitterSite": "@example",
"locales": { "en": "en_US", "tr": "tr_TR" },
"noAlternates": false
}
}
- The canonical and
og:URLs follow the site's origin:Config.BaseURLor, per host, what anOriginResolverplugin such as elagoht/tenant gives. With neither, the application does not start. v0.3.0 removed the plugin's ownbaseURL. - Registering it gives every page
og:site_name,og:type, the canonical URL — built by name, so a query string a reader arrived with is never part of it —og:locale, anhreflanglink for every locale the page has a path in, and the default image and Twitter card. - What a page is about it says from its data handler with
meta.Set. Each tag is hoisted under its own key, so a page's declaration replaces the default tag by tag, and a deeper fragment's replaces its parent's. - The
<title>is not among them: it isrc.HoistTitleorWithTitle, as without the plugin. It needs{{hoist "head"}}in the layout.
elagoht/ogimage
github.com/Elagoht/collage-ogimage draws each page's share card — the 1200×630 image a link is shown with — from an HTML template, in pure Go, and serves it at a URL made from its content.
import "github.com/Elagoht/collage-ogimage"
Plugins: []collage.Plugin{
meta.New(meta.Options{SiteName: "The blog"}),
ogimage.New(ogimage.Options{
Templates: templatesFS,
Root: "templates",
Default: "og/default.html",
Dir: ".cache/ogimage",
}),
},
<!-- templates/og/post.html -->
<div style="display:flex; flex-direction:column; justify-content:space-between;
width:1200px; height:630px; padding:72px; background:#0f172a; color:#fff">
<span style="font-size:28px">{{.Site.Name}}</span>
<h1 data-fit style="font-size:72px">{{.Title}}</h1>
<span style="font-size:28px">{{.Label}}</span>
</div>
if err := ogimage.Set(rc, "og/post.html", ogimage.Card{Title: post.Title, Label: post.Category}); err != nil {
return view{}, nil, err
}
- It needs the application's
Config.BaseURL; a card's URL follows the request's origin on a site served on several hosts, soConfig.BaseURLis not required when anOriginResolverplugin is registered. Register it after elagoht/meta, and leave meta'sDefaultImageunset. - v0.3.0 has one constructor,
ogimage.New(ogimage.Options{…}).renderTimeoutis a duration string ("5s"), a negativemaxEntriesormaxBytesis an error rather than unlimited, and the build finding isogimage-draw. - v0.4.0 takes the two strings of
ogimage.Drawas one value:ogimage.Draw(ctx, opts, ogimage.Input{HTML: html, Locale: locale}), so swapping them no longer compiles; an emptyLocalestill draws as"en". A static build now draws every card, even when there are more thanmaxEntriesormaxByteskeep: it used to fail withogimage-draw"file does not exist" for the cards evicted before they were drawn. - A card is an
html/templatefile underog/in a subset of HTML and CSS: an element holding boxes saysdisplay:flex, one holding text is a paragraph of runs. What it cannot draw stops the application at startup, with the template, line and column. - A page that sets no card gets
Default, drawn from its title and description. - The URL is a hash of what is drawn, served immutable; nothing is invalidated, a changed page has a new card. A card is drawn on its first request, only if a render recorded it;
collage exportwrites them.Dirkeeps them across restarts, which a disk page cache needs. - In development
/_og-preview/lists them;go run . ogimage og/post.html card.json > card.pngdraws one without the site, in the default locale or the one-locale trnames.
elagoht/sitemap
github.com/Elagoht/collage-sitemap serves /sitemap.xml from the pages the application registered.
import "github.com/Elagoht/collage-sitemap"
BaseURL: "https://example.com",
Plugins: []collage.Plugin{sitemap.New(sitemap.Options{})},
{
"elagoht/sitemap": {
"path": "/sitemap.xml",
"exclude": ["thanks"],
"maxURLs": 50000
}
}
- A sitemap lists absolute URLs, so it needs an origin:
Config.BaseURL, or the request's own origin on a site served on several hosts, as anOriginResolverplugin names it. With neither, the application does not start. v0.3.0 removed the plugin's ownbaseURL. - It lists every page with a path, in every locale, as
App.URLspells it, with its other locales ashreflangalternates. A{param}pattern is listed once for each value itsWithStaticParamsreturns, the URLs a static build writes; one without it is left out.Excludeleaves pages out by name. LastMod, a Go function, gives a page's<lastmod>.- It is a static document: cached, exported, and made again when
sitemap.Tagis invalidated — invalidate it with the tags of a post you publish. - Past 50,000 URLs (
maxURLs; 0 is 50,000, a negative value stops the application) it becomes a sitemap index of numbered files.
elagoht/robots
github.com/Elagoht/collage-robots serves /robots.txt.
import "github.com/Elagoht/collage-robots"
Plugins: []collage.Plugin{robots.New(robots.Options{
Rules: []robots.Rule{{Disallow: []string{"/admin"}}},
Sitemaps: []string{"https://example.com/sitemap.xml"},
})},
{
"elagoht/robots": {
"rules": [{ "userAgents": ["*"], "disallow": ["/admin"] }],
"sitemaps": ["https://example.com/sitemap.xml"],
"disallowAll": false
}
}
- With no rules it allows every crawler everything; a rule with no user agents is for
*. A negativecrawlDelaystops the application. v0.3.0 removed(*Plugin).Render: request/robots.txtfrom the application instead. disallowAllcloses the site to every crawler, whatever the rules say, and sends every response withX-Robots-Tag: noindex, nofollow. Set it in the configuration of a staging deployment, so one binary is open in production and closed elsewhere.- A sitemap may be given as a path (
"/sitemap.xml"), which is made absolute per request against the request's origin:Config.BaseURLor, on a multi-host site, anOriginResolverplugin's. A scheme-relative//host/pathis refused, and with no origin to resolve a path against the application does not start. - The body is fixed at startup, and a static build writes it to
robots.txt.
elagoht/feed
github.com/Elagoht/collage-feed serves RSS 2.0 and Atom 1.0 feeds from items the application lists, and announces them in every page's head.
import "github.com/Elagoht/collage-feed"
BaseURL: "https://example.com",
Plugins: []collage.Plugin{feed.New(feed.Feed{
Title: "The blog",
Link: "/blog",
Items: latestPosts, // func(ctx) ([]feed.Item, error), newest first
Tags: []string{"posts"},
})},
- It is configured in Go only, since
Itemsis a function;collage plugin addwritesfeed.New(), and with no feed given the plugin logs a warning and serves nothing. - A feed is served at
/feed.xmlas RSS and/atom.xmlas Atom;RSSandAtommove them, and"-"leaves a format out. Several feeds each take aNameand their own paths. It carries at mostLimititems, 20 by default. - Every page gets a
<link rel="alternate">for every feed, so it needs{{hoist "head"}}in the layout;NoDiscoverykeeps a feed out of the heads. - It is a static document: cached, exported, and made again when one of its
Tagsis invalidated. - Links are written only as
httporhttps(since v0.2.1). An item link, a URL-shapedID, or the channel link with any other scheme (javascript:,data:,file:, however it is spelled) is dropped and logged once atWARN, with the scheme and not the link. A feed's ownLink,RSSorAtomwith such a scheme stops the application from starting withErrUnsafeLink. An absolutehttporhttpslink is written as given (v0.2.2; v0.2.1 re-encoded a non-ASCII path). - A feed's links follow the request's origin,
Config.BaseURLor anOriginResolverplugin's, so one feed serves each host its own links. v0.3.0 removedFeed.BaseURL; with no origin the application does not start.
elagoht/redirects
github.com/Elagoht/collage-redirects serves redirects kept in a file rather than in code — what a site migration leaves behind — before routing, and hands them to a static build for the host's own configuration.
import "github.com/Elagoht/collage-redirects"
//go:embed redirects.txt
var siteFS embed.FS
Plugins: []collage.Plugin{redirects.New(redirects.Options{FS: siteFS})},
# the old blog
/blog/* /posts/:splat
/about-us /about 301
/summer-sale /sale 302
/moved https://new.example/moved 308
/old-product - 410
{
"elagoht/redirects": {
"file": "redirects.txt",
"rules": [{ "from": "/careers", "to": "https://jobs.example.com", "status": 302 }]
}
}
- One rule a line: the old path, where it went, and a status —
301when left out, or302,307,308, or410with-for a page that is gone, answered with the site's own not-found page and status410./blog/*is a prefix, and:splatin the target is what the*matched. The first rule that matches wins, and the reader's query string is carried over. - A file that is wrong stops the application from starting, and says where: a malformed line, a rule no request can reach, rules that send a reader round in a circle. Since v0.2.0 so does a control character in a rule, or a target beginning
/\, which a browser reads as another host. - Since v0.2.0 it no longer serves or writes
_redirects(breaking):Options.NoRedirectsFileandRedirectsFile()are gone, and anoRedirectsFilekey in configuration stops the application as an unknown key. It is aRedirectSource: a static build takes its rules, and elagoht/deploy writes them in the host's format. Without a deploy plugin nothing is written. - A rule collage's pattern syntax cannot say is still served, but left out of the build with a
redirects-not-exportedwarning. A rule covering a page's or a document's own redirect is aredirects-overlapwarning: the server follows the rule, a static host the page's redirect. - A static build fails on a rule over a file it wrote (
collage.ErrRedirectShadowsFile) or from the same path as another redirect (collage.ErrDuplicateRedirect), so a site whose export worked with v0.1.x can fail until the rule or the page goes. Rules can also be given in Go or configuration.
elagoht/indexnow
github.com/Elagoht/collage-indexnow tells search engines which URLs changed, through the IndexNow protocol — Bing, Yandex, Seznam, Naver and the others that share what one of them is told.
import "github.com/Elagoht/collage-indexnow"
BaseURL: "https://example.com",
Plugins: []collage.Plugin{indexnow.New(indexnow.Options{
Key: "4f1c2e9a7b3d4c8e",
})},
{
"elagoht/indexnow": {
"key": "4f1c2e9a7b3d4c8e",
"window": "10s",
"skip": ["/api", "/search"]
}
}
keyis required. URLs followConfig.BaseURL; on a site served on several hosts one submission is sent per origin, and an origin two hosts share is sent once.- v0.3.0 removed
baseURLand renamedexcludetoskip— request path prefixes never sent,"/api"covering/apiand what is under it.windowandbackoffare duration strings, and a negativeretriesorbatchSizestops the application. - What it sends is what the cache let go of: the paths an invalidation reached. A page that was not cached when its tag was invalidated is not sent.
- URLs are batched for
window, sent in the background and retried on a429or5xx; what is waiting is flushed on shutdown. - It serves the key at
/<key>.txt, and a static build writes it there. A development server and a static build send nothing.
Content
Where the words come from and how they are presented: Markdown rendered as HTML, coloured code, a table of contents, search on a static site, and translations.
elagoht/markdown
github.com/Elagoht/collage-markdown renders Markdown strings as HTML: a {{markdown}} template function, Render from Go, and Parse, which also reads a document's front matter into a type of the application's own. It reads no files and builds no pages: where the Markdown comes from, and the page, its data and its SEO, are the application's.
import "github.com/Elagoht/collage-markdown"
md := markdown.New(markdown.Options{})
Plugins: []collage.Plugin{md},
<article>{{markdown .Body}}</article>
type Post struct {
Title string `md:"title"`
Date time.Time `md:"date"`
Tags []string `md:"tags"`
}
doc, err := markdown.Parse[Post](md, rc.Locale, src) // doc.Meta, doc.HTML, doc.Text, doc.Headings
{
"elagoht/markdown": {
"extensions": ["table", "strikethrough", "linkify", "taskList", "footnote", "mark", "headingIDs", "headingAttributes"],
"unsafe": false
}
}
- It must be in
Config.Plugins: it adds a template function. extensionspicks fromtable,strikethrough,linkify,taskList,footnote,mark(==text==is<mark>text</mark>),headingIDs,headingAttributes,definitionListandtypographer. Left out, it is all but the last two; a list replaces that whole,[]turns them all off, and an unknown name stops the application.- A front matter key is read into the field tagged
md:"key", or the untagged field of that name; a key no field takes is ignored, a value that does not convert is an error.markdown.FrontMatter[Post](src)reads it without rendering. - Heading ids keep letters of any alphabet and follow the page's locale (
## IŞIKisışıkin Turkish). Code blocks are<pre><code class="language-go">, which elagoht/highlight colours when it is registered. - Raw HTML, and a heading's
{style="…"}andon…attributes, are left out unlessunsafeis on;idandclassstay. - Changed in v0.4.0: the plugin no longer reads a directory.
FS,Dir,LocaleDirs,Drafts,Name,Handler,IndexHandler,StaticParams,List,Get,TagandDirTagare gone; the application reads its own files and builds its pages withmarkdown.Parse. The plugin's README shows a blog built that way.
elagoht/highlight
github.com/Elagoht/collage-highlight colours code with chroma: the code blocks on every rendered page, a {{highlight}} template function, and a light and dark stylesheet.
import "github.com/Elagoht/collage-highlight"
Plugins: []collage.Plugin{highlight.New(highlight.Options{})},
{{highlight .Snippet "go"}}
{
"elagoht/highlight": { "light": "github", "dark": "github-dark", "noBackground": true }
}
- It must go in
Config.Plugins: it adds{{highlight}}. - Unless
noAutois set, every<pre><code class="language-go">a page holds — what elagoht/markdown and most Markdown renderers write — is coloured where it stands, once per render; a cached page is served as it was coloured. - The stylesheet is linked from pages with coloured code only, by a content-addressed name, each theme under its own
prefers-color-schemequery.noAuto: trueleaves those blocks alone, so only{{highlight}}colours code; since v0.3.0 it replaces"auto": false, and"auto"is an unknown key. Since v0.2.0 the automatic pass hoists it withAfterRenderEvent.Hoist, so it lands where the layout put{{hoist "head"}}, or before</head>without one;{{highlight}}needs{{hoist "head"}}in the layout.
elagoht/toc
github.com/Elagoht/collage-toc gives a page's headings ids, and puts a table of contents and a reading time where the templates ask for them.
import "github.com/Elagoht/collage-toc"
Plugins: []collage.Plugin{toc.New(toc.Options{})},
<aside>{{toc}}</aside>
<p>{{readingTime}}</p>
{
"elagoht/toc": {
"minLevel": 2,
"maxLevel": 4,
"wpm": 225,
"text": { "label": "Table of contents", "readingTime": "{n} min read" },
"locales": { "tr": { "label": "İçindekiler", "readingTime": "{n} dk okuma" } }
}
}
- It must go in
Config.Plugins: it adds template functions. - Since v0.2.0 the default locale's words are under
text(Options.Text, a named field rather than an embedded one), not at the top level, andlocalesholds the others;"ids": falseis"noIDs": true. An old top-levellabeloridsstops the application as an unknown key. - Each function writes a placeholder, and the plugin fills it in once the page has rendered: the
h2toh4inside<main>, as a nested list, and the words divided bywpm. - A heading without an
idgets one from its text, letters of any alphabet kept and lowered as the page's language lowers them;noIDsleaves a page without placeholders alone. - A fragment served on its own does not run the page hooks, so put
{{toc}}in the page, not in a fragment refreshed on its own.
elagoht/search
github.com/Elagoht/collage-search adds search to a static site: a static build writes an index of every page, and a small script searches it in the browser.
import "github.com/Elagoht/collage-search"
Plugins: []collage.Plugin{search.New(search.Options{})},
{{searchBox}}
{
"elagoht/search": {
"maxText": 5000,
"exclude": ["admin", "tags"],
"text": { "label": "Search" },
"locales": { "tr": { "label": "Ara", "noResults": "Sonuç yok" } }
}
}
- It must go in
Config.Plugins: it adds{{searchBox}}. - Since v0.2.0
excludetakes page names, left out in every locale, not path prefixes: an old"/admin/", or a name no page has, stops the application. What the box says is undertext(label,placeholder,results,oneResult,noResults,unavailable), andlocalesholds the same per locale. - The index is a static build's.
collage exportwritessearch-index.jsonfrom each page's title, description, headings and text; a running server has none, and the box says so rather than breaking. - The script is fetched with the page and loads the index the first time the box is focused. It matches every word, ignoring case and accents, ranks titles above headings above text, and keeps to the page's language.
elagoht/i18n
github.com/Elagoht/collage-i18n translates: a catalog per locale, {{t}} in templates in the locale the page is rendered in, plurals, and missing translations reported as findings.
import "github.com/Elagoht/collage-i18n"
//go:embed locales
var locales embed.FS
Plugins: []collage.Plugin{i18n.New(i18n.Options{FS: locales})},
<a href="{{pageURL "home"}}">{{t "nav.home"}}</a>
<p>{{tn "cart" .Count}}</p>
{ "elagoht/i18n": { "dir": "locales", "strict": true } }
- It must go in
Config.Plugins: it adds template functions. The catalogs come fromOptions.FS, so it is constructed in Go. - One JSON file of nested keys per supported locale,
locales/<locale>.json; the application does not start while a supported locale has none. ttranslates a key and fills{name}from name and value pairs,tnpicks a plural form for a count,thallows markup from the catalog. A data handler callsi18n.T(rc, key, pairs...); since v0.3.0 the pairs are strings (i18n.T(rc, "visits", "n", strconv.Itoa(n))), while the template functions still print any value.thescapes each value for where it lands (since v0.4.0), as html/template escapes{{.Value}}there: the catalog's markup is trusted, the values filling it are not. In text a value is escaped; in a URL attribute (href,src,action…) one that is nothttp:,https:,mailto:or relative becomes#ZgotmplZ; in an unquoted attribute its spaces and=are escaped, so it cannot add an attribute. Up to v0.3.0 a value was HTML-escaped wherever it was, so ajavascript:value in<a href="{url}">made a working link. An entry that ends inside a tag or an attribute now fails the render with ani18n:error: close the tag in the catalog. A safe URL or plain text renders as before, except that a URL's spaces and non-ASCII letters are now percent-encoded.- A missing key falls back to the default locale, then to the key, and is reported as
i18n-missingover the page in development and in a static build's report. In development the catalogs are read again on every request. - Outside a render (since v0.2.0), for an email or a background job, keep the plugin's value:
tr.In(user.Locale)returns aTranslatorwhoseT,TNandTHfollow the same catalogs, fallback and plurals, and whoseFuncs()gives an application's ownhtml/templatet,tnandth. A locale the application does not support is the default one. A key it cannot find is logged, once per key and locale. The catalogs are read when the application starts, not incollage.New; a translation asked for before then is the key itself. - A key one catalog has and another lacks is logged at startup and listed as
i18n-untranslatedin a build, in either direction since v0.2.0 (the codes weremissing-translationanduntranslatedbefore v0.3.0). A plural form a locale's rule never picks is not counted;zerois. Withstrictthe application does not start while the catalogs differ. - A key written both dotted and nested,
{"nav.home": …}beside{"nav": {"home": …}}, refuses to start since v0.2.0; which text it showed used to depend on map order.
Forms and state
What a form needs around an action: validation, spam protection, a message shown after the redirect, a session in a cookie, and file uploads.
elagoht/validate
github.com/Elagoht/collage-validate validates a form an action receives: chainable checks per field, a refused submission rendered again with status 422, and template functions that put each field's message and what the reader typed back in the form.
import "github.com/Elagoht/collage-validate"
Plugins: []collage.Plugin{validate.New(validate.Options{})},
v := validate.Form(rc)
v.Field("email").Required().Email()
v.Field("password").Required().MinLen(8)
if !v.Valid() {
return validate.Refuse(rc, v, signupPage), nil
}
return collage.SeeOther("/welcome"), nil
Each field gives back what was checked, as its type (since v0.3.0):
servings := v.Field("servings").Required("How many servings?").Int().Range(1, 50)
minutes := v.Field("minutes").Int() // optional
steps := v.Field("steps").Required().Lines() // a <textarea>, one per line
tags := v.Field("tags").All().OneOf(tagNames...) // a group of checkboxes
if !v.Valid() {
return validate.Refuse(rc, v, rc.Page), nil
}
create(servings.Value(), minutes.Ptr(), steps.Value(), tags.Value()) // int, *int, []string, []string
<input name="email" type="email" value="{{fieldValue "email"}}">
{{with fieldError "email"}}<p class="error">{{.}}</p>{{end}}
<!-- a form that starts from a record: the stored name, or what was typed -->
<input name="fullname" value="{{fieldValue "fullname" .User.FullName}}">
{
"elagoht/validate": {
"messages": { "required": "Please fill this in." },
"localeMessages": { "tr": { "required": "Bu alan zorunludur." } },
"noRefill": ["pin", "card"]
}
}
- It must go in
Config.Plugins: it adds{{fieldError}},{{fieldValue}}and{{hasErrors}}. {{fieldValue "name" fallback}}shows what was submitted when a submission was refused, and the fallback when the form is shown for the first time — the value a profile or an edit form starts with.- Since v0.1.2
validate.Formreads nothing until a check orv.Valueneeds the form. An action refusing a body before reading it — a photo whoseContent-Lengthis over its size — builds a validator forv.Failandvalidate.Refuse, and the body is never read. Since v0.1.3 such a refusal shows each field's fallback, since there is nothing typed to show. The action'sWithMaxBodyBytesmust be above the size it checks, or collage's413answers first. - It is the first half of collage's rule for a form — see Forms and actions. On a page nobody submitted the functions are empty, so one template serves both renders and the first stays cacheable.
- The checks are
Required,MinLen,MaxLen,Email,URL,Int,Range,OneOf,Matches,EqualandCustom;v.Failreports what only the application knows. A field keeps its first message. Every check butOneOftakes an optional message of its own,Required("…"), as.Message("…")after it would (since v0.3.0). - Every check sees the trimmed value (since v0.3.1) — the value
Value()returns, with the white space around it gone. Before,MinLen,MaxLen,Email,OneOf,Matches,EqualandCustomsaw it as it arrived, soMinLen(8)passed" x"whileValue()handed back"x". A value padded to reach a minimum length is now refused," m "passesOneOf("m"),Equalcompares both fields trimmed, andCustomis given the trimmed value. A value of only white space counts as empty for every check, as it already did forRequired, so an optional field sent as" "is skipped.v.Value(name)still returns the value as it arrived. - Typed values (since v0.3.0).
Field.Value()is the string, trimmed.Int(),Float(),Bool()(a checkbox),Date()(2026-10-25),All()(every value under the name) andLines()(a textarea's lines) turn the field into a typed one whoseValue()is anint,float64,bool,time.Timeor[]string, and whose checks work on it:Min,Max,Range,MinItems,MaxItems,Custom(func(int) string).Ptr()is nil for a field left empty — an optional field's "not given". A field that failed gives the zero value.Int()returns an*IntField: a string check after it no longer compiles;.Int().Message(…)and.Int().Range(…)still work. - Messages are English by default, and are replaced per check, per locale or for every locale. A field whose name contains
passwordis never typed back;noRefilladds names of your own to it (since v0.2.0 it no longer replacespassword). validate.Values(rc, values)(since v0.2.0) checks values something else already read — the fieldsuploads.Receivehands back after streaming a body — andRefusetypes them back the same way.- Field names are one space per render: two forms on one page sharing a field name both show that field's message and value. Give each form's fields names of their own.
elagoht/honeypot
github.com/Elagoht/collage-honeypot stops form spam without a CAPTCHA: a decoy field people never see and bots fill in, and a signed timestamp that refuses a form that was never served, was served too long ago, or — when the form asks — came back too soon.
import "github.com/Elagoht/collage-honeypot"
Plugins: []collage.Plugin{honeypot.New(honeypot.Options{})},
<form method="post" action="/contact">
{{csrfToken}}
{{honeypot}}
<textarea name="message"></textarea>
<button>Send</button>
</form>
{
"elagoht/honeypot": {
"minDelay": "0s",
"maxAge": "24h",
"silent": false,
"protect": []
}
}
- It must go in
Config.Plugins: it adds{{honeypot}}. - Since v0.6.0 the key is read from
HONEYPOT_KEYwith nothing configured: putHONEYPOT_KEY=(openssl rand -hex 32) in.env.developmentand where production runs.keyEnvnames another variable and wins, thenOptions.Key, thenHONEYPOT_KEY; a named variable must be set,HONEYPOT_KEYmay be empty, and either one not hex stops the application. - Changed in v0.5.0: the hex
keyis gone —keyEnvnames the environment variable holding it, andOptions.Keytakes the bytes from Go.maxAgeandminDelayare duration strings ("24h","300ms");{{honeypot 0.3}}still takes seconds, and"0s", the default, is no delay (-1is now an error). An old key or a bare number stops the application at start, naming the key. - It has no say in how large a submission may be. It checks the form in
BeforeActionHook, through the action's own body limit, so a form that uploads large files needs only the action'sWithMaxBodyBytes. Only collage actions are checked, not handlers mounted withapp.Handle. - The forms say which paths are protected: once a page with a
{{honeypot}}form has been served, a form body posted to that form'sactionis checked before it reaches the action. A form without{{honeypot}}is never checked, and nothing in the configuration has to name the forms. A JSON body and everyGETpass unchecked. - An action built with
WithStreamingBody()passes unchecked too: its form is never parsed, so there is nothing to check. - A process learns the paths from the pages it serves. After a restart or a new release, until the form's page has gone out again, a bot posting straight to the path is not checked.
protectlists prefixes checked from the first request;["/"]checks every form the site accepts. Before v0.2.0 that was the default. - A process keeps up to 4096 learned paths. Since v0.6.1 the path whose form was served least recently is forgotten for a new one, with a warning at most once a minute; before, learning stopped at 4096, so a page answering any path with a
{{honeypot}}form let a client fill the set with junk and leave every form not yet learned unchecked until a restart. A submission that reaches an action through a learned path also marks the action, which is then checked on every path: a comment form for record 2 is checked once one for record 1 was posted to. Until an action's first such submission its path can still be pushed out;protectcloses that. A full set never means checking every form, since a form that never carried{{honeypot}}— a log-out button, another plugin's form — would then be refused. - No delay by default.
{{honeypot 0.3}}asks a form to be open at least that many seconds before it is sent, signed into the timestamp so a bot cannot shorten it;minDelay("300ms") sets one for every form that does not choose its own. - The timestamp survives the page cache as collage's forgery token does: the cached page carries a placeholder, and the plugin signs the current time into it through
PersonaliseHook, after the page cache and before compression. Its place inConfig.Pluginsdoes not matter. (Before v0.4.0, listed before elagoht/compress it left the placeholder in the gzip body and every real submission was refused.) A stamped page is sent withCache-Control: private, no-store(set by collage) and a newETagon every response. Set a key of at least 32 random bytes, the same on every instance, hex-encoded in the variablekeyEnvnames; it never goes inplugins-config.json. - Only what collage renders is stamped: a page, a fragment, an action's HTML answer, an error page. A placeholder a hand-written
app.Handlehandler writes itself goes out as it is, unstamped. A form carrying it that posts to a collage action is refused when the action's path is protected (inprotect, or learned from another form) or the action is marked, and is not checked otherwise; list such a path inprotect. (Before v0.4.0 such a response was stamped, its type sniffed from the first bytes.) - A refusal is a
400; withsilentit is a303back to the form, as an accepted form answers. It stops careless bots, not a determined one — pair it with elagoht/ratelimit.
elagoht/flash
github.com/Elagoht/collage-flash adds flash messages: a message an action sets before it redirects, shown once by the page it redirects to.
import "github.com/Elagoht/collage-flash"
Plugins: []collage.Plugin{flash.New(flash.Options{})},
flash.Add(rc, flash.Success, "Your changes are saved.")
return collage.SeeOther("/settings"), nil
{{range flashes}}
<p class="flash flash--{{.Kind}}" role="status">{{.Text}}</p>
{{end}}
{
"elagoht/flash": {
"cookie": "collage_flash",
"maxAge": "5m"
}
}
- It must go in
Config.Plugins: it adds{{flashes}}. - Since v0.3.0 the key is read from
FLASH_KEYwith nothing configured: putFLASH_KEY=(openssl rand -hex 32) in.env.developmentand where production runs.keyEnvnames another variable and wins, thenOptions.Key, thenFLASH_KEY; a named variable must be set,FLASH_KEYmay be empty, and either one not hex stops the application. - Changed in v0.2.0: the hex
keybecamekeyEnv, the name of the environment variable holding it (Options.Keyfrom Go is unchanged), andmaxAgeis a duration string,"5m"by default, where it was seconds. An oldkeystops the application withunknown key "key". - The messages travel in a signed,
HttpOnlycookie,Securewhencollage.IsHTTPSsays the request came over HTTPS. Set a key of at least 32 random bytes, the same on every instance; without one a key is made per process and a warning logged. - At most eight messages of 300 characters are kept, and since v0.3.1 the cookie is measured as it is written: a browser drops a cookie over four kilobytes whole, so its
Set-Cookieline is never written over 4096 bytes. Text that grows when encoded — non-ASCII letters, or<,>and&, six bytes each — can pass that with fewer messages; the oldest are then dropped until the rest fit, a lone message too big is cut short, and a warning is logged. Before, such a cookie reached 6–7 KB and every message was lost silently. - A request carrying a message is rendered fresh, neither read from the page cache nor written to it, and marked
private, no-store. Every other request is served as it would be without the plugin.
elagoht/session
github.com/Elagoht/collage-session keeps a session in a cookie: a small map of strings the site signs, and can encrypt, with no database behind it.
import "github.com/Elagoht/collage-session"
Plugins: []collage.Plugin{session.New(session.Options{})},
s := session.Get(rc)
s.Regenerate()
if err := s.Set(session.UserKey, user.ID); err != nil {
return nil, err
}
return collage.SeeOther("/account"), nil
A layout carrying session.RequireUserPage keeps signed-out readers off every page it wraps — a guard that sends them to the page named login:
private := collage.NewFragment("private", "layouts/private.html").
WithGuard(session.RequireUserPage("login")).
Build()
{
"elagoht/session": {
"encrypt": true,
"maxAge": "168h",
"idleTimeout": "0s",
"sameSite": "lax"
}
}
- Since v0.5.0 the key is read from
SESSION_KEY, and the previous keys fromSESSION_PREVIOUS_KEYS, with nothing configured: putSESSION_KEY=(openssl rand -hex 32) in.env.developmentand where production runs.keyEnvandpreviousKeysEnvname other variables and win, then the options set from Go, then these two; a named variable must be set, these may be empty, and a key that is not hex stops the application. - It adds no template function, so
RegisterPluginaccepts it too. - Changed in v0.3.0: keys never go in
plugins-config.json.keyEnvnames the environment variable holding the hex key andpreviousKeysEnvthe one holding previous keys, comma-separated; from Go,Options.KeyandOptions.PreviousKeystake the bytes.maxAgeandidleTimeoutare duration strings ("168h","30m") where they were seconds. An oldkeyorpreviousKeysstops the application withunknown key. RequireUser(loginPath)(since v0.2.0) lets through a reader whose session holds a value undersession.UserKey("user"), and sends everyone else303tologinPathwith where they were going innext:/login?next=%2Fdashboard. A login path with a query of its own keeps it.Require(key, loginPath)is the same for any key —Require("admin", "/login"). Without the plugin in the application the guard fails the request withErrNoSessionrather than sending every reader to a login that could never let them in. Passnextthroughcollage.SafeRedirectbefore the login action redirects to it:collage.SafeRedirect(rc.Request.URL.Query().Get("next"), "/").RequireUserPage(loginPage)isRequireUserwith the login page named rather than its path written: the path is built withcollage.URLfor each request, in its locale —/tr/giris?next=…from a Turkish page — so a renamed or translated path cannot leave the guard pointing at the old one.RequirePage(key, loginPage)is its form for any key. A name the application has not registered fails the request rather than letting anyone through.RequireGuest(homePath)andRequireGuestPage(homePage)(since v0.6.0) guard the pages only a signed-out reader needs — sign in, sign up, a forgotten password. A signed-out reader goes through; a signed-in one gets303to the request'snextwhencollage.SafeRedirectfinds it a path on this site, or to the home path, or the named page in the request's locale.WithGuard(session.RequireGuestPage("account"))on the auth pages' layout.Get,Set,Delete,Clear,RegenerateandID; a handler of your own reads it withsession.FromContext(r.Context()).- A request carrying a valid session is rendered fresh, neither read from the page cache nor written to it, and marked
private, no-store. A reader without one is served from the cache as before. Set a session from an action, not from a cached page. - The cookie is
HttpOnlyandSameSite=Lax, written only when the session changed, andSecurewhencollage.IsHTTPSsays the request came over HTTPS. Keys rotate through the previous keys: a cookie under one is accepted and rewritten under the current key. A session cannot be revoked: it lives in the reader's cookie. - A session is bound to the host it was issued on (since v0.7.0): the host, lower-cased and without its port, is inside the signed payload, and a cookie presented on another host is no session there — ignored, not cleared. On one process serving several sites with one key, elagoht/tenant's tenants, a cookie copied from
acme.testtoglobex.testis anonymous there. Withdomainon a one-site application the session is bound to the domain instead, so its subdomains share it; with tenants (any plugin resolving hosts to origins) each host stays its own, so do not setdomainthere. The host is the request'sHost: behind a proxy that rewrites it, forward the original, or every session is bound to the proxy's. - Cookies from before v0.7.0 carry no host. A one-site application accepts one and rewrites it bound to the host it arrived on, so the upgrade signs nobody out; a multi-site one cannot tell which tenant issued it, so it is refused and cleared, and every reader signs in again once. Nothing in the configuration changes.
elagoht/uploads
github.com/Elagoht/collage-uploads receives file uploads: it checks each file by its content, stores it under a random key, and serves it back without letting it act as your site. It reads a form that was already parsed, or streams the body part by part, with the same result.
import "github.com/Elagoht/collage-uploads"
u := uploads.New(uploads.Options{Dir: "var/uploads"})
Plugins: []collage.Plugin{u},
got, err := u.Receive(rc,
uploads.Field("avatar", uploads.Rules{
MaxSize: 5 << 20,
MaxFiles: 1,
Types: []string{"image/png", "image/jpeg"},
}),
)
var rule *uploads.Error
if errors.As(err, &rule) {
// Show rule.Field's error beside the form; got.Values holds what was typed.
return showFormAgain(rc, got.Values, rule)
}
if err != nil {
return nil, err
}
avatar := got.Files["avatar"][0] // Key, Name, Type, SHA256, Size
app.Handle("/uploads/", u.Handler())
{
"elagoht/uploads": {
"dir": "var/uploads"
}
}
- It adds no template function, so
RegisterPluginaccepts it too. Keep it in a variable: the action callsu.Receiveand the application mountsu.Handler(). That mount runs with no middleware; addcollage.WithMiddleware()to theapp.Handlecall if a basicauth, a session check or elagoht/compress should cover the files. - Changed in v0.2.0: one constructor,
uploads.New(uploads.Options{…}):New(store)isNew(uploads.Options{Store: store})andNewWith(uploads.Config{Dir: d})isNew(uploads.Options{Dir: d}).Handlertakes no argument; itsCache-ControliscacheControlin configuration orOptions.CacheControl. The configuration is read even with a store given in Go, so an unknown key stops the application there too. - Two paths. On an ordinary action, a plain
<form enctype="multipart/form-data">with{{csrfToken}}works with no JavaScript, andReceivereads the parsed form — fine for files up to tens of MB. On an action built withWithStreamingBody(), it walks the body withMultipartReaderand streams each file straight into the store; such an action takes its token only from theX-CSRF-Tokenheader, so post to it withfetch(). Anything that parses the form first,validate.Formincluded, gives up the stream; read the other fields fromgot.Values. See Streaming bodies. - Typed by content. A file's type is sniffed from its first 512 bytes; its name, extension and
Content-Typeare never consulted. A broken rule is an*uploads.Errorwith the field and one ofErrTooLarge,ErrType,ErrTooManyorErrUnexpectedField. - All or nothing. If anything fails — a broken rule, a client that went away, a body over its limit, the store — every file that call stored is deleted before
Receivereturns. Once it succeeds the files are yours: delete them withu.Store().Deleteif the action fails after that. Dirkeys each file by 128 random bits plus an extension for its sniffed type, so nothing the client sent goes into a path.Nameis the client's file name, cleaned, for display only. It writes 0600 files in a 0700 directory, never overwrites, and reads only regular files. Metadata — name, owner, upload time — is yours to keep in your database next to the key.Handlerserves a file by key withX-Content-Type-Options: nosniff,Content-Security-Policy: sandbox, its type sniffed again, andContent-Disposition: attachmentunless it is a PNG, JPEG, GIF or WebP image. It does no access control: anyone with a key can fetch the file, so serve private files from an action of your own. Never serve the directory directly.- Abuse and disk. Guard the upload action (a token is not authentication), keep
MaxBodyBytesandMaxSizetight, rate-limit the path, keep the store on a volume of its own, and give the actionWithBodyTimeout; see Deployment for proxies. A crash betweenReceiveand your database write leaves files no row points to; sweep the directory for old keys your database does not know, skipping.upload-*temp files younger than an hour, which may be uploads in progress.
Security
Headers a site should send, a limit on how fast one client can hit it, a password in front of a site that is not public yet, sign-in with an identity provider, and the visitor's consent to cookies.
elagoht/secure
github.com/Elagoht/collage-secure sends the security headers a site should, and a Content-Security-Policy whose nonces survive the page cache.
import "github.com/Elagoht/collage-secure"
Plugins: []collage.Plugin{secure.New(secure.Options{
CSP: "default-src 'self'; script-src 'self' 'nonce-{nonce}'",
})},
{
"elagoht/secure": {
"csp": "default-src 'self'; script-src 'self' 'nonce-{nonce}'",
"cspReportOnly": false,
"hsts": 63072000,
"hstsSubdomains": true,
"frameOptions": "DENY",
"permissionsPolicy": "camera=(), microphone=(), geolocation=()"
}
}
- It must go in
Config.Plugins: it adds{{cspNonce}}. Its place in the list does not matter: the nonce goes in after the cache and before compression, throughPersonaliseHook, so it works whether it is listed before or after elagoht/compress. (Before v0.2.0, listed before compress it left the marker in the gzip body and the CSP blocked every inline script.) - By default it sends
X-Content-Type-Options,X-Frame-Options,Referrer-Policy,Cross-Origin-Opener-Policyand, over TLS or behind a proxy sendingX-Forwarded-Proto: https,Strict-Transport-Security. Since v0.3.0 that header is believed only from a proxy inServer.TrustedProxieswhen any are listed (collage.IsHTTPS).Permissions-Policyand the CSP are sent when set;"-"leaves a header out,X-Content-Type-Optionsincluded ("contentTypeOptions": "-", which replaced"noSniff": falsein v0.3.0). {nonce}in the policy and{{cspNonce}}on an inline script are one nonce, new on every response: the cached page carries a placeholder, and the plugin's hook puts a fresh nonce in its place. A page carrying one is sent withCache-Control: private, no-store(set by collage) and a newETagon every response. Every other response answers conditional requests as usual: a feed, a document or a mounted file still gets its304(since v0.1.5; before, with a policy set, nothing behind the plugin could).- Set a key: at least 32 random bytes, the same on every instance and across restarts, in hex (
openssl rand -hex 32) inSECURE_KEY, which is read with nothing configured (since v0.4.0). A secret never goes inplugins-config.json:keyEnvnames another variable and wins, orOptions.Keytakes the bytes from Go, and wins overSECURE_KEY(v0.3.0;keyandOptions.KeyHexare gone). With it the{{cspNonce}}placeholder is the same in every process, so a page from a disk cache that survived a deploy, or from a cache shared by several instances, still gets its nonce. Without a key the placeholder changes per process, and such a page carries another process's placeholder, matching no header until the entry expires: set a key when you use a disk cache or several instances. A key that is short, a named variable that is empty or not hex, or aSECURE_KEYthat is not hex, stops the application from starting; keep it secret. - With no policy, or one without
{nonce}, there is no nonce to name: thenonceattribute is removed, as in a static build, and the page stays cacheable with a stableETag. - A static export writes pages this middleware never serves, and a file cannot carry a per-response nonce. So in a static build the
nonceattribute is removed and the script kept, with one warning; allow those inline scripts in the host's own policy (since v0.1.2 — before, the placeholder was left in the exported HTML). - In development the policy is sent report-only, so collage's live-reload script keeps working.
elagoht/ratelimit
github.com/Elagoht/collage-ratelimit limits how fast one client can hit the site: a token bucket per client, per rule, and a 429 Too Many Requests with Retry-After once it is empty.
import "github.com/Elagoht/collage-ratelimit"
Plugins: []collage.Plugin{ratelimit.New(ratelimit.Options{
Rules: []ratelimit.Rule{
{PathPrefix: "/login", Rate: 0.1, Burst: 5},
{Rate: 0.5, Burst: 10},
},
})},
{
"elagoht/ratelimit": {
"rules": [{ "pathPrefix": "/login", "rate": 0.1, "burst": 5 }],
"skip": ["/_collage/", "/healthz", "/readyz", "/api/webhooks"],
"ipv6Prefix": 48
}
}
- With no options, every form and action — every method but
GET,HEADandOPTIONS— is limited to a burst of ten, then one request every two seconds. - The first rule a request matches counts it, so put narrow rules first; each rule has its own buckets.
skip(by default/_collage/,/healthzand/readyz) and a rule'spathPrefixmatch whole segments, with or without a trailing slash:/loginis not/login-help. Responses carryRateLimit-Limit,RateLimit-RemainingandRateLimit-Reset. - A client is its IP address, or its
/64for IPv6. Behind a reverse proxy list the proxies in collage'sServer.TrustedProxies, and the client iscollage.ClientIP. The plugin's owntrustProxyandtrustedProxiesare gone since v0.2.0, and an old configuration naming them stops at start.KeyFunc, in Go, keys by something else. ipv6Prefix(since v0.3.0) sets how many leading bits of an IPv6 address name the client: 32 to 128, 64 by default; IPv4 clients are always one address. A/64is not a whole attacker — a tunnel broker hands out a/48for free, and many hosts give each server a/48or a/56, 65536 or 256 buckets of their own.48makes a whole/48one client and one bucket, shared with everyone else in it;128is one address. A value outside the range stops the application from starting.- Buckets are kept in memory, so limits are per process.
- Since v0.1.7 a static build's header capture is not limited and gets no
RateLimitheaders.
elagoht/basicauth
github.com/Elagoht/collage-basicauth puts HTTP Basic authentication in front of a site — a staging deployment, a preview, a site not launched yet.
import "github.com/Elagoht/collage-basicauth"
Plugins: []collage.Plugin{basicauth.New(basicauth.Options{
Users: map[string]string{"team": "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"},
})},
{
"elagoht/basicauth": {
"realm": "Staging",
"protect": ["/"],
"skip": ["/healthz", "/readyz", "/_collage/"],
"disabled": false
}
}
- The application does not start with no users, unless
disabledis set.skipdefaults to/healthz,/readyzand/_collage/. - It covers what goes through collage's middleware: every page, document, action, mounted directory and plugin handler. A handler the application mounts itself with
app.Handleis bare — no middleware runs for it, this plugin's included — so on a "protected" staging host an API, a webhook or an upload handler mounted that way answers anyone. Mount itapp.Handle("/api/", api, collage.WithMiddleware())to put it behind the password;protectandskipthen apply to it as to any other path. - A failed bcrypt check is paid for every time, and anyone can send
Authorization: Basic x:y. On an exposed site list elagoht/ratelimitbefore basicauth, with a rule counting every method — its default rule leaves outGET, which is what a password guesser sends — so a refused guess is counted before the check is paid for:ratelimit.Rule{Methods: []string{"*"}, Rate: 5, Burst: 50}. - A password is written in plain text, as
sha256:and its hex, or as a bcrypt hash.COLLAGE_BASICAUTH_USERSadds users from the environment, keeping secrets out of files. disabled, orCOLLAGE_BASICAUTH_DISABLED=true, opens one deployment of the same binary — the production one.- Every authenticated response has
publicreplaced byprivateand carriesVary: Authorization, so a CDN in front does not hand a page to the next reader without asking. Serve it over HTTPS. - A static build's header capture is let through, so a deployed page does not carry a
401's headers. A build that writes files under a protected path warnsbasicauth-exported: a static host serves them without a password, so protect them at the host or leave them out of the build.
elagoht/oauth
github.com/Elagoht/collage-oauth signs a reader in with an OpenID Connect provider (Google, Microsoft, GitLab or any other with a discovery document) and, when you ask, keeps the provider's API tokens so the application can call the provider for the reader. The application keeps its own users: you answer with your user ID, and the plugin signs the reader in through elagoht/session, so session.RequireUser guards work unchanged.
import "github.com/Elagoht/collage-oauth"
Plugins: []collage.Plugin{
session.New(session.Options{}),
oauth.New(oauth.Options{
Providers: []oauth.Provider{{
Name: "google",
Preset: "google",
ClientID: "1234-abcd.apps.googleusercontent.com",
ClientSecretEnv: "GOOGLE_CLIENT_SECRET",
}},
OnLogin: func(ctx context.Context, id oauth.Identity) (string, error) {
return users.FindOrCreate(ctx, id.Provider, id.Subject, id.Name)
},
}),
},
<a href="{{oauthLogin "google"}}">Sign in with Google</a>
{
"elagoht/oauth": {
"providers": [
{ "name": "google", "preset": "google", "clientID": "1234-abcd.apps.googleusercontent.com",
"clientSecretEnv": "GOOGLE_CLIENT_SECRET", "offline": true }
],
"afterLogin": "/account",
"errorPath": "/sign-in-failed"
}
}
- It needs elagoht/session v0.3.0 or later, registered too: without it the login routes answer
500.collage plugin add elagoht/oauthadds elagoht/session first.OnLoginandStoreare code, so set them in Go. The secret and the key stay in the environment: the file names the variables, withclientSecretEnv,keyEnvandpreviousKeysEnv(since v0.2.0;key,previousKeysandOptions.KeyHexare gone, and an old configuration stops at start). - Since v0.3.0 the key is read from
OAUTH_KEY, and the previous keys fromOAUTH_PREVIOUS_KEYS, when neitherkeyEnv/previousKeysEnvnor the Go options set them: putOAUTH_KEY=(openssl rand -hex 32) in.env.developmentand where production runs whenStorekeeps tokens. These may be empty; a key in them that is not hex stops the application. - The routes are
{prefix}/{name}/loginand{prefix}/{name}/callback(prefix/auth),GETonly. Register{origin}/auth/google/callbackwith the provider: the origin isConfig.BaseURL, or what an origin resolver such as elagoht/tenant says for the request's host, so a multi-tenant site registers each host's. - An
issuermust behttps(plainhttponly tolocalhostor a loopback IP), or the site does not start; a discovery document naming an endpoint that is not ends the sign-in withunavailable. Token and revocation calls never follow a redirect. Keep elagoht/session'ssameSiteat"lax", its default: with"strict"the session cookie misses the provider's return, and a reader's session is replaced rather than signed in. - The pending sign-in is a cookie of its own (since v0.3.1), not the session:
collage_oauth,Path=/auth/<provider>/(under the prefix) so it reaches that provider's two routes and never a page, ten minutes,HttpOnly,SameSite=Lax,Secureover HTTPS, and deleted by the callback whatever its outcome. Anybody can start a sign-in, and a session is signed, lastsmaxAgeand turns the page cache off for whoever carries it: before, one anonymousGETof the login route handed anybody such a cookie. Now only a successful callback starts a session; a failed sign-in starts none. Anextthat would take the cookie past 4096 bytes ends atafterLogin. Nothing to change in configuration; a sign-in in progress during the upgrade fails withstate, and sessions an earlier version minted this way stay valid untilmaxAgeunless the session key is rotated. - The
microsoftpreset alone accepts any Entra ID tenant and any personal Microsoft account. Setissuerto one tenant's (https://login.microsoftonline.com/<tenant-id>/v2.0) to admit only it: a configured issuer is matched exactly. Microsoft sends noemail_verified, soEmailVerifiedis false for it.offlineasks a provider without a preset for theoffline_accessscope. - A sign-in uses
state, anonceand PKCE, checks the id_token's claims, gives the session a new ID (or starts one), and sends the reader tonext, checked withcollage.SafeRedirectand written as checked. A failure leaves no one signed in:errorPathgets?error=<code>(state,expired,denied,rejected,exchange,token,unavailable), or the site's status page is shown. - Key accounts on
Provider+Subject, and trust the e-mail only whenEmailVerifiedis true: matching an account by an unverified address lets one reader take over another's. - With a
Storeand a key (at least 32 bytes:Options.Keyfrom Go, or hex in the variablekeyEnvnames) the tokens are kept sealed with AES-256-GCM, andplug.Client(ctx, userID, "google")returns an*http.Clientthat sends the user's token and refreshes it.errors.Is(err, oauth.ErrNotLinked)means send the reader through sign-in again;Revokeunlinks. To rotate the key, move the old one toPreviousKeys(or the variablepreviousKeysEnvnames, comma-separated hex). The token goes only to the host it was first sent to, or its subdomains. - Limits: no GitHub (not OpenID Connect), no account linking, and the id_token's signature is not checked (it comes from the token endpoint over TLS, which OpenID Connect Core allows). Refresh coalescing is per process. A guard's or an action's redirect stays unchecked: only
nextis.
elagoht/fail2ban
github.com/Elagoht/collage-fail2ban bans clients that probe or brute-force a site. It counts strikes per client in named jails, and a client that reaches a jail's limit gets a plain 403 for the length of the ban.
import "github.com/Elagoht/collage-fail2ban"
bans := make(chan fail2ban.Ban, 100) // read by a goroutine of yours that batches alerts
f2b := fail2ban.New(fail2ban.Options{
OnBan: func(b fail2ban.Ban) {
select {
case bans <- b:
default: // full: drop it rather than block the request
}
},
})
Plugins: []collage.Plugin{f2b /* , the rest */},
{
"elagoht/fail2ban": {
"jails": {
"probe": { "banTime": "6h" },
"notfound": { "disabled": true }
},
"allow": ["203.0.113.7", "10.0.0.0/8"],
"ipv6Prefix": 48
}
}
- It uses
collage.Duration,Server.TrustedProxies,collage.ClientIPand aRequestHookthat sees requests collage rejects before routing. List it first inConfig.Plugins, afterelagoht/healthwhen that is used, so its ban check runs before the other plugins' middleware and health's probes are not refused by a ban.elagoht/accesslogmay go before it: it only writes the line, and listed first it logs a ban's403with its byte count (listed later it still logs the refusal since accesslog v0.3.0, without one). - When the client cannot be told from the forwarded chain (an entry that is not an address) and the connection's own address,
RemoteAddr, is used instead, the plugin logs it once, at Warn (since v0.2.1). Limiting is unchanged. - Behind a reverse proxy or a CDN, set
Server.TrustedProxies. Without it the proxy is the client: one scanner gets your proxy banned, and with it every visitor. List every hop, a CDN's published ranges included. If you forget, a request from a loopback or private address that carriesX-Forwarded-Forbut whoseClientIPis still that address is not counted, and one Warn saysTrustedProxiesis probably missing. A client is an IPv4 address, or an IPv6/64. ipv6Prefix(since v0.3.0) sets how many leading bits of an IPv6 address name the client: 32 to 128, 64 by default; IPv4 clients are always one address. One holder of a/48— a free tunnel-broker allocation, or a server's — has 65536/64s, each with strikes and a ban of its own.48makes the whole/48one client, so its strikes add up and its ban covers all of it, at the cost of banning everyone else in it;128is one address. A value outside the range stops the application from starting. An address inallowis never refused, even inside a banned block, and aBan'sPrefixis the block's.- The
probejail (3 strikes in10m, banned for1h) strikes on a request for a probe path (/.env,/.git/,/wp-login.phpand the like, and anywhere a segment starting with.envor a.gitsegment; add your own withprobePaths) or one collage rejects early, with an encoded slash or a./..segment. A probe path your site really serves as a page, document or action is not counted, unless it answers404or another error. Thenotfoundjail (50 in1m,10m) strikes on any other404, except a mount's. A browser's subresource request (Sec-Fetch-Destsuch asimageorscript) never strikes, nor does a request markedSec-Fetch-Site: cross-site(a no-cors fetch, a hidden iframe, a link from another site). That keeps a page on another site from getting your readers banned, in browsers that send these headers; a page on a subdomain of yours, or user content on your own origin, using an iframe or a fetch still counts. A scanner forging these headers goes undetected. A jail of your own strikes only onReport; override any by name, or turn it off with"disabled": true("off"until v0.2.0). Durations are strings —"10m","1h30m"— and a bare number such as"banTime": 3600stops the application, naming the key. - A repeat ban doubles, up to
maxBanTime(24h). A banned client gets a plain403 Forbidden, never the site's error page. Collage's own404or redirect for an encoded-slash or dirty-path request still reaches it. - The ban is middleware. A handler mounted with plain
app.Handleruns none, so a banned client keeps full access to it,/api/login brute force included, though its probes there still count. Mount itcollage.WithMiddleware()to cover it; see No middleware, unless you ask. - Call
Report(r, "login")on a failed login.Forgive(r, "login")clears the strikes, but is only safe when the success is for the account whose password was being guessed: forgiving any success lets an attacker with their own account guess without limit. Failures age out afterfindTimeanyway.allowlists addresses and ranges never counted or banned.Ban,UnbanandBansare the manual API (Bannever shortens a ban);OnBan(Go only) is called after each ban, maybe thousands of times in a distributed scan, so never notify per ban synchronously. - Bans are per process and in memory: instances do not share them and a restart clears them. In dev mode nothing happens unless
inDevelopmentis set. It reacts after strikes; it does not replaceelagoht/ratelimit. maxTracked(10000) bounds the strike counters, dropping the client struck longest ago;maxBans(10000) bounds the ban records. Since v0.3.0 a live ban is never evicted: at the cap only a ban that has ended (kept so a repeat ban doubles) makes room. While the table is full of live bans a new offender is not banned — its strikes are kept, and it is banned as soon as a ban ends — and aWarnat most once a minute saysfail2ban: the ban table is full;Banfrom Go is refused the same way. Before, an attacker could lift its own ban by gettingmaxBansother addresses banned. RaisemaxBans, or setipv6Prefixto48when the offenders are the/64s of one/48.
elagoht/consent
github.com/Elagoht/collage-consent adds a cookie-consent banner, holds scripts and iframes back until their category is granted, and gives the page a small JS API to read the visitor's choice. On the paths you list, the server can read the choice too.
import "github.com/Elagoht/collage-consent"
Plugins: []collage.Plugin{consent.New(consent.Options{})}, // configured from plugins-config.json
{
"elagoht/consent": {
"version": 1,
"categories": [
{ "name": "necessary", "required": true },
{ "name": "analytics" },
{ "name": "media" }
],
"text": {
"title": "Cookies", "body": "We use cookies to measure visits and to show embedded media.",
"accept": "Accept all", "reject": "Reject all", "save": "Save choices", "settings": "Choose",
"placeholder": "This content loads from {host}.", "allow": "Allow {category}",
"categories": { "necessary": "Necessary", "analytics": "Analytics", "media": "Embedded media" }
},
"locales": {
"tr": { "title": "Çerezler", "accept": "Tümünü kabul et", "reject": "Tümünü reddet" }
},
"policyURL": "/privacy",
"maxAgeDays": 180,
"serverPaths": []
}
}
It needs
{{hoist "head"}}in the layout. Without that marker nothing appears and nothing gated ever runs.Consent is decided in the browser. Every visitor gets the same HTML, so the page cache works as before.
versionasks every visitor again when you bump it. Arequiredcategory is always granted and never written to the cookie.textis the default locale's wording and must label every category;localesholds the others, which fall back totextkey by key (since v0.2.0; the oldtext: {"en": {…}}shape stops the application, naming the locale key).Mark up what needs consent so it is inert as written. A granted category turns a gated script into a real one, in document order, and gives a gated iframe its
src. Until then the iframe has a placeholder button, and markup added later by a fragment swap or a router is gated too:<script type="text/plain" data-consent="analytics" src="https://example.com/a.js"></script> <iframe data-consent="media" data-src="https://www.youtube-nocookie.com/embed/…" title="…"></iframe>A gated script cannot be a module. Taking a category back after its content has run reloads the page.
The JS API is
collageConsent.get()(the granted categories, sorted),collageConsent.set({ analytics: true }),collageConsent.open(), and acollage:consentevent ondocumentafter every save. An element withdata-consent-openreopens the banner. The banner is a<dialog>themed with--consent-*custom properties.Server side, list the paths in
serverPaths(whole segments:/shopcovers/shop/cart, not/shopping), then callconsent.Granted(rc, "analytics")in a data handler there. The page cache keeps one entry per choice, not per cookie. OutsideserverPaths, in a static export and in a build's capture,Grantedanswers false (a required category: true). Every response on those paths carriesVary: Cookie, which most CDNs will not cache, so list only pages whose HTML must differ. Never list a stream path: collage-live's/_live/and/_collage/are never varied.The choice is kept in the first-party cookie
collage_consent, readable by the script, so never set it from the server or asHttpOnly.GPC (
navigator.globalPrivacyControl) leaves every optional box unticked, and Accept all still grants everything. Do Not Track is not read.Content-Security-Policy: the script tag has no nonce, so
script-srcneeds'self'; a policy that is nonce-only or relies on'strict-dynamic'blocks it. The banner's stylesheet is built by the script, sostyle-srcmust allow its hash, which the plugin's README keeps current ('unsafe-inline'also works). A gated inline script needs its ownnonceor a'sha256-…'of its text inscript-src.With collage-live, a pushed fragment passes the middleware for its own path: on a path
serverPathscovers, it reads the reader's own choice and is rendered for that reader, never shared. A static export writes the script beside the pages and decides in the browser, so exported pages always render as "not granted" on the server.Grantedreads the configuration of the App it renders for (since v0.2.0; before, the last App initialised), and is false without a render context, even for a required category. For analytics, setconsentCategoryon elagoht/analytics.
Live updates
Keeping parts of a page current in the browser, without a framework on the client.
elagoht/live
github.com/Elagoht/collage-live keeps parts of a page current in the browser. It serves a small client script that refreshes the fragments a page opened with WithFragmentPath — on an interval, or when the server pushes a change over an event stream.
import (
client "github.com/Elagoht/collage-client"
live "github.com/Elagoht/collage-live"
)
Plugins: []collage.Plugin{client.New(), live.New(live.Options{})},
{
"elagoht/live": { "prefix": "/_live/", "noStream": false, "keepAlive": "25s", "maxFragments": 32, "maxStreamAge": "0s" }
}
<head>
{{liveClient}}
</head>
<section data-collage-fragment="{{fragmentURL "home" "cpu"}}" data-collage-interval="2s">
{{slot "cpu"}}
</section>
<section data-collage-fragment="{{fragmentURL "home" "disks"}}" data-collage-push>
{{slot "disks"}}
</section>
- It must go in
Config.Plugins: it adds{{liveClient}}, which the layout calls to include the client. It needs elagoht/client v0.2.0: every answer goes into the page through collage-client'scollage.put.collage plugin add elagoht/liveadds client too; without it,collage.Newfails.{{liveClient}}writes client's script ahead of its own, so the layout does not change, and one that also calls{{clientjs}}loads it once. - A transport of another plugin, such as elagoht/websocket, calls
UseTransportfrom itsConfigureas well as itsInit; the last call wins (v0.5.2). keepAliveandmaxStreamAgeare duration strings (collage.Durationinlive.Options): a number, a negative duration or a negativemaxFragmentsstops the application, andnullleaves the default. Since v0.5.0live.New()andlive.NewWith(live.Config{…})are onelive.New(live.Options{…}).- The page owns the container and the fragment owns what is inside it.
data-collage-intervalfetches on an interval,data-collage-pushtakes the fragment from the stream,data-collage-swap="morph"patches the DOM in place with collage-client's morph, anddata-collage-targeton a form submits it withfetchand puts the answer into an element — on a success, or on a422, which is how an action says a submission did not validate: it answers the form's fragment again, with the errors, and status 422 (see Forms and actions). Any other failure leaves the target as it was and marks it stale. Since v0.2.1 a form whose action redirects navigates in one request, with collage'sCollage-Fetch. - Since v0.6.0 the morph is idiomorph's, which matches elements by id. The old one matched them by position, so an item added at the top of a list rebuilt every item after it, and a field being typed into lost its text and focus. A focused field still keeps its value, but a focused
<select>'s options now take the server's.collage:swapcomes from collage-client, withdetail: { url: null, mode, inner: true }. - The client sends the
ETagit holds and leaves the DOM alone on a304, adds what the fragment hoisted to the head once by its key, stops in a hidden tab, and backs off when a request fails, marking the elementdata-collage-stale. A pushed copy carries the same ETag a poll would get, so one the client already holds is not sent again. - Holding an element still (since v0.3.0). While the reader is in the middle of something, a drag, a menu held open,
collageLive.pause(el)holds the element: polls, pushes and form answers keep arriving, but only the latest is kept, andcollageLive.resume(el)puts it in. An element inside a fragment names that fragment, so the list a drag started from holds the board around it; pauses nest, and a held element carriesdata-collage-paused.collageLive.put(el, html)puts in an answer the page fetched itself, an action's fragment, the way a form's answer is put in; patching the DOM directly would leave the client believing it still shows what it last put in. The README has a drag-and-drop example. - Animating a swap (since v0.4.0). A view transition has to begin before the DOM changes, and
collage:swapfires after.data-collage-transitionputs every answer in insidedocument.startViewTransition— pushes, polls, form answers andputalike — so cards that keep theirview-transition-namefrom one answer to the next slide to their new places; without the API, or underprefers-reduced-motion: reduce, the answer goes in at once. For more control,collage:before-swapfires on the element just before it changes: a listener that callspreventDefaultrunse.detail.swap()itself, inside its own transition, naming the elements that should move before and after. A lateswap()after a newer answer does nothing, and one called while the element is held waits for the resume. The README has the example. - One connection per browser. A browser holds at most six connections to one origin over HTTP/1.1, across all its tabs, so since v0.2.0 the client opens the stream from a shared worker that every tab of the site shares. Where there is no shared worker, each tab opens its own and closes it while hidden. Since v0.2.1 a tab coming back from the back-forward cache receives pushes again; the worker forgot it when it left.
- While the stream is down, pushed elements are marked stale; after three failed connections they are polled every five seconds, and the stream is tried again every minute.
- Pushing is tag-based. When the application invalidates a tag, the plugin re-renders every open fragment that depended on it and sends it down the stream; invalidating is the whole API.
- Sampled data — CPU load, a queue's length — is pushed by invalidating on a timer, one tag per fragment. Mark such a fragment
Shared(), notStatic(), so that collage renders it once per change rather than once per tab while its page stays dynamic; several fragments reading one measurement fetch it throughcollage.Cachedwith no tags, so that one fragment's tick does not re-render the others. A fragment that is notSharedis rendered for each connection, andCached, with the data cache on, keeps what it fetches fetched once. The README walks through a system monitor. - Every push is made for one connection, with that connection's own request, and sent to it alone: it is a request to the fragment's URL, which the application's and every plugin's middleware answer, then the guards. A reader one of them refuses — a session revoked on the server, changed credentials, a ban — is sent a stale message instead of the fragment, never one no guard covered. The render itself is still made once per change, which collage shares between the readers it admits; a rate limit counts each push as a request.
- A form in a pushed fragment is accepted. Every render after a connection's first carries a token its forgery cookie verifies.
- A connection renders with the cookies it was opened with; with signed, stateless cookies,
maxStreamAgecloses it after that long, and the client reopens it at once with the cookies it holds then. - The stream is served at
<prefix>stream/. A compression middleware of your own should leavetext/event-streamalone, or the stream arrives only when it ends. WithnoStreamthe client only polls, and nothing is pushed over any other transport either.
elagoht/websocket
github.com/Elagoht/collage-websocket carries collage-live's pushed fragments over a WebSocket instead of an event stream.
import (
client "github.com/Elagoht/collage-client"
live "github.com/Elagoht/collage-live"
"github.com/Elagoht/collage-websocket"
)
Plugins: []collage.Plugin{client.New(), websocket.New(websocket.Options{}), live.New(live.Options{})},
collage plugin add elagoht/websocketadds collage-live and collage-client too, and puts websocket before live. The plugin finds the application's live plugin by itself, wherever it is listed; without one,collage.Newfails. It needs collage-live v0.6.0 and collage-client v0.2.0 or later.- Nothing else changes: the layout still includes
{{liveClient}}, which now tells the client to connect here, and elements still saydata-collage-push. collage-live stops serving its event stream. The WebSocket is opened from the same shared worker, so every tab still shares one connection. - The push settings are live's. The WebSocket is served at live's
prefixplusws/(/_live/ws/by default), pinged every livekeepAlive, and closed after live'smaxStreamAge; with live'snoStreama connection is refused with the site's own not-found page (404; a plain-text 404 before v0.4.1).PathandPingare gone, andpathorpingin its configuration is an unknown key. - Usually you do not need it. Pushing fragments is one-way, which is what an event stream is for: it needs no dependency and reconnects by itself. This plugin is for deployments where streams are what breaks — a proxy that buffers them, a platform that limits them. It is the one piece of the live stack with a dependency,
github.com/coder/websocket. - A connection carries the reader's cookies, so by default only a page from the site itself may open one;
originPatternsnames other hosts whose pages may:
{
"elagoht/live": { "prefix": "/push/", "keepAlive": "20s", "maxStreamAge": "1h" },
"elagoht/websocket": { "originPatterns": ["admin.example.com"] }
}
elagoht/client
github.com/Elagoht/collage-client serves a tiny client script for the swaps a page does itself: element getters, and a fragment put in place, replacing the element or morphing it — fetched from its own URL, or handed over as markup. Everything else is left to plain JavaScript. elagoht/live puts its answers in with it too.
import client "github.com/Elagoht/collage-client"
Plugins: []collage.Plugin{client.New()},
<head>
{{clientjs}}
</head>
<!-- the fragment's own template: its root is what is swapped -->
<ul id="items" data-src="{{fragmentURL "list" "items"}}">
{{range .}}<li>{{.Name}}</li>{{end}}
</ul>
const names = collage.$$("li", collage.$("#items")).map((li) => li.textContent);
collage.replace("#items").catch(() => {}); // fetch data-src, put it in as outerHTML would
collage.morph("#items").catch(() => {}); // the same fetch, the DOM patched in place
collage.put("#items", html, { morph: true }); // markup in hand, no fetch
document.addEventListener("collage:swap", (event) => {
console.log(event.target.id, event.detail.mode, event.detail.url);
});
- It must go in
Config.Plugins: it adds{{clientjs}}, which the master layout calls once, in its<head>. There is nothing to configure. - The script defines
window.collageand nothing else.collage.$isquerySelectorandcollage.$$isquerySelectorAllreturned as an Array, both ondocumentunless a root is given as the second argument. collage.replace(target, url?)fetches a fragment and puts it in place oftarget, a selector or an Element, asouterHTMLwould.urldefaults to the element'sdata-src, where a page opened withWithFragmentPathputs{{fragmentURL}}. The answer takes the place of the whole element, so the element is the fragment's own root, its template's outermost tag. It resolves to the new element.collage.morph(target, url?)is the same fetch, with the DOM patched in place by idiomorph: elements that match are kept, so the field being typed into keeps its focus, its caret and what is typed in it, and a kept element keeps its scroll position. Another field of the morphed element takes the server's value, so morph a part of the page that does not hold a half-filled form, orreplaceit.collage.put(target, content, { morph?, inner? })(since v0.2.0) is the same swap without the fetch: markup, an Element or a DocumentFragment already in hand, such as what a form'sfetchanswered. It changes the page before it returns, returns the element now in the page, and throws where the others reject. Withoutinnerthe content must be one element; with it, the element stays and its children become the content, replaced or morphed. It checks no origin, asinnerHTMLdoes not, so never pass it what a visitor wrote. It aborts areplaceormorphin flight on the element.- After any of them, a
collage:swapevent bubbles from the element now in the page, withdetail: { url, mode, inner }:mode"replace"or"morph", andurlnullforput. - The request is a
GETwithCollage-Fetch: 1(collage.FetchHeader) and the page's cookies, as fragment paths and actions expect. The answer is inserted as trusted markup, sourlmust be on the page's own origin: another origin is refused before the fetch, and so is an answer a redirect brought from one. Never buildurlordata-srcfrom visitor input. - The newest call on an element wins. A
replaceormorphon an element that already has one in flight aborts the older call, which rejects as superseded, so a slow answer never lands on top of a newer one. - A failure leaves the page as it was. A target not in the page, no
urland nodata-src, another origin, a network error, an answer that is not 2xx or not a single element (a plain-text error body, a whole document, two elements side by side), an element taken out of the page while it was fetched, or a newer call: each fires no event and rejects with anErrorthat says which, such ascollage: morph /list/items: answered 500. A polling tick that may fail quietly ends in.catch(() => {}). Scripts inside a fetched fragment do not run, as withouterHTML. - With a Content-Security-Policy nonce from elagoht/secure, pass it:
{{clientjs cspNonce}}. A policy that allows'self'loads the script without it. Under a nonce-only or'strict-dynamic'policy, a layout that forgot it still works undercollage dev, where the policy only reports, and stops loading the script in production. - The script is served at
/_client/client.<hash>.js, cached for a year asimmutable, and loaded withdefer. A page that includes it twice, as{{clientjs}}and{{liveClient}}together do, runs it once. It is about 7 KB gzipped, idiomorph 0.8.0 (0BSD) included, and depends on nothing. - It neither polls, nor posts forms, nor takes pushes: for those, use elagoht/live. A form's post stays your own
fetch, its answer put in withput, as Update part of a page shows.
Assets and delivery
What the bytes a browser receives look like and how they get there: minified, resized, bundled, compressed, purged from a CDN, kept for offline reading, and deployed to a static host with their headers and redirects.
elagoht/minimizer
github.com/Elagoht/collage-minimizer strips whitespace and comments from rendered pages, from documents such as JSON endpoints, and from the files your mounts serve.
import minimizer "github.com/Elagoht/collage-minimizer"
Plugins: []collage.Plugin{minimizer.New(minimizer.Options{})},
{
"elagoht/minimizer": { "noCSS": false, "js": true }
}
- It must go in
Config.Plugins: it wraps the mounted filesystems, which happens while the application is built. - The zero
Optionsminifies HTML, JSON and CSS;noHTML,noJSONandnoCSSturn one off. JavaScript is off by default; turn it on with{"js": true}.minimizer.New(minimizer.Options{...})sets a starting point that the JSON section is decoded over. - Changed in v0.2.0:
New()andNewWith(Config{…})areNew(Options{…});"html": false,"json": falseand"css": falseare"noHTML": true,"noJSON": trueand"noCSS": true, and"html": trueand the like are simply left out. An old key stops the application at start. - Each language is covered wherever it appears (since v0.1.5): JavaScript a mounted script and an inline
<script>of JavaScript or a module, CSS a stylesheet and a<style>, JSON a JSON document and a<script>holding JSON —application/ld+json,importmap. A script of a type it does not know, such astext/template, stays verbatim. - It is a scanner, not a parser, and removes only what cannot carry meaning:
<pre>and<textarea>are kept verbatim, CSS strings are untouched, JavaScript keeps a line break wherever a semicolon may stand for it, and invalid JSON is returned as it was. A JavaScript line is joined only after a token no statement can end with —{ ( [ , ;or an operator such as=,&&or=>— and kept after a name, a closing bracket, a string or++(since v0.1.6; before, every newline was kept). - Mounted files are minified by wrapping the filesystem rather than the response, so
Rangerequests against a mount keep returning the right bytes.
elagoht/opti-image
github.com/Elagoht/collage-opti-image rewrites every <img> that declares a pixel width and height to a resized copy it serves itself, from its own mount.
import optiimage "github.com/Elagoht/collage-opti-image"
Plugins: []collage.Plugin{optiimage.New(optiimage.Options{})},
{
"elagoht/opti-image": {
"allowedOrigins": ["https://images.example.com"],
"webp": "auto",
"maxRecipes": 10000,
"maxDiskBytes": 1073741824
}
}
- It must go in
Config.Plugins. - Changed in v0.5.0: the output size is bounded. The size is the
<img>'s, and a page showing HTML its author did not write — sanitized comments that keepwidthandheight— lets a visitor declare one:width="50000" height="50000"on a 2×2 image was a 10 GB bitmap. An<img>declaring more pixels thanmaxPixels, or a side longer than 16384, is now left as it is, with one warning per render, and no name is minted for it; a recipe on disk from an earlier version asking for such a size is refused before its source is read. maxRecipes(10000) andmaxDiskBytes(1 GiB), since v0.5.0, bound what is kept.maxRecipescaps the images the plugin knows how to make, in memory and as<name>.jsonincacheDir; past it the least recently used is forgotten with its image, and its name is a 404 until a page names it again.maxDiskBytescaps the produced images on disk, least recently used removed first and made again when next asked for. Both count what an earlier process left in the directory. Before, a page putting a request's value into an<img>minted a name per request, kept forever. A static build lists the recipes after every page has rendered, so a site with more distinct images thanmaxRecipesneeds it raised; the warning is in the build's output.- An allowed origin that spells its scheme's default port,
https://cms.example.com:443, matches the same host's images whether or not the image's URL writes the port (v0.4.1); it was accepted at start but matched nothing. - Changed in v0.4.0:
New()andNewWith(Config{…})areNew(Options{…});allowedOriginsis a list of origin strings ("https://cms.example.com"), not{scheme, host}objects, each checked ascollage.ParseOriginchecks one;fetchTimeoutandoriginMaxAgeare strings such as"10s", and a bare number stops the application; a negative size, pixel count or quality is an error. - An empty
allowedOrigins, with noFiles, disables it. It never fetches from a host you did not list, and the scheme is part of the origin. - The site's own images come from its files (since v0.3.0):
optiimage.New(optiimage.Options{Files: map[string]fs.FS{"/static/": staticFS}})makes<img src="/static/avatar.png" width="256" height="256">a resized copy read fromstaticFS, with no request made — so the site does not fetch from its own public address, and a test or an export needs no network. The file's content is part of the image's name, so a changed file is a new name.Fileshas no JSON form. - An image from an origin is not
immutable(since v0.3.5). Its name is made from the recipe (URL, size, format), not from the content, so the origin can change the file under the same name. It is served withpublic, max-age=<originMaxAge>;originMaxAgeis a duration,"24h"by default, at least one second. An image of the site's ownFiles, whose name carries its content's digest, keepspublic, max-age=31536000, immutable. - Only images with both
widthandheightas pixel counts are rewritten; that declared size is the only honest target size there is. - Nothing is fetched during the render. The page links a content-addressed name such as
/_image/8f2a91c0b4e7d3a6.webp, and the image is fetched and resized the first time a browser asks for it. - A static export writes the images into its output, because they are served from a mount and every mount is copied after the pages have rendered.
webpisfalse(the default),true, or"auto", which uses WebP only where the image would otherwise be lossless. Produced images are kept in memory and in.cache/opti-imageby default (cacheDir);p.Purge()andp.PurgeSource(url)clear them.
optiimage.New(optiimage.Options{...}) sets a starting configuration in Go, which the JSON section is then decoded over key by key.
elagoht/bundle
github.com/Elagoht/collage-bundle bundles an application's JavaScript, TypeScript and CSS with esbuild when it starts, serves the output under content-hashed names, and rebuilds on an edit in development.
import "github.com/Elagoht/collage-bundle"
Plugins: []collage.Plugin{bundle.New(bundle.Options{
Dir: "assets",
Entries: []string{"app.ts", "app.css"},
})},
<link rel="stylesheet" href="{{bundle "app.css"}}">
<script src="{{bundle "app.js"}}" defer></script>
{
"elagoht/bundle": {
"dir": "assets",
"entries": ["app.ts", "app.css"],
"prefix": "/_bundle/",
"target": "es2020"
}
}
- It must go in
Config.Plugins: it adds{{bundle}}. minifyandsourcemapare""(left out: on outside development only forminify),"always"or"never". Changed in v0.2.0: they were booleans, andtrueorfalsenow stops the application at start;prefixno longer needs its trailing/.- The output is served from a mount at
/_bundle/, each file under esbuild's hash of its content and cached for a year. A name the build did not produce fails the render, as{{asset}}does for a missing file. - A production server whose bundle does not build does not start; in development the error is shown in the page and the server keeps running.
- The sources are read from disk when the application starts, not from an
fs.FS. A static build copies the mount, so the built site holds the bundle.
elagoht/favicon
github.com/Elagoht/collage-favicon makes a site's icons from one source image — favicon.ico, the Apple touch icon, the web app icons and the manifest that lists them — serves them at the root, and links them from every page's head.
collage plugin add elagoht/favicon
Since v0.3.0 that is all it needs. The icons are made from the site's own static/icon.png (and static/icon.svg, if there is one), and until there is one they are collage's. The settings are for the manifest and the colours:
{
"elagoht/favicon": {
"name": "The blog",
"themeColor": "#0f172a",
"backgroundColor": "#ffffff"
}
}
- The source is a square PNG, JPEG or GIF, ideally 512 pixels or larger.
- The source defaults to
/static/icon.png(since v0.3.0), and the SVG to/static/icon.svgwhen there is one: URLs of the site's own, read through the mount that serves them withHost.OpenMounted— from disk in development, from the copy the binary embeds once built.sourceandsvgname another file: one starting with/is a URL, read the same way; any other path is read from disk, or fromFS.SourceBytesandSVGBytesgive the bytes in Go. The start page key isstartURL. - A missing source never stops the application (since v0.3.0). With no file at the default URL it serves collage's icons and logs where to put one; a source that was named but is missing, cannot be decoded or is not square is a warning, with the same fallback. Only a colour that is not one stops it.
- The icons are made once at startup and served as static documents, so a static build writes them. An SVG is passed through, never rasterised.
- The links carry
?v=and a digest of the source, so a changed icon is a changed URL. It needs{{hoist "head"}}in the layout.
elagoht/compress
github.com/Elagoht/collage-compress compresses responses with Brotli and gzip, and writes .br and .gz files beside a static build.
import "github.com/Elagoht/collage-compress"
Plugins: []collage.Plugin{
compress.New(compress.Options{}),
secure.New(secure.Options{CSP: "..."}),
},
{
"elagoht/compress": { "minSize": 512, "gzipLevel": 6, "brotliLevel": 4, "types": ["application/x-yaml"] }
}
- Register it before any plugin that rewrites response bodies: the first plugin registered is the outermost middleware. elagoht/secure and elagoht/honeypot do not need this: they rewrite through
PersonaliseHook, inside every middleware.elagoht/healthmay be listed before or after compress. - Text types of at least
minSizebytes are compressed with the best encoding the request accepts.text/event-stream, a WebSocket and aRangerequest are left alone. - A compressed body is kept per ETag, so a page collage serves from its cache is compressed once per encoding, not once per reader. The ETag gains the encoding, and a conditional request still gets its
304. A response whoseCache-Controlhasprivateorno-store, such as a page carrying elagoht/secure's nonce, is still compressed but never kept (v0.1.3): it changes every time, so what was kept would never be reused. skipPrivate(since v0.1.8,falseby default) sends a response whoseCache-Controlcarriesprivateorno-storeuncompressed, against BREACH: when a response holds a secret, such as a forgery token, next to input the page reflects, its compressed size can leak the secret a character at a time. Nothing changes unless it is turned on. The README's BREACH section lists the other mitigations.- A static build writes a
.brand a.gzbeside every compressible file, for a host that serves precompressed files;noPrecompressturns it off. noCache(since v0.2.0) keeps no compressed bodies; it replaces a negativecacheBytes, which now stops the application.
elagoht/cdnpurge
github.com/Elagoht/collage-cdnpurge purges a CDN's copies of the pages collage invalidates: Cloudflare by zone, or any service that takes a list of URLs through a webhook.
import "github.com/Elagoht/collage-cdnpurge"
Plugins: []collage.Plugin{cdnpurge.New(cdnpurge.Options{
Cloudflare: &cdnpurge.Cloudflare{
ZoneID: os.Getenv("CF_ZONE_ID"),
APITokenEnv: "CF_API_TOKEN",
},
})},
{
"elagoht/cdnpurge": {
"webhook": { "url": "https://purge.example.com/", "tokenEnv": "PURGE_TOKEN" },
"window": "2s",
"retries": 4
}
}
- At least one of
cloudflareandwebhookis required, and an origin:Config.BaseURLor an origin resolver. - Changed in v0.3.0:
baseURLis gone (setConfig.BaseURL);forceisinDevelopment;cloudflare.apiTokenandwebhook.tokenareapiTokenEnvandtokenEnv, naming the environment variable that holds the token (APITokenandTokentake it from Go); durations are strings, and a negativeretriesis an error. An old key stops the application at start. - It purges exactly the paths an invalidation reached, under
Config.BaseURL, and purges each entry under its own host's origin, as anOriginResolverplugin names it; two hosts of one origin purge the URL once. A page the origin had not cached is not named, so make sure what the CDN caches, collage caches too. - Purges are batched for
window, sent off the goroutine that invalidated, retried on a429or5xx, and flushed on shutdown. A development server purges nothing unlessinDevelopmentis set. - The token never goes in
plugins-config.json, only its variable's name.
elagoht/offline
github.com/Elagoht/collage-offline serves a service worker, so the pages a visitor has read open again without a network.
import "github.com/Elagoht/collage-offline"
Plugins: []collage.Plugin{offline.New(offline.Options{
Precache: []string{"/"},
Fallback: "/offline",
})},
<head>
{{offlineScript}}
</head>
{
"elagoht/offline": {
"precache": ["/", "/about"],
"fallback": "/offline",
"assets": ["/static/", "/_bundle/"],
"maxPages": 100
}
}
- It must go in
Config.Plugins: it adds{{offlineScript}}, which installs the worker served at/sw.js. - Changed in v0.2.0:
versionisbuildID,inDevisinDevelopment, and a negativemaxPagesormaxAssets(keep everything) is an error — write a large number. Anassetsprefix covers whole path segments, with or without its trailing/. - Pages are fetched network-first and kept; static files under
assetsare served stale-while-revalidate; a page neither reachable nor kept gets thefallbackpage. A response markedno-storeorprivateis never kept, nor precached. - Private pages are not kept offline (since v0.2.1). A guarded page (
WithGuard) goes outprivate, no-cache, and basicauth marks its pagesprivate: a browser may keep such a page because it asks the server again before showing it, but the worker answers offline without asking anybody. Up to v0.2.0 it kept them and showed them offline to whoever used the device, with no guard asked. The cache version changes with the plugin's, so the first visit after the upgrade drops what the old worker kept. A page of your own that holds one reader's data says so withCache-Control: privateorno-store. - The worker's caches are named after a version that changes with each deployment, so a new build replaces what the old one kept. The build is
buildIDwhen set, and otherwise collage'sHost.BuildID—Config.Cache.Version, or a fingerprint of the executable. - In development
/sw.jsunregisters itself, unlessinDevelopmentis set. A static build writessw.js; keep a CDN from holding it long.
elagoht/deploy
github.com/Elagoht/collage-deploy writes the configuration files a static host reads from a static build's captured headers and redirects, so a site's redirects, caching and security headers survive the export.
import "github.com/Elagoht/collage-deploy"
Plugins: []collage.Plugin{deploy.New(deploy.Options{Target: "netlify"})},
{
"elagoht/deploy": {
"target": "netlify"
}
}
- The constructor is
deploy.New(deploy.Options{…}).targetisnetlify,cloudflare,vercelorgithub-pages; another value stops the application from starting. Left empty, it writes nothing, removes what the last export wrote, and warns. netlifyandcloudflareget_headersand_redirects,vercelavercel.json, andgithub-pagesone meta-refresh page per literal redirect and a.nojekyll, but no headers.- What a host cannot carry is a warning, never a rule that would redirect differently from the application: a 410 on every host; 307 and 308 written as 302 and 301 on Netlify; Cloudflare's rule limits; patterned redirects and every header on GitHub Pages. Vercel reads
vercel.jsononly when the output directory is deployed as the project (vercel deploy dist). - Headers are compacted into the fewest rules: what every file shares goes under
/*, what a directory shares under/dir/*, the rest at each file's path.Content-Typenever goes in a wildcard rule, and aContent-Typethe file's extension implies is left to the host. - It records what it wrote in
.collage-deploy.jsonand replaces those files on the next export into the same directory. It never overwrites a_headers,_redirectsorvercel.jsonit did not write: that is an error, and nothing is written. So is a control character in a redirect or a header. - Its redirects come from pages, documents and any
RedirectSourceplugin, such as elagoht/redirects; its headers from the capture, so build in production mode with the realBaseURL.
Operations and development
Checking what a site renders, seeing a render in development, and watching a running site: access logs, metrics, traces, analytics, error reports and health probes, and the scheduled jobs and background queues it runs.
elagoht/htmlcheck
github.com/Elagoht/collage-htmlcheck checks the HTML a site renders — structure, accessibility, what a search engine reads, what slows a page down, and the links between pages — and reports what it finds as findings.
import "github.com/Elagoht/collage-htmlcheck"
Plugins: []collage.Plugin{htmlcheck.New(htmlcheck.Options{})},
{
"elagoht/htmlcheck": {
"rules": { "img-dimensions": "off", "heading-order": "error" },
"titleMax": 60,
"descriptionMax": 160,
"pageBudget": 200000,
"ignoreLinks": ["/api/"]
}
}
- It has no
inProductionkey any more: findings on a production server went nowhere, so read them in development or in a static build. - In development each page is checked as it renders, and what is found is shown over the page. In a static build every page is checked, then the build as a whole — titles two pages share, links to pages the build did not write — and an error fails the build (see Static export). On a production server nothing is checked.
- It has 22 rules —
html-lang,title,img-alt,input-label,duplicate-id,heading-order,broken-linkand more — each aterrororwarnby default.ruleschanges a level or turns oneoff; a rule name it does not know stops the application from starting.htmlcheck.Rules()lists them all. ignoreLinksprefixes cover whole segments, with or without the trailing/, and must begin with/. A negativetitleMax,descriptionMaxorpageBudgetstops the application; 0 is the default (60, 160, no budget).
elagoht/devtoolbar
github.com/Elagoht/collage-devtoolbar shows a small panel on every page in development: which page rendered, in which locale, with what status, how long the render and each of its fragments took, which fragments failed, the dependency tags the render depended on, its Cache-Control and ETag, its size, and how many findings the checking plugins reported.
import "github.com/Elagoht/collage-devtoolbar"
Plugins: []collage.Plugin{
htmlcheck.New(htmlcheck.Options{}),
devtoolbar.New(devtoolbar.Options{}), // last
},
- Local clients only. The panel is drawn only for a client on the developer's machine or a private network (loopback, RFC 1918, IPv6 unique-local, link-local), as
collage.ClientIPnames it, so behind a proxy listed inServer.TrustedProxiesit is the forwarded client. Any other client gets the response untouched, and the first one logs a warning. Since v0.4.2 a local peer that forwards a non-local client — a proxy missing fromServer.TrustedProxies— gets no panel either, and the first one logs a warning naming that setting. - A tailnet or carrier-grade NAT address (
100.64.0.0/10) is not a private network, so a phone reaching the machine over Tailscale gets no panel. To show it to remote clients, turn the check off withdevtoolbar.New(devtoolbar.Options{AllowRemote: true}), or in the plugin configuration:
{ "elagoht/devtoolbar": { "allowRemote": true } }
- Position. The panel sits in the bottom-left corner. Since v0.5.0
positionputs it in another corner or in the middle of the top or bottom edge:top-left,top,top-right,bottom-right,bottomorbottom-left. In Go it isdevtoolbar.Options{Position: devtoolbar.PositionTopRight}; any other value stops the application at start-up.
{ "elagoht/devtoolbar": { "position": "top-right" } }
- Register it last: the findings it counts are those of the plugins that ran before it.
- On a server without
DevModeand in a static build it does nothing at all. The panel is added after the page cache, so what collage caches never carries it. - Since v0.2.3 a page written without a
Content-Typegets the panel too: the type is sniffed from the first bytes, as net/http does.
elagoht/accesslog
github.com/Elagoht/collage-accesslog writes one structured log line per request through slog, and gives every request an id its handlers can log with.
import "github.com/Elagoht/collage-accesslog"
Plugins: []collage.Plugin{accesslog.New(accesslog.Options{})},
{
"elagoht/accesslog": {
"skip": ["/_collage/", "/healthz", "/readyz", "/static/"],
"sample": 0.25,
"requestIDHeader": "X-Request-ID"
}
}
/_collage/, and /healthz and /readyz, the paths of elagoht/health, are skipped by default. A skip prefix covers whole segments, with or without the trailing /: /healthz does not cover /healthz-report. For a request answered before routing it is matched against the cleaned path, so /_collage/../admin is not skipped.
- Since v0.3.0 every request is logged, wherever it was answered. The plugin is a
collage.RequestHookas well as a middleware, and the hook logs the requests the middleware never reached: a ban anelagoht/fail2banlisted before it refuses, a request anelagoht/healthlisted before it sheds, a bareapp.Handlemount's response, and collage's own redirect of a dirty path (under the path as asked) or404for an encoded slash. Those lines have nobytes, and their responses noX-Request-ID. Expect more lines than before, a banned client's403s among them.accesslog.RequestIDworks in a bareapp.Handlehandler too. - List it first in
Config.Plugins, beforeelagoht/healthandelagoht/fail2ban— it only observes — and mount a handlercollage.WithMiddleware(), for the full line. A request whose handler panics is logged only when the middleware reached it, and the development reload stream and the dev server's refusal of an unknownHostare never logged. - The line has the method, path without its query, status, bytes, duration, client address, user agent, referer and request id, through the application's logger or
Options.Logger; a5xxis logged atERROR. - An
X-Request-IDthat looks like an id is kept, otherwise a new one is made; it is sent back and read withaccesslog.RequestID(ctx). samplelogs a fraction of2xxresponses, never of the rest. The client's address iscollage.ClientIP, so behind a proxy list it inServer.TrustedProxies; thetrustProxyandtrustedProxieskeys are gone, andX-Real-IPis never read.- The referer is logged without its query (since v0.1.11): its scheme, host and path only, with no query, fragment or user info, where a reset token or a session id can travel. One that does not parse is logged as
"".fullReferer: truelogs the header exactly as before.
elagoht/prometheus
github.com/Elagoht/collage-prometheus exports the framework's metrics to Prometheus — render and fragment timings, cache events, HTTP responses by route, invalidations — and serves them at /metrics.
import "github.com/Elagoht/collage-prometheus"
m := prometheus.New(prometheus.Options{Namespace: "collage"})
app, err := collage.New(&collage.Config{
Observability: collage.ObservabilityConfig{Metrics: m},
Plugins: []collage.Plugin{m},
})
{
"elagoht/prometheus": { "path": "/metrics", "tokenEnv": "METRICS_TOKEN" }
}
- The constructor is
New. Hand the one value over as both the application'sMetricsand a plugin: without the first nothing is measured, without the second nothing is served. - No label is taken from a request. Since v0.2.0
routeis whatcollage.RouteInfosays the request resolved to, as kind and name —/blog/aand/blog/bbothpage:post,/robots.txtdocument:robots, a mountmount:/static/, a 404other— so a crawler inventing paths cannot mint time series. Theroutesoption is gone: mounts and handlers are labelled by their prefix without it. - With a token, the scrape must send it as a bearer token. The token is a secret, so it never goes in
plugins-config.json:tokenEnvnames the environment variable that holds it, orOptions.Tokensets it from Go; atokenkey stops the application.path: "-"serves the metrics nowhere. The path is exact: one another route already answers, or one ending in/, stops the application from starting.
elagoht/otel
github.com/Elagoht/collage-otel turns collage's own spans into OpenTelemetry spans, and continues the trace a request's caller started.
import otel "github.com/Elagoht/collage-otel"
t := otel.New(otel.Options{Tracer: provider.Tracer("example.com/site")})
app, err := collage.New(&collage.Config{
Observability: collage.ObservabilityConfig{Tracer: t},
Plugins: []collage.Plugin{t},
})
{ "elagoht/otel": { "skip": ["/healthz"], "trustIncoming": "" } }
- The constructor is
New(otel.Options{Tracer: tracer}). As the tracer it turnscollage.http,collage.renderandcollage.fragmentinto spans; as a plugin it reads the caller's trace context from the headers, in aRequestHookthat runs before collage's own span. Each works alone. - With both, a request is one trace: a server span, a child of a trusted caller's, with
collage.httpunder it and the render and every fragment under that. The server span is named for the routecollage.RouteInforeports — the pattern a page, a document or an action was registered with (GET /blog/{slug},GET /feed.xml), the prefix of a mount or a handler. A request collage refused before routing (a dirty path's redirect, an encoded slash's404) names no route: its span keeps the method as its name and carries onlycollage.route.kind=rejected, so a scanner's paths never become span names. - Changed in v0.4.0: a client's trace context is continued only when it is trusted. A
traceparentis a claim anyone can send: continued from anyone, it lets an internet client decide what aParentBasedsampler exports and pick the site's trace ids, and itsbaggagereaches the application. By default the trace is continued only on a request whose connection comes fromConfig.Server.TrustedProxies; any other request's server span is the root of a new trace with a link to the caller's span, and its baggage is dropped.trustIncomingis""(that default),"always"(a service only other services reach — the old behaviour) or"never"; anything else stops the application. A CDN in front usually forwards the client'straceparentas it came, so striptraceparent,tracestateandbaggageat the proxy, or set"never", unless the proxy starts the trace. - Since v0.4.0 the method is bounded too: a method outside RFC 9110's and
PATCHis_OTHERinhttp.request.method, with the method as sent inhttp.request.method_original, andHTTPin the span's name (HTTP /blog/{slug}), so a client inventing methods does not invent span names. - The application owns the SDK: the provider, the exporter, the sampler and the propagator. Set a propagator, or every request starts a trace of its own.
skipprefixes match at a segment boundary, with or without the trailing/.url.schemefollowscollage.IsHTTPS, so it ishttpsbehind a trusted proxy that says so.
elagoht/analytics
github.com/Elagoht/collage-analytics adds an analytics snippet to every page's head — Plausible, Umami, GoatCounter or Google Analytics 4 — in production and in static builds, never in development.
import "github.com/Elagoht/collage-analytics"
Plugins: []collage.Plugin{analytics.New(analytics.Options{
Plausible: &analytics.Plausible{Domain: "example.com"},
})},
{
"elagoht/analytics": {
"plausible": { "domain": "example.com" },
"exclude": ["admin"],
"respectDNT": true,
"requireConsent": true
}
}
- It needs
{{hoist "head"}}in the layout. Its keys spell initialisms as Go does:respectDNT,goatCounter, Umami'swebsiteID, Google Analytics'measurementID. - Plausible, Umami and GoatCounter count visits without cookies. Google Analytics 4 sets cookies; use it with
requireConsent. - With
respectDNTorrequireConsent, a small loader served from the site decides in the browser, before any provider's script is fetched: nothing loads under Do Not Track or Global Privacy Control, or until the page callswindow.collageAnalyticsConsent(). excludenames pages that get no snippet.- With elagoht/consent on the site, set
consentCategory(say"analytics") instead ofrequireConsent. Every tag the plugin writes becomes atype="text/plain" data-consent="analytics"tag that the consent plugin runs once the visitor agrees to that category. The category must be one the consent plugin configures, or the tags never run. Google Analytics becomes two gated tags, its script and the inline call that configures it, with no loader. consentCategorycannot be combined withrequireConsent: the application does not start with both, nor with a name that is not lowercase letters, digits and hyphens.respectDNTstill applies and also honours Global Privacy Control, so a browser sending GPC loads nothing even after "Accept all". Under a strict Content-Security-Policy, Google Analytics' inline tag needs a'sha256-…'inscript-src(see the consent plugin's CSP notes above).
elagoht/tenant
github.com/Elagoht/collage-tenant serves one site to many customers, each on a host of its own: acme.app.com, globex.app.com or a customer's own domain. A cached page is kept per tenant, and every absolute URL the site writes follows the host.
import "github.com/Elagoht/collage-tenant"
Plugins: []collage.Plugin{tenant.New(tenant.Options{
Tenants: []tenant.Static{
{ID: "acme", Origin: "https://acme.app.com", Hosts: []string{"acme.app.com", "acme.localhost"}},
},
Resolve: lookupCustomDomain, // or a database, for hosts added at run time
})},
{
"elagoht/tenant": {
"tenants": [
{ "id": "acme", "origin": "https://acme.app.com", "hosts": ["acme.app.com"] }
],
"bypass": ["app.com"],
"ttl": "1m",
"unknownTTL": "1m",
"maxUnknownPerMinute": 600
}
}
- It needs
tenantsor aResolvefunction (Go only). - A host that is no tenant's is answered 404 with the site's own 404 page. A resolver that fails or panics is answered 503 with a
Retry-After, and that is not cached. A tenant is cached forttland, since v0.3.0, a "no tenant" answer forunknownTTL(both"1m", duration strings; a number is an error, and so is a negative one);maxHosts(10000) bounds how many hosts are remembered — since v0.2.1 tenants and "no tenant" answers each up to that many, so a flood of made-up hosts cannot push a real tenant out, and concurrent misses for one host share one resolver call — and a negative one stops the application.bypasshosts are served without a tenant. maxUnknownPerMinute(600, since v0.3.0) bounds the lookups a minute that may answer "no tenant" or fail: a client sending a new randomHoston every request used to make oneResolvecall each. Once the budget is spent, a host with no answer held is answered 503 with aRetry-Afterwithout callingResolve, until it refills, and a warning is logged once a minute. A host whose tenant is held, even past itsttl, is resolved whatever the budget, and a lookup that finds a tenant costs nothing, so a flood cannot take a known tenant's site down. A tenant's host never seen before can get that 503 during a flood: list it undertenants, or raise the budget.- A handler reads the tenant with
tenant.ID(rc), and code that holds only a context, such as a page'sStaticParams, withtenant.IDFromContext(ctx). Both are safe in a cached page.collage.BaseURL(rc)is the tenant's origin. elagoht/sitemap,feed,meta,ogimage,indexnow,cdnpurgeandrobotsfollow the host: the URLs they write are the tenant's origin.acme.localhostworks throughcollage dev. A static build has no host, so it renders without a tenant and warnstenant-no-host. A static export is the site ofConfig.BaseURL's host, rendered without a tenant; exporting per tenant is not supported. Its header capture is answered as that host, so it must be a tenant's or listed inbypass.
elagoht/errortrack
github.com/Elagoht/collage-errortrack reports server errors and panics to Sentry, or to any service that speaks its protocol (GlitchTip, self-hosted Sentry), with the standard library alone. It hears every 5xx and every recovered panic through ErrorHook and sends from a background goroutine, so a slow or down Sentry never slows a request.
import "github.com/Elagoht/collage-errortrack"
Plugins: []collage.Plugin{errortrack.New(errortrack.Options{
User: func(r *http.Request) errortrack.User {
return errortrack.User{ID: userID(r)}
},
})},
{
"elagoht/errortrack": {
"dsnEnv": "SENTRY_DSN",
"environment": "production",
"sampleRate": 1
}
}
- It reads the status and the request from
ErrorEvent, and needs aDSNorDSNEnv: startup fails without one, except in dev mode withoutinDevelopment, where nothing is sent and no DSN is needed. The DSN is a credential; keep it in the environment, not inplugins-config.json.timeout("5s") is a duration string; a number stops the application. - What leaves the server is limited: the error chain, a panic's stack, the route pattern rather than the raw path (only
scheme://hostwhen no route resolved, as for a middleware's panic; the raw path only withsendPath), query keys with[filtered]values, and six request headers, theReferercut to its origin unlesssendPathis set; the URL's scheme followscollage.IsHTTPS. Cookies,Authorization, the body and the client address are never sent (the address only withsendIP, ascollage.ClientIPnames it). A user is sent only as far as yourUsercallback returns one. - A message is sent as the failing code wrote it, and may carry a secret. Scrub it with
BeforeSend, which may edit the event or returnfalseto drop it. minStatus(500) lowers or raises what is reported; panics always are.sampleRate,perMinute(60) andqueueSize(100) bound the volume: what exceeds them is dropped and counted, never retried, and a429pauses sending.Capture(ctx, err)on the plugin you registered reports an error from outside a request, such as a background job. Nothing is sent in dev mode unlessinDevelopmentis set.
elagoht/health
github.com/Elagoht/collage-health answers a platform's liveness and readiness probes, and turns readiness false the moment collage starts draining for a shutdown, so a load balancer stops sending requests before the port closes. The endpoints are answered by its middleware, not by pages or documents, so a static export never contains them.
import "github.com/Elagoht/collage-health"
h := health.New(health.Options{})
h.Check("db", func(ctx context.Context) error { return db.PingContext(ctx) })
app, err := collage.New(&collage.Config{
Server: collage.ServerConfig{DrainDelay: 5 * time.Second, ShutdownTimeout: 10 * time.Second},
Plugins: []collage.Plugin{
h, // before anything that can refuse or answer a request
basicauth.New(basicauth.Options{}),
ratelimit.New(ratelimit.Options{}),
},
})
{
"elagoht/health": {
"livePath": "/healthz",
"readyPath": "/readyz",
"checkTimeout": "2s",
"cacheFor": "1s",
"details": false,
"maxInFlight": 0
}
}
- The durations are strings:
"checkTimeout": 2stops the application, naming the key; write"2s". /healthz(livePath) answers200 okwhenever the process serves a request, and runs no checks./readyz(readyPath) answers200 ok,503 unavailablewhile a check fails, and503 drainingonce a drain has started. Both answerGETandHEADwithCache-Control: no-store. A page registered at either path stops the application from starting; a document there is shadowed — the demo scaffold's/healthzdocument is never reached, so delete it or changelivePath.h.Check(name, fn)adds a readiness check, before the application starts. A probe runs every check at once, each under a context that ends aftercheckTimeout(2s); one that errors, panics or has not returned by then fails. A result is reused forcacheFor(1s), and probes arriving during a run share it. An error is logged, never sent; withdetailsreadiness answers JSON naming each checkokorfailing— leave it off where the names say too much.- Once a drain starts, readiness is
503 drainingand the checks are not run. SetDrainDelaya little longer than the readiness probe's period times its failure threshold. maxInFlight(0, no cap) sheds load: a request past the cap is answered503 overloadedwithRetry-After: 1at once, never queued. The cap is global, not per client — that is ratelimit's job — and the probes are never counted or refused.- List it before any plugin that can refuse or answer a request, so a probe always reaches it: tenant answers a probe's pod-IP host with
404, basicauth asks it for a password, ratelimit and fail2ban refuse it. compress and accesslog may sit before it. Since accesslog v0.3.0 a shed request is logged wherever accesslog is listed — listed after health, withoutbytes; listed before, in full. The probes stay out of the log through accesslog's defaultskip.
elagoht/jobs
github.com/Elagoht/collage-jobs runs scheduled jobs, on an interval or a cron expression, and typed background queues, only while the application serves. Jobs and queue workers start when ListenAndServe has bound its port, through ServeHook, and jobs stop being triggered when the drain begins. Nothing runs in collage build, in a plugin command, or in a test that only calls app.Handler() or app.Start().
import "github.com/Elagoht/collage-jobs"
j := jobs.New(jobs.Options{})
j.Every("refresh-feed", 15*time.Minute, refreshFeed).RunOnStart()
j.Cron("cleanup", "0 3 * * *", cleanup).Timeout(10 * time.Minute)
type Email struct{ To, Subject string }
mail := jobs.NewQueue(j, "email", func(ctx context.Context, m Email) error {
return send(ctx, m)
}, jobs.QueueOptions[Email]{Workers: 2, MaxAttempts: 3})
app, err := collage.New(&collage.Config{
Plugins: []collage.Plugin{j},
})
// In an action:
if err := mail.Enqueue(r.Context(), Email{To: to}); err != nil {
// jobs.ErrQueueFull, or jobs.ErrDraining once Shutdown has begun:
// tell the user to try again
}
{
"elagoht/jobs": {
"timezone": "Europe/Istanbul",
"disabled": ["cleanup"]
}
}
Keep the plugin in a variable, as j above: collage plugin add writes jobs.New(jobs.Options{}) straight into the list, where nothing can call Every on it.
- Every instance runs its own scheduled jobs. With N replicas behind a load balancer, a job runs N times per trigger; there is no leader election. Make such a job safe to run concurrently, or run it on one instance only, deciding that from the environment with
jobs.New(jobs.Options{Disabled: …})rather than withdisabledin a configuration every replica shares. - A job is a
func(ctx context.Context) error, defined before the application starts.Every(name, d, fn)runs it everyd, measured in elapsed time, so neither DST nor a wall clock set back changes it.Cron(name, expr, fn)takes a five-field expression — minute, hour, day of month, month, day of week — with*, values, ranges, steps and comma lists; no names, macros or seconds. When day of month and day of week are both restricted, a day matches if either one does, as in Vixie cron:0 0 1 * 1runs on the 1st and on every Monday. An expression that is malformed or can never match panics atCron. RunOnStart()also runs the job as soon as the plugin starts;Timeout(d)bounds each run's ctx, which the job must watch. A run in progress makes a trigger skip, so runs never overlap, and a failed or panicking run is logged at Error and not retried.- Cron expressions are read in
timezone(UTC). Across a DST change, a time in the skipped hour runs once, at the first instant after the gap; a time in the repeated hour runs once, on its first occurrence, for a schedule with a fixed hour; and a schedule whose hour field starts with*fires through both copies of the repeated hour, as Vixie cron does.disablednames jobs that do not run; an unknown name, like an invalid zone, fails startup. - The zone is read from the system's zoneinfo, which an image
FROM scratchdoes not have. Embed it, about 450 KB, withimport _ "time/tzdata"inmain. The scaffold's distroless image ships zoneinfo already. NewQueue[T]hands items of typeTto a function, with no type assertion.Workers(1) is how many items are handled at the same time,Capacity(1000) bounds how many wait, andMaxAttempts(1, no retry) is how many times an item is tried; each retry waits 1s, 2s, 4s… capped at a minute.OnFailureis called once with the last error.Enqueuenever blocks: it returnsErrQueueFullon a full queue, andErrDrainingonly once the plugin'sShutdownhas begun. The drain refuses nothing, since the server still serves then. Items live in memory and are lost if the process ends.- Shutdown finishes queued work. It waits for runs in progress and keeps taking queued items until every queue is empty. If its ctx ends first, it cancels the runs and waits one more second for them. Items left are logged at Warn as
dropped, and runs still going after the give-up asabandoned. With it, a stop can takeDrainDelay + ShutdownTimeout + 1s, which your platform's grace period must cover; see Deployment. - Register it after the plugins its work uses, so it shuts down first, while they still work. They share its shutdown deadline, so size
ShutdownTimeoutfor the queued work plus what they need. - Do not enqueue from data handlers: a build or a header capture runs them, never serves, and the item is never handled. A scaffolded project at least logs it as dropped, because its
main.goshuts the application down after a build. An application on its ownhttp.Serverstarts the plugin withj.Start(ctx); see Deployment.
elagoht/gesso
github.com/Elagoht/collage-gesso runs the lifecycle of a gesso application — a JSON API framework, the backend collage itself does not do — when collage serves it in the same process. The API's modules (a queue worker, a warmed cache) start when ListenAndServe has bound its port, through ServeHook; after collage's server has stopped, they stop in reverse order and the API's OnShutdown hooks run. Nothing starts in collage build, in a plugin command, or in a test that only calls app.Handler() or app.Start().
The plugin does not mount the API. Mount it with the application's own Handle, which keeps middleware off it, and give the plugin the same app — build it in newApp, before collage.New:
// main.go
api, err := gesso.New(gesso.Config{BasePath: "/api"}, notes.New(notes.Deps{DB: db}))
if err != nil {
return nil, err
}
api.OnShutdown(func(context.Context) error { return db.Close() })
app, err := collage.New(&collage.Config{
// …
Plugins: plugins(api),
})
if err != nil {
return nil, err
}
if err := app.Handle("/api/", api); err != nil {
return nil, err
}
// plugins.go: collage plugin add imports the plugin as gesso, so the
// framework takes another name here.
import (
"github.com/Elagoht/collage/pkg/collage"
gessoapp "github.com/Elagoht/gesso"
gesso "github.com/Elagoht/collage-gesso"
)
func plugins(api *gessoapp.App) []collage.Plugin {
return []collage.Plugin{
gesso.New(gesso.Options{App: api}),
}
}
- It needs gesso v0.5.0 or later. It takes nothing from
plugins-config.json; withoutOptions.App, startup fails.pluginsmay take arguments:collage plugin addanddelstill edit its list. - A page calls the API in the same process through an endpoint both sides declare:
notes.GetNote.Call(ctx, gesso.NewLocal(api), in, gesso.Bearer(token)). The call goes through the API's whole pipeline — authentication, guards, validation — and comes back as JSON or a problem, as over the network, without leaving memory. Moved to a process of its own, the API is called throughgesso.NewRemote(url, nil)instead, its ownRunhandles its lifecycle, and the plugin is dropped; the calling code does not change. - If the API's modules fail to start, the failure is logged at Error and the API answers every request
503, problem codeunavailable: its handlers would meet modules that are not running. - A request in flight is answered before any module stops, since collage stops its server before it shuts plugins down. The
OnShutdownhooks also run when the API never started — after a build — so a database they close is closed. - In a test built with
collagetest, nothing serves, so the modules do not start: handlers answer, and a worker's jobs run only when the test runs them.
Libraries that are not plugins
The plugins above are all registered in Config.Plugins. A library is a module your own code uses — from a page, or in the application's configuration — so there is nothing to register, no collage plugin add and no plugins-config.json section, and it is not counted among the forty-six plugins.
elagoht/paginate
The arithmetic of a pager, a numbered window (1 … 4 5 [6] 7 8 … 20), and links for a paged listing: path-paged ones a static export writes (/blog, /blog/page/2) and query-paged ones only a server answers (/search?page=3). It is used from a data handler and a template; see Pagination.
go get github.com/Elagoht/collage-paginate
FromPath(rc, last)reads the path parametern, the onePathNamedandStaticParamswrite, where v0.1 took the parameter's name;paginate.Versionis gone.
elagoht/redis
A Redis-backed collage.SharedCache: every instance of an application runs against one page cache and one collage.Cached data store, so an invalidation on any instance is seen by all of them. It is handed to Cache.Store:
go get github.com/Elagoht/collage-redis
import "github.com/Elagoht/collage-redis" // package redis
store, err := redis.New(redis.Config{URL: os.Getenv("REDIS_URL")})
if err != nil {
log.Fatal(err)
}
defer store.Close()
app, err := collage.New(&collage.Config{
Cache: collage.CacheConfig{Enabled: true, Store: store},
})
- It needs Redis 6 or later. A single node and Sentinel (through
Config.Client) are supported; Redis Cluster is not. Newnever dials Redis, so an application starts, and serves uncached, while Redis is down. A Redis error is a miss, never a failed request.- By default every deploy of a new binary starts with an empty namespace, and
MaxAge(seven days) bounds every key, the stale fallback included. The configuration, and how to run Redis for it, are in Caching and the library's README.
Plugins that write to the head
A plugin that contributes to the document head — structured data, meta tags, preload hints — does it by hoisting, the same mechanism fragments use for their titles and stylesheets. Hoisted content lands where the layout calls {{hoist "head"}}, and nowhere else:
<head>
<meta charset="utf-8">
{{hoist "head"}}
</head>
Without that marker, nothing appears. The plugin registers, runs, declares its block, and the block has nowhere to go. That is deliberate: a plugin that searched the HTML for </head> and spliced itself in would be deciding a layout question on your layout's behalf.
A layout from collage new already has the marker; a layout you wrote by hand may not. See Head and SEO for hoisting in general. Among the published plugins, jsonld, meta, ogimage, feed, favicon and analytics write to the head this way.
Where plugins run
Plugins see more than the pages a server renders:
- Cached pages are processed once. A plugin's changes to the HTML are made before the page is cached, so a cache hit serves the processed bytes without running the plugin again. A plugin that must run on every request — to inject a per-visitor value — cannot be combined with a cached page.
- Error pages go through the same render hooks, so your 404 is minified and annotated like any other page.
- A page an action answers with — the validation re-render of a form — runs
OnAfterRendertoo, so it is minified like the page aGETgets. See Forms and actions. - Documents — sitemaps, feeds, JSON — go through their own hook, so a minifier covers them too. See Documents.
- A static export runs the same render hooks as a served render, with each plugin started and configured first, so the exported site is the site the server serves. See Static export.
- A static build's header capture asks the handler for every written file when a
BuildFinishedHookplugin is registered, so middleware and the request hooks see a build's paths. A plugin that counts or limits traffic skips them withcollage.IsCapture(r.Context()). See Static export. - Not around a plain
app.Handlemount. A handler the application mounts withapp.Handleruns no plugin's middleware — no session, basicauth, rate limit, ban, access log, redirect or tenant — unless it is mountedcollage.WithMiddleware(). The request hooks still run for it, and a plugin's ownHost.Handleendpoints always run inside the middleware. See No middleware, unless you ask. - Work that runs only while serving — a scheduler, a queue worker — starts in
OnServe, which onlyListenAndServecalls: a static export, a plugin command andapp.Handler()never start it. See Writing a plugin.
Going further
Writing a plugin covers the plugin contract, every hook and what it may change, and a complete plugin with its tests.