site

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: 25 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 site is the composition root for an HB Labs web service. One call to New does everything a typical main needs to stand up the framework:

  1. Reads config/config.yaml (env vars expanded, defaults merged).
  2. Builds the *render.Site (prod) or wraps it in a hot-reload *render/dev.Server (when EnvHBEnv is "local").
  3. Optionally builds the rules engine (web/rules/engine) from YAML pipelines embedded next to the service. In dev it wraps it with rules/dev so YAML edits hot-reload, in prod it builds once at boot.
  4. Mounts everything on a top-level mux: pipeline endpoints at the URLs declared in RulesOptions.Mounts, the render site at "/".
  5. Wraps the mux in the canonical middleware bundle: Secure → RequestID → AccessLog (with QuietPaths) → Recover.
  6. Returns the composed http.Handler ready to drop into system.RunForever, alongside the system.Module slice for the two dev hot-reloaders (nil-filtered: in prod the slice is all nils that RunForever silently drops).

Wiring from main:

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

handler, modules, _, err := site.New(site.Options{
    SiteFS: siteFS, // WatchRoot ".", ConfigPath "config/config.yaml", uikit mounted by default
    Rules: site.RulesOptions{
        PipelinesDir: "pipelines",
        Mounts: map[string]string{
            "/__rules/visitor": "visitor_flags",
        },
    },
})
if err != nil { log.Error("site", "err", err); os.Exit(1) }

modules = append(modules, system.NewServer(serverOpts))
system.RunForever(ctx, modules...)

Rules wiring is optional: leave Options.Rules zero and site behaves exactly like the render-only setup (no /__rules/* endpoints, no rules dev server).

Index

Constants

View Source
const (
	DefaultWatchRoot  = "."
	DefaultConfigPath = "config/config.yaml"
	// UIKitMount is the ExtraStatic key (URL segment) of the default
	// uikit mount: /static/uikit/...
	UIKitMount = "uikit"
)

Defaults applied by New to zero Options fields.

Variables

This section is empty.

Functions

func BannerExtras

func BannerExtras() []string

BannerExtras returns the banner lines that describe site-level runtime state main should surface in system.Boot's startup banner. Empty in prod; in dev it surfaces the hot-reload affordance so the operator sees it before the first request log line.

func BuildInfoFuncMap

func BuildInfoFuncMap() template.FuncMap

BuildInfoFuncMap exposes the binary's build stamp (system.ReadBuildInfo) to templates, typically for a footer:

buildVersion    → "v1.0.487"
buildTime       → "2026-05-25T18:23:00Z"
buildTimePretty → the same instant formatted for humans

The stamp is read once, when the map is built; all three functions return "" for an unstamped (go run) binary.

func MergeFuncMaps

func MergeFuncMaps(maps ...template.FuncMap) template.FuncMap

MergeFuncMaps returns a new FuncMap holding every entry of maps. Later maps win on a name clash, so a service passes the shared maps first and its own overrides last. Nil maps are skipped; the inputs are never mutated.

func New

func New(opts Options) (http.Handler, []system.Module, *config.Config, error)

New is the one-shot composition root. See the package doc for the full call shape and lifecycle.

Returns:

  • http.Handler: the composed handler, middleware already applied. Ready for system.NewServer.
  • []system.Module: dev hot-reloaders (render + rules). In prod all entries are nil; RunForever filters them automatically.
  • *config.Config: the parsed YAML so callers can read fields beyond what the middleware bundle consumes (CanonicalHost for external integrations, SEO config, etc.).

func UIKitFS

func UIKitFS() fs.FS

UIKitFS returns the shared design-system asset tree to mount under Options.ExtraStatic["uikit"]: the on-disk tree in dev (so an edit to a local kit checkout shows up on the next request, see uikit.DevFS), the embedded immutable copy otherwise.

Types

type Options

type Options struct {
	// SiteFS is the production source FS (typically the //go:embed
	// rooted at the service directory). Used as-is when EnvHBEnv
	// resolves to anything other than "local"; ignored otherwise.
	SiteFS fs.FS

	// WatchRoot is the on-disk source directory used in dev mode —
	// New wraps it with os.DirFS so file edits flow through the
	// dev wrapper without recompiling. Defaults to DefaultWatchRoot
	// (".", i.e. `go run .` from the service directory); ignored
	// outside EnvHBEnv "local".
	WatchRoot string

	// ConfigPath is the location of the framework config inside
	// whichever fs.FS render uses. Same path in both modes —
	// LoadConfig reads it from SiteFS in prod and from os.DirFS in
	// dev. Defaults to DefaultConfigPath.
	ConfigPath string

	// Rules wires the rules engine into the service. Zero value =
	// no rules engine, no /__rules/* endpoints. Set PipelinesDir +
	// Mounts to mount one or more pipelines.
	Rules RulesOptions

	// FuncMap is an optional set of template helpers the service
	// wants exposed inside its .html.tmpl files alongside the
	// framework built-ins. Threaded straight through to
	// render.Options.FuncMap, so collisions with framework helpers
	// (T, asset, pageURL, canonical, ogImage, devScript) are
	// silently dropped in favour of the built-in.
	//
	// Typical use: a service-local catalogue (e.g. {{ featuredProjects }}
	// and {{ projectsByCategory }} for a portfolio).
	// Leave nil for services that don't need extras.
	FuncMap template.FuncMap

	// ExtraStatic mounts shared asset subtrees alongside the
	// service's own static/. Each entry's key is a URL-path segment
	// (e.g. "uikit") that maps to /static/<key>/, with the same
	// cache-immutable + content-fingerprinting policy.
	//
	// Use it to consume cross-service asset packages — typically
	// github.com/hblabs-co/kit/web/uikit for the shared design-system
	// CSS — without copying files into each service's embed:
	//
	//	import "github.com/hblabs-co/kit/web/uikit"
	//
	//	site.Options{
	//	    ExtraStatic: map[string]fs.FS{"uikit": uikit.FS},
	//	}
	//
	// In templates, the standard asset helper resolves shared paths
	// the same way as local ones:
	//
	//	{{ asset "uikit/css/tokens.css" }}
	//
	// The uikit is mounted under "uikit" by default (UIKitFS); an
	// explicit "uikit" entry here wins, and WithoutUIKit opts out.
	ExtraStatic map[string]fs.FS

	// WithoutUIKit skips the default "uikit" ExtraStatic mount.
	WithoutUIKit bool

	// AdditionalImgSrc extends the framework's default CSP `img-src`
	// directive with extra origins. Use case: in dev the asset host
	// is `http://localhost:9000` (MinIO), which the default policy
	// (`img-src 'self' data: https:`) blocks because plain `http:` is
	// not in the source list. Pass the resolved origin here so
	// browser-loaded assets render without disabling CSP wholesale.
	//
	// Each entry must be a valid CSP source expression — typically
	// "scheme://host[:port]" (e.g. "http://localhost:9000") or a
	// scheme-only token like "https:" if a broader allow-list is
	// intended. In prod, leave empty: the default already permits
	// any HTTPS image origin via `https:`.
	AdditionalImgSrc []string

	// AdditionalFrameSrc extends the framework's CSP with a
	// `frame-src` directive so the service can embed third-party
	// iframes (Spotify episode embeds, YouTube, Vimeo, payment
	// widgets). Default policy has no frame-src, so default-src
	// 'self' applies — blocking every embedded origin. Pass an
	// explicit list here to opt in per service. Same grammar as
	// AdditionalImgSrc.
	AdditionalFrameSrc []string

	// DataSchema is an optional pointer to a service-defined Go
	// struct whose yaml tags lock the shape of config.yaml's
	// `data:` section. Threaded straight through to
	// render.Builder.WithDataSchema, which (a) validates the
	// loaded data against the struct's tags with KnownFields(true)
	// so a typo in YAML fails at boot, and (b) leaves the struct
	// populated as a side effect of the validation decode — so
	// services can read typed values from Go-side code (URL
	// builders, init guards) without re-parsing the YAML or
	// walking the framework's map[string]any.
	//
	// In dev mode the closure that re-loads config on every
	// request re-decodes into the same pointer, so a YAML edit
	// shows up immediately in both templates and Go-side helpers
	// without restarting the binary.
	//
	// Leave nil when the data: section is free-form (prototype,
	// content authored by non-engineers) or absent entirely.
	DataSchema any

	// IconCatalog is the shared name→inner-SVG map the framework's
	// {{ icon }} / {{ iconStroke }} / {{ iconFilled }} helpers
	// fall back to when a name is missing from the per-service
	// data.icons override. Typically `uikit.IconSet` — passing
	// it once here lets templates use {{ icon "leaf" 18 }} for
	// any catalogue glyph without the service redefining it.
	//
	// The render helpers are registered only when this is
	// non-nil. Leave empty when the service paints icons by
	// other means (raw <img>, pure CSS, etc.).
	IconCatalog map[string]string

	// Ready is the optional readiness probe behind the framework's
	// auto-mounted GET /readyz. Threaded straight through to
	// render.Builder.WithReady: return nil when the service can
	// take traffic, an error to answer 503. Leave nil for services
	// without a hard runtime dependency — /readyz then mirrors
	// /healthz. See render.Options.Ready for the contract.
	Ready func(ctx context.Context) error

	// StyledNotFound, when true, wraps the site handler so a
	// 404 from the render framework gets re-served as the
	// service's own `/<lang>/not-found` page (with status 404
	// preserved). Sub-request strategy — see notfound.go for
	// the gritty details. Default false to keep behaviour
	// unchanged for services that don't ship a not-found
	// template; flip to true when you have one at
	// pages/not-found.html.tmpl and want visitors to see it
	// instead of the framework's plaintext "404 page not
	// found".
	//
	// Lang resolution uses the loaded config.yaml's
	// supported_langs / default_lang so the wrapper stays in
	// sync with whatever the service declares — no need to
	// pass those again here.
	StyledNotFound bool
}

Options configures New.

type RulesOptions

type RulesOptions struct {
	// PipelinesDir is the subdirectory inside SiteFS containing
	// the *.yaml pipeline declarations. The same path is used as
	// a relative-to-WatchRoot disk path in dev. Required when
	// Mounts is non-empty.
	PipelinesDir string

	// Mounts maps URL patterns to pipeline names. Each entry
	// becomes mux.Handle(pattern, engine.HTTPHandler(name)).
	// Empty = rules wiring is skipped entirely.
	//
	// Patterns follow http.ServeMux semantics: exact path or
	// prefix with trailing slash. The canonical middleware bundle
	// (Secure / RequestID / AccessLog / Recover) wraps the mux
	// once, so every pipeline endpoint gets correlation IDs and
	// access logs without extra wiring.
	Mounts map[string]string

	// ExtraRules registers additional Rule instances on top of
	// rules.All(). Useful for service-local rules that aren't
	// reusable enough to live in web/rules/rules. Optional.
	ExtraRules []rulesengine.Rule
}

RulesOptions configures the rules-engine half of site.New.

Jump to

Keyboard shortcuts

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