render

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package render is HB Labs' own opinionated framework for serving static, multi-language sites with Go html/template. The goal is the convenience of Next.js (file-based routing, i18n, asset versioning, SEO files, OG images) without leaving stdlib + a hand-rolled CSS pipeline.

Project layout

Every site that uses this framework keeps the same on-disk shape; the loader walks subtrees by name, so renaming a directory means rewriting code in render. Don't.

myservice/
├── pages/                     html/template files (file-based routing)
│   ├── index.html.tmpl        → /{lang}/
│   └── about.html.tmpl        → /{lang}/about
├── partials/
│   └── _layout.html.tmpl      template named "_layout" — wraps every page
├── locales/                   one JSON per supported language
│   ├── es.json
│   ├── de.json
│   ├── en.json
│   └── nl.json
├── static/                    served at /static/, cached immutable
├── config/
│   └── config.yaml            framework config (see render/config)
├── seo/                       optional, e.g. seo/llms.txt
└── main.go

Conventions:

  • Pages with a leading "_" in the filename are skipped (treated as partials/layouts). The layout file therefore lives at partials/_layout.html.tmpl.
  • Page templates define a "content" block; the layout renders it via {{ template "content" . }}.
  • Every locales/<code>.json must be present for the codes listed in supported_langs — a missing file is a boot-time error.

Use the builder to load config from disk, layer in the code-only bits (FS, dev-mode toggle, og.Storage), and assemble the *Site:

//go:embed pages all:partials locales static config
var siteFS embed.FS

site, err := render.Init(siteFS).
    LoadConfig("config/config.yaml").
    Build()
if err != nil { log.Fatal(err) }

mux := http.NewServeMux()
site.Mount(mux)

The `all:partials` pattern is required because embed.FS skips underscore-prefixed entries by default; the framework relies on that underscore convention for partials, so we override the embed default and keep the convention.

Builder steps:

  • render.Init(fs.FS) — pin the source FS (embed.FS in prod, os.DirFS in dev).
  • .LoadConfig(path) — strict-mode YAML parse via web/render/config. Unknown keys / malformed files fail at boot, not at runtime.
  • .WithDev(bool) — flip the {{ devScript }} hot-reload helper. Typically `env == "local"`.
  • .WithOGStorage(og.Storage) — inject prod storage (MinIO/S3). Omit in dev to fall back to the in-process MemoryStorage.
  • .WithOGThemes(map[string]og.Theme) — register extra themes.
  • .Build() (*Site, error) — final step.
  • .BuildOptions() (Options, error) — same merge, no construction. Used by render/dev which builds a fresh *Site per request.

config.yaml

The on-disk surface is documented in web/render/config. Defaults live in render.New (one source of truth) — leaving a key out keeps the Go zero value, which the framework then defaults the same way it would for an all-in-code main.

Wiring from code (no YAML)

render.New is the lower-level API the builder calls into. Use it directly when every field is computed in code (typical for tests, migration jobs, embedded use cases that don't ship a config file):

site, _ := render.New(render.Options{
    FS:             siteFS,
    CanonicalHost:  "https://hblabs.co",
    DefaultLang:    "es",
    SupportedLangs: []string{"es", "de", "en", "nl"},
})

Sub-packages

  • render/config: YAML schema + Load() helper.
  • render/og: Open Graph image generator + storage backends.
  • render/dev: hot-reload wrapper for local development.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AssetLink struct {
	Relation []string        `json:"relation"`
	Target   AssetLinkTarget `json:"target"`
}

AssetLink mirrors the schema Google uses for Android App Links (https://developers.google.com/digital-asset-links/v1/getting-started).

type AssetLinkTarget

type AssetLinkTarget struct {
	Namespace              string   `json:"namespace"`
	PackageName            string   `json:"package_name,omitempty"`
	Sha256CertFingerprints []string `json:"sha256_cert_fingerprints,omitempty"`
}

AssetLinkTarget is the `target` sub-document of an AssetLink.

type Builder

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

Builder is the fluent counterpart to New: read declarative bits from YAML, layer in code-only bits (FS, og.Storage, og.Themes, dev mode), and assemble a *Site at the end. Use it from main when most of the site config lives in config/config.yaml:

//go:embed pages partials locales static config seo
var staticFS embed.FS

site, err := render.Init(staticFS).
    LoadConfig("config/config.yaml").
    Build()
if err != nil { log.Fatal(err) }

LoadConfig stashes any read/parse error; Build surfaces it. The builder returns *Builder from every chain step so the call site reads top-to-bottom even when an intermediate step failed.

For the all-in-code path, keep using render.New(Options{...}) — the builder is sugar over New, not a replacement. Both paths converge on the same defaulting logic inside New so behaviour stays in one place.

func Init

func Init(fsys fs.FS) *Builder

Init starts a Builder pinned to fsys — typically the //go:embed fs.FS rooted at the service directory. fsys is required; nil is treated as a configuration bug and surfaces from Build.

func (*Builder) Build

func (b *Builder) Build() (*Site, error)

Build assembles the merged Options and calls New. Returns the first stashed error (Init / LoadConfig) before attempting to build, so a failure surfaces with the original cause, not a confusing follow-on like "missing pages directory".

func (*Builder) BuildOptions

func (b *Builder) BuildOptions() (Options, error)

BuildOptions returns the resolved Options without calling New. Useful when a wrapper (e.g. render/dev) builds its own *Site per request and just needs the config plumbing — same YAML + With* merge as Build, no construction. Same error-stash semantics: LoadConfig / read failures surface here.

func (*Builder) Config

func (b *Builder) Config() *config.Config

Config returns the parsed *config.Config from the most recent LoadConfig call, or nil if LoadConfig wasn't called or errored. Useful for callers (e.g. main, render/dev.MountSite) that need to read non-render fields like QuietPaths without re-parsing the YAML.

The pointer is the loader's own — treat as read-only; mutations would diverge from the Options the builder already merged.

func (*Builder) LoadConfig

func (b *Builder) LoadConfig(path string) *Builder

LoadConfig reads + parses the YAML at path inside the builder's fs.FS and merges its values into the in-flight Options. Strict mode: unknown keys fail at parse, not at runtime. The merge preserves any earlier With* call (code wins over disk so main can override, e.g. flipping Dev based on env).

Errors are stashed on the builder and returned by Build, so the chain still reads cleanly:

site, err := render.Init(fsys).LoadConfig("config/config.yaml").Build()

func (*Builder) WithDataSchema

func (b *Builder) WithDataSchema(schema any) *Builder

WithDataSchema opts the loaded config.yaml `data:` section into strict-shape validation. Pass a pointer to a Go struct whose `yaml:"…"` tags describe the keys the service expects; at Build, the parsed Data map is re-marshalled and decoded into the schema with KnownFields(true). Missing required keys, unknown keys, and type mismatches surface as a boot error with the offending path, so a typo in config.yaml fails before the binary serves a single request.

Use it for any data tree that backs templates — typos in a `{{ data "myconfig.subconfig.name" }}` lookup would otherwise surface as a 500 on a single page rather than at boot. Leave unset when the data tree is truly free-form (prototype, ad-hoc content); the `data` helper still works, it just fails per-request instead of per-deploy when a key is missing.

The schema is only validated, never installed in place of Data — the helper continues to walk the map[string]any tree so template authors don't have to track which fields became typed.

func (*Builder) WithDev

func (b *Builder) WithDev(dev bool) *Builder

WithDev flips the Dev flag — typically driven from env (e.g. `HBL_ENV=local`) rather than from config.yaml so the same YAML can ship to every environment. Overrides whatever LoadConfig set (config.yaml has no `dev` field anyway, but keep the override shape consistent).

func (*Builder) WithExtraStatic

func (b *Builder) WithExtraStatic(extra map[string]fs.FS) *Builder

WithExtraStatic attaches additional static-asset subtrees to the builder. Each entry is mounted at /static/<prefix>/ with the same cache-immutable + content-fingerprinting policy as the service's own static. Use it to plug in shared brand/UI packages — see Options.ExtraStatic for the contract.

func (*Builder) WithFuncMap

func (b *Builder) WithFuncMap(fm template.FuncMap) *Builder

WithFuncMap attaches service-specific template helpers to the builder. Pass through from a service's main when its page templates need helpers the framework doesn't ship (e.g. a project catalogue). Framework helpers always win on name collisions — see Options.FuncMap.

func (*Builder) WithIconCatalog

func (b *Builder) WithIconCatalog(catalog map[string]string) *Builder

WithIconCatalog plugs in the `name → inner-SVG` catalog the framework's `{{ icon }}` / `{{ iconStroke }}` helpers fall back to when a name isn't overridden under config.yaml's data.icons. Pass web/uikit.IconSet here for the shared HB Labs catalog; clients shipping their own catalog plug that map in instead. nil keeps both helpers unregistered — services use `{{ data "icons.<name>" }}` to read the raw markup directly in that case.

func (*Builder) WithOGStorage

func (b *Builder) WithOGStorage(storage og.Storage) *Builder

WithOGStorage attaches the OG image storage backend. Required in production (MinIO/S3-backed); optional in dev where the in-process MemoryStorage default is fine. Has no effect when og.enabled is false in config.yaml.

func (*Builder) WithOGThemes

func (b *Builder) WithOGThemes(themes map[string]og.Theme) *Builder

WithOGThemes registers extra themes alongside og's built-in "default". Themes carry font.Face values that don't serialise, so they only ever come from code. nil = just the default theme.

func (*Builder) WithReady

func (b *Builder) WithReady(ready func(ctx context.Context) error) *Builder

WithReady attaches the readiness probe backing the auto-mounted GET /readyz endpoint. Code-only, like WithOGStorage: a readiness check is a live dependency probe, not YAML config. nil (or never calling this) keeps /readyz on healthz semantics — see Options.Ready for the contract.

type OGOptions

type OGOptions struct {
	// Enabled flips the pipeline on. Required because the zero
	// value of OGOptions otherwise looks indistinguishable from
	// "use defaults".
	Enabled bool

	// Brand is the line shown above the title in every card.
	// Typically the product / site name. Empty disables the brand
	// line in the rendered image.
	Brand string

	// URLPrefix is the route the handler mounts under. "" → "/og".
	// Trailing slashes are tolerated; the helper and resolver agree
	// on the trimmed form.
	URLPrefix string

	// Storage is where rendered cards live. nil → an in-process
	// MemoryStorage seeded at boot, sufficient for local dev. In
	// prod, pass the MinIO-backed Storage (packages/storageclient).
	Storage og.Storage

	// Themes registers extra og.Themes alongside the default. nil
	// means just the default theme; Cards then leave Theme="".
	Themes map[string]og.Theme
}

OGOptions configures the auto-mounted OG image pipeline. Zero value disables OG entirely — Mount won't register the handler and the {{ ogImage }} helper returns an empty string. Opt in with Enabled=true so an empty struct doesn't accidentally enable a bunch of defaults.

type Options

type Options struct {
	// FS is the embed.FS (or any fs.FS) rooted at the service directory
	// and containing pages/, partials/, locales/, static/.
	FS fs.FS

	// CanonicalHost is the absolute origin used in links, sitemap and
	// OG metadata. Example: "https://launch.hblabs.co".
	CanonicalHost string

	// DefaultLang is what we serve when the visitor has no cookie and no
	// recognisable Accept-Language header. Must appear in SupportedLangs.
	DefaultLang string

	// SupportedLangs lists the BCP-47-ish two-letter codes we serve. Each
	// must have a matching locales/<code>.json file.
	SupportedLangs []string

	// Brand is the site's identity name passed to layouts as
	// {{ .Brand }}. Also used as the default OG card brand when
	// OG.Brand is empty — one source of truth for the visible
	// product name across nav, footer, social previews.
	Brand string

	// Dev opts the site into development affordances. The only effect
	// today is the {{ devScript }} template helper emitting the
	// hot-reload <script> tag — everything else (file watching, SSE)
	// lives in web/render/dev. Layouts call {{ devScript }} in
	// every environment; in prod it's an empty string, in dev it's
	// the tag the dev wrapper expects.
	Dev bool

	// SEO controls the auto-mounted /robots.txt, /sitemap.xml,
	// /llms.txt, /security.txt, /.well-known/security.txt,
	// /.well-known/apple-app-site-association and
	// /.well-known/assetlinks.json endpoints. Zero value = every
	// endpoint enabled with sensible defaults; tweak per-field for
	// per-site customisation. See SEOOptions.
	SEO SEOOptions

	// OG configures the auto-mounted Open Graph image pipeline. Zero
	// value (Enabled=false) disables it; set Enabled=true to register
	// the /og handler and unlock the {{ ogImage }} template helper.
	// See OGOptions.
	OG OGOptions

	// FuncMap is an optional set of template helpers a service wants
	// exposed inside its .html.tmpl files alongside the framework's
	// own (T, asset, pageURL, canonical, ogImage, devScript). Use it
	// for service-specific catalogues — a list of projects, a menu
	// of features, anything where the alternative is repeating large
	// HTML blocks in the template or shoving structured data through
	// the flat locales map.
	//
	// Precedence: framework helpers always win. If a caller registers
	// a key that collides with a built-in (e.g. "T"), the built-in is
	// kept and the override is silently dropped — templates rely on
	// the framework helpers' signatures and letting a service shadow
	// them would surface as obscure runtime errors. Add new helpers
	// under names that won't collide; if you need to replace a
	// built-in, that's a framework-level change, not a service one.
	FuncMap template.FuncMap

	// Data is a free-form key/value tree exposed to templates via
	// the `{{ data "dot.path" }}` helper. Loaded from config.yaml's
	// `data:` section (see render/config), or populated directly in
	// code for tests / non-YAML callers. Leaves can be any YAML
	// scalar (string, int, bool, …); the helper stringifies them
	// before returning template.HTML so SVG bodies and other inline
	// markup pass through unescaped.
	//
	// Values come from operator-controlled YAML, NOT user input —
	// treat the leaves as trusted bytes; do not put visitor-supplied
	// content into this tree.
	Data map[string]any

	// IconCatalog optionally registers a `name → inner-SVG` catalog
	// that the framework's `{{ icon name size }}` / `{{ iconStroke
	// name size stroke }}` helpers resolve against. When non-nil,
	// New registers both helpers; the resolver looks up Data["icons"]
	// first (per-service extensions / overrides from config.yaml)
	// then IconCatalog (the shared catalog the service plugged in).
	// When nil, neither helper is registered — templates that need
	// icons either receive their catalog from a service-supplied
	// FuncMap or use `{{ data "icons.<name>" }}` to read the raw
	// markup.
	//
	// Generic map keeps render independent of any particular icon
	// package; services typically pass web/uikit.IconSet,
	// but a client that ships its own catalog just plugs that map
	// in instead.
	IconCatalog map[string]string

	// Ready optionally backs the auto-mounted GET /readyz endpoint
	// (the orchestrator's readiness probe, as opposed to /healthz
	// liveness). Return nil when the service can take traffic; any
	// error answers 503 with the error text. Code-only — a readiness
	// check is a live dependency probe (upstream API, database), not
	// YAML config. nil = /readyz mirrors /healthz semantics (always
	// 200 once the binary serves), which is correct for services
	// without a hard runtime dependency.
	//
	// The probe runs with a short timeout derived from the request
	// context, so implementations should honour ctx cancellation.
	Ready func(ctx context.Context) error

	// ExtraStatic mounts additional fs.FS subtrees alongside the
	// service's own static/ directory. Each entry's key becomes a
	// URL-path segment under /static/, and the fs.FS is served with
	// the same cache-immutable policy and content-hash fingerprinting
	// the framework already applies to static/.
	//
	// Use it to plug in cross-service shared assets — a UI kit, a
	// brand pack, fonts published from a single Go package — without
	// copying bytes into each service's embed:
	//
	//	import "github.com/hblabs-co/kit/web/uikit"
	//
	//	render.Options{
	//	    ExtraStatic: map[string]fs.FS{"uikit": uikit.FS},
	//	}
	//
	// Templates pull files via the standard asset helper, prefixed
	// with the same key — fingerprinting + cache-immutable headers
	// are identical to local static:
	//
	//	{{ asset "uikit/css/tokens.css" }}
	//
	// Prefix rules: non-empty, no slashes ("/" splits it into
	// directory segments which would break the mount). Collisions
	// with file names under the service's own static/ are not
	// detected; pick prefixes that won't clash (the empty prefix
	// would shadow everything, hence the validation).
	ExtraStatic map[string]fs.FS
}

Options configures a Site at boot. Most fields have sensible defaults for local dev so a service can spin up with just FS + SupportedLangs.

type SEOOptions

type SEOOptions struct {
	// Disable* lets services opt out of specific endpoints. Setting
	// any of these to true skips the mux registration entirely — the
	// path returns 404 from the catch-all instead.
	DisableRobots      bool
	DisableSitemap     bool
	DisableLLMsTxt     bool
	DisableSecurityTxt bool
	DisableAASA        bool
	DisableAssetLinks  bool

	// SecurityContact is the email shown in /.well-known/security.txt.
	// Empty → endpoint serves a placeholder + the renderer logs a
	// boot warning so the operator notices the misconfig before a
	// security researcher complains.
	SecurityContact string

	// PreferredLanguages overrides the default Preferred-Languages
	// header in security.txt. Empty → SupportedLangs is used as-is
	// (the languages we serve are the ones we accept reports in).
	PreferredLanguages []string

	// AppleTeamID + IOSBundleID drive
	// /.well-known/apple-app-site-association. Empty teamID logs a
	// warning at boot but the endpoint still serves a placeholder
	// JSON so AASA validators have something to point at.
	AppleTeamID string
	IOSBundleID string

	// AASAComponents lists the URL paths that should open the iOS
	// app via Universal Links. Empty → the renderer derives a
	// "/<lang>/*" component for every SupportedLang.
	AASAComponents []string

	// AndroidAssetLinks is the array served at
	// /.well-known/assetlinks.json. Empty → "[]" so scanners and
	// Android Studio's "App Links Assistant" don't 404 even when
	// no Android app exists yet.
	AndroidAssetLinks []AssetLink

	// LLMsTxt is the body served at /llms.txt. Non-empty → served
	// verbatim, bypassing the template. Empty → the embedded stub
	// template runs against the Site's seoContext.
	LLMsTxt string
}

SEOOptions configures the auto-mounted SEO endpoints. Zero value gets every endpoint enabled with sensible defaults; tweak per-field to customise. Disabling everything is supported for services where these endpoints don't make sense (a JSON-only API, a private admin surface).

type Site

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

Site is a configured render instance. Build with New, then Mount. One Site corresponds to one service binary's HTML surface.

func New

func New(opts Options) (*Site, error)

New parses templates and locales. Errors are wrapped so the caller can fail-fast at boot — a parse error in production means the binary should not start serving partial content.

func (*Site) Mount

func (s *Site) Mount(mux *http.ServeMux)

Mount wires the site's routes onto the given mux. Caller is free to register additional routes before or after this call (e.g. an API endpoint at /api/...). Order:

GET /healthz                → 200 ok (liveness)
GET /readyz                 → 200 ok, or 503 when draining or Options.Ready errors (readiness)
GET /static/...             → embedded assets, cached immutable
GET /                       → pickLang and 302 to /<lang>/
GET /<lang>/[<page>]        → render the matching page template
anything else               → 404

Directories

Path Synopsis
Package config is the on-disk configuration surface of the render framework.
Package config is the on-disk configuration surface of the render framework.
Package dev wires hot reload onto a render-based service for local development.
Package dev wires hot reload onto a render-based service for local development.
Package og generates Open Graph PNG cards on demand and caches them via a pluggable Storage so multiple pods don't redo the work.
Package og generates Open Graph PNG cards on demand and caches them via a pluggable Storage so multiple pods don't redo the work.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL