Documentation
¶
Overview ¶
xtemplate extends Go's html/template to be capable enough to define an entire server-side application with a directory of Go templates.
Index ¶
- Constants
- Variables
- func AddBlueMondayPolicy(name string, policy *bluemonday.Policy)
- func AddMarkdownConfig(name string, md goldmark.Markdown)
- func CheckLegacyTemplateKeys(data []byte) error
- func ControllerTypeFromRaw(raw json.RawMessage) (string, error)
- func FuncFailf(format string, args ...any) (string, error)
- func FuncHumanize(formatType, data string) (string, error)
- func FuncIdx(idx int, arr any) (any, error)
- func FuncMeta(name string, args ...string) string
- func FuncReturn() (string, error)
- func FuncSanitizeHtml(policyName string, html string) (template.HTML, error)
- func FuncTrustAttr(s string) template.HTMLAttr
- func FuncTrustHtml(s string) template.HTML
- func FuncTrustJS(s string) template.JS
- func FuncTrustJSStr(s string) template.JSStr
- func FuncTrustSrcSet(s string) template.Srcset
- func FuncTry(fn any, args ...any) (*result, error)
- func GetLogger(ctx context.Context) *slog.Logger
- func GetRequestId(ctx context.Context) string
- func RegisterController(name string, ctor func() ServerController)
- func RegisterProvider(name string, ctor ProviderFactory)
- func RegisteredControllerTypes() []string
- type Closer
- type Config
- func (config Config) Check() error
- func (config Config) Instance() (_ *Instance, err error)
- func (c *Config) MaterializeController(preferType string) (string, error)
- func (c *Config) Options(options ...Option) (*Config, error)
- func (config Config) Server() (*Server, error)
- func (config *Config) SetDefaults() *Config
- func (c *Config) UnmarshalJSON(data []byte) error
- type CrossOriginConfig
- type DotFlush
- type DotProvider
- type DotReq
- type DotResp
- func (h *DotResp) AddHeader(field, val string) string
- func (h *DotResp) DelHeader(field string) string
- func (d *DotResp) RespondWith(status int, body any) (string, error)
- func (h *DotResp) ReturnStatus(status int) (string, error)
- func (d *DotResp) ServeContent(path_ string, modtime time.Time, content any) (string, error)
- func (h *DotResp) SetHeader(field, val string) string
- func (h *DotResp) SetStatus(status int) string
- type DotVars
- type DotX
- type Duration
- type ErrorStatus
- type Finalizer
- type HandlerRoute
- type Initializer
- type Instance
- type InstanceRoute
- type InstanceStats
- type MarkdownDoc
- type Meta
- type MetaHandler
- type Middleware
- type Option
- func WithContext(ctx context.Context) Option
- func WithController(s ServerController) Option
- func WithFuncMaps(fm ...template.FuncMap) Option
- func WithHandler(pattern string, h http.Handler) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMinify(minify bool) Option
- func WithOnClose(fn func() error) Option
- func WithProvider(f ProviderFactory) Option
- func WithTemplateDir(dir string) Option
- func WithTemplateFS(fs afero.Fs) Option
- type OsFsController
- type Provider
- type ProviderFactory
- type ReturnError
- type RouteInfo
- type Server
- func (server *Server) Context() context.Context
- func (server *Server) Instance() *Instance
- func (server *Server) Logger() *slog.Logger
- func (server *Server) Reload(options ...Option) error
- func (server *Server) Serve(listen_addr string) error
- func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (server *Server) Shutdown(ctx context.Context) error
- func (server *Server) Stop()
- type ServerController
Constants ¶
const DefaultMaxBodyBytes int64 = 1 << 20
DefaultMaxBodyBytes is the maximum request body accepted by DotReq.ReadBody when the caller does not pass a limit. It is 1 MiB.
Variables ¶
var DefaultControllerType = "os"
DefaultControllerType is used when no controller or TemplateFS is configured. Core default is "os". Binaries may reassign (e.g. cmd/xtemplate sets "watchfs").
Functions ¶
func AddBlueMondayPolicy ¶ added in v0.5.0
func AddBlueMondayPolicy(name string, policy *bluemonday.Policy)
AddBlueMondayPolicy adds a bluemonday policy to the global policy list available to all xtemplate instances.
func AddMarkdownConfig ¶ added in v0.9.0
AddMarkdownConfig adds a custom markdown configuration to xtemplate's markdown config map, shared by all xtemplate instances.
func CheckLegacyTemplateKeys ¶ added in v0.11.0
CheckLegacyTemplateKeys returns a migrate error if banned top-level keys are present.
func ControllerTypeFromRaw ¶ added in v0.11.0
func ControllerTypeFromRaw(raw json.RawMessage) (string, error)
ControllerTypeFromRaw peeks the "type" field of a controller JSON object. Empty raw returns ("", nil).
func FuncHumanize ¶ added in v0.5.0
humanize transforms size and time inputs to a human readable format using the go-humanize library.
Call with two parameters: format type and value to format. Supported format types are:
"size" which turns an integer amount of bytes into a string like "2.3 MB", for example:
{{humanize "size" "2048000"}}
"time" which turns a time string into a relative time string like "2 weeks ago", for example:
{{humanize "time" "Fri, 05 May 2022 15:04:05 +0200"}}
func FuncIdx ¶ added in v0.5.0
idx gets an item from a list, similar to the built-in index, but with reversed args: index first, then array. This is useful to use index in a pipeline, for example:
{{generate-list | idx 5}}
Returns an error if the value is not indexable or the index is out of range.
func FuncMeta ¶ added in v0.13.0
FuncMeta is a build-time metadata declaration directive ({{meta "<name>" args...}}). Declarations are extracted from the template AST during instance build and dispatched to MetaHandler providers; at render time meta is a no-op.
func FuncReturn ¶ added in v0.5.0
return causes the template to exit early with a success status.
func FuncSanitizeHtml ¶ added in v0.5.0
sanitizeHtml Uses the BlueMonday library to sanitize strings with html content. First parameter is the name of the chosen sanitization policy.
func FuncTrustAttr ¶ added in v0.5.0
trustAttr marks the string s as safe and does not escape its contents in html attribute context.
func FuncTrustHtml ¶ added in v0.5.0
trustHtml marks the string s as safe and does not escape its contents in html node context.
func FuncTrustJS ¶ added in v0.5.0
trustJS marks the string s as safe and does not escape its contents in script tag context.
func FuncTrustJSStr ¶ added in v0.5.0
trustJSStr marks the string s as safe and does not escape its contents in script expression context.
func FuncTrustSrcSet ¶ added in v0.5.0
trustSrcSet marks the string s as safe and does not escape its contents in script tag context.
func FuncTry ¶ added in v0.5.0
The try template func accepts a fallible function object and calls it with the provided args. If the function and args are valid, try returns the result wrapped in a result object that exposes the return value and error to templates. Useful if you want to call a function and handle its error in a template. If the function value is invalid or the args cannot be used to call it then try raises an error that stops template execution.
func GetRequestId ¶ added in v0.6.0
func RegisterController ¶ added in v0.11.0
func RegisterController(name string, ctor func() ServerController)
RegisterController makes a controller type available to ResolveController. Call from init(). Panics on duplicate registration.
func RegisterProvider ¶ added in v0.11.0
func RegisterProvider(name string, ctor ProviderFactory)
RegisterProvider makes a provider type available to resolveProviders. Call from init(). Panics on duplicate registration (names the type in the message; the registering package is identified by the runtime's stack trace).
func RegisteredControllerTypes ¶ added in v0.11.0
func RegisteredControllerTypes() []string
RegisteredControllerTypes returns sorted registered controller type names.
Types ¶
type Closer ¶ added in v0.11.0
type Closer interface {
Close() error
}
Closer is an optional capability for releasing instance-scoped resources when the instance is retired (reload or stop). Prefer Close over relying solely on context cancellation when the provider owns connections or similar handles.
type Config ¶ added in v0.3.0
type Config struct {
// Controller is the optional ServerController (JSON key "controller").
// Resolved from ControllerRaw by [Config.MaterializeController] (LoadConfig /
// Server.construct). Instance requires TemplateFS instead and rejects
// Controller / ControllerRaw.
Controller ServerController `json:"-" arg:"-"`
// ControllerRaw is the JSON "controller" object until MaterializeController.
ControllerRaw json.RawMessage `json:"controller,omitempty" arg:"-"`
// TemplateFS is the private build-root FS (not JSON). Sticky after controller
// Init or WithTemplateFS/Dir; also the per-Reload root when set via options.
TemplateFS afero.Fs `json:"-" arg:"-"`
// File extension to search for to find template files. Default `.html`.
TemplateExtension string `json:"template_extension,omitempty" arg:"--template-ext" default:".html"`
// Whether html templates are minified at load time. Default `false`.
//
// This is a *bool to distinguish unset (nil) from explicitly set.
Minify *bool `json:"minify,omitempty" arg:"-m,--minify" default:"false"`
CrossOrigin CrossOriginConfig `json:"crossorigin" arg:"-"`
ProvidersRaw []json.RawMessage `json:"providers,omitempty" arg:"-"`
// Providers holds factories that produce a fresh [Provider] per Instance
// build / Reload (same isolation as JSON ProvidersRaw → resolveProviders).
Providers []ProviderFactory `json:"-" arg:"-"`
// Encodings to pre-compress static files into at load time. Supported values:
// "gzip", "zstd", "br". Default empty (no pre-compression).
Precompress []string `json:"precompress,omitempty" arg:"--precompress,separate"`
// Left template action delimiter. Default `{{`.
LDelim string `json:"left,omitempty" arg:"--ldelim" default:"{{"`
// Right template action delimiter. Default `}}`.
RDelim string `json:"right,omitempty" arg:"--rdelim" default:"}}"`
// Additional functions to add to the template execution context.
FuncMaps []template.FuncMap `json:"-" arg:"-"`
// Peer HTTP handlers registered on the instance ServeMux next to template
// and static routes. Use this to embed existing handlers (APIs, webhooks,
// health checks) under the same ServeMux as the template app. Errors if the
// pattern conflicts with another route registered by the template root.
//
// Each entry is a sibling route on the mux (net/http.ServeMux pattern).
// Re-registered when a new instance is built, so they survive reloads.
Handlers []HandlerRoute `json:"-" arg:"-"`
// The instance context that is threaded through dot providers and can
// cancel the server. Defaults to `context.Background()`.
Ctx context.Context `json:"-" arg:"-"`
// The default logger. Defaults to `slog.Default()`.
Logger *slog.Logger `json:"-" arg:"-"`
// contains filtered or unexported fields
}
func (Config) Check ¶ added in v0.13.0
Check validates templates, routes, providers, and config without running provider Initializers or INIT templates (safe for offline CI and editors). Forces Minify to false so diagnostics report original file and line numbers.
func (Config) Instance ¶ added in v0.4.0
Instance creates a new *Instance from the given config. Requires a resolved template FS (WithTemplateFS / WithTemplateDir). Controller and ControllerRaw must be nil. Owned slices are cloned.
func (*Config) MaterializeController ¶ added in v0.11.0
MaterializeController ensures c.Controller is set and c.ControllerRaw is nil. The returned string is the selected type name when known (from Raw, preferType, or DefaultControllerType). Empty when Controller was already set (name unknown).
If Controller is already non-nil, only clears ControllerRaw. If ControllerRaw is set:
- When preferType is empty (library/Server), always decode Raw.
- When preferType is non-empty (CLI effective type), decode Raw only if its type is empty or equals preferType; otherwise discard Raw (CLI type wins). An empty raw type still attempts decode so ResolveController reports "missing type".
If still no Controller, creates NewController(preferType), or DefaultControllerType when preferType is empty.
func (*Config) Options ¶ added in v0.6.5
Options applies the given options to the Config, returning the updated Config or the first error.
func (Config) Server ¶ added in v0.4.0
Server creates a Server from Config. Apply Options on the Config first; this method does not take Option args. Owned slices are cloned so the caller's Config is not mutated by sticky Options or later Reloads.
func (*Config) SetDefaults ¶ added in v0.9.0
SetDefaults fills unset fields. Does not choose a Controller or clone slices.
func (*Config) UnmarshalJSON ¶ added in v0.11.0
UnmarshalJSON applies the ban-list then unmarshals into Config.
type CrossOriginConfig ¶ added in v0.9.0
type DotFlush ¶ added in v0.5.0
type DotFlush struct {
// contains filtered or unexported fields
}
DotFlush is used as the .Flush field for flushing template handlers (SSE).
func (*DotFlush) Flush ¶ added in v0.5.0
Flush flushes any content waiting to be written to the client.
func (*DotFlush) Repeat ¶ added in v0.5.0
Repeat generates numbers up to max, using math.MaxInt64 if no max is provided.
func (*DotFlush) SendSSE ¶ added in v0.6.0
SendSSE sends an sse message by formatting the provided args as an sse event:
Requires 1-4 args: event, data, id, retry
func (*DotFlush) Sleep ¶ added in v0.5.0
Sleep sleeps for ms milliseconds. Template execution is aborted if the request is canceled or the server receives a stop signal.
func (*DotFlush) WaitForServerStop ¶ added in v0.5.0
WaitForServerStop blocks template execution until the server receives a stop signal, then continues to allow sending a final response before the request is closed. Template execution is aborted if the client cancels the request.
type DotProvider ¶ added in v0.5.0
type DotProvider interface {
// FieldName is the exported struct field on the dot (e.g. "Shop" → {{.Shop}}).
FieldName() string
// Prototype returns a non-nil value of the field type. It is called once
// when building the instance solely to infer the type via reflection; the
// returned value is discarded. It must not depend on request data.
Prototype() any
// Value returns the value to assign to this provider's field for a request.
// w and r are the HTTP response writer and request (same as http.Handler).
// Request-scoped context is r.Context(); instance lifetime context should
// have been saved during [Initializer.Init] if needed.
Value(w http.ResponseWriter, r *http.Request) (any, error)
}
DotProvider is an optional capability for providers that contribute one named field on the per-request dot context (e.g. "Shop" → {{.Shop}}).
type DotReq ¶ added in v0.5.0
DotReq is used as the .Req field for template invocations with an associated request, and contains the current HTTP request struct which can be used to read request data. See http.Request for detailed documentation. Some notable methods and fields:
http.Request.Method, http.Request.PathValue, http.Request.URL, [http.Request.URL.Query], http.Request.Cookie, http.Request.Header, [http.Request.Header.Get], http.Request.FormValue, DotReq.ReadBody.
Note that http.Request.ParseForm must be called before using http.Request.Form, http.Request.PostForm, and http.Request.PostValue. DotReq.ReadBody reads the raw body (JSON, webhooks, and other non-form payloads) without parsing it as a form.
func (*DotReq) ReadBody ¶ added in v0.12.0
ReadBody reads the raw request body and returns it as a string.
An optional maxBytes argument is the maximum number of bytes to accept. When it is omitted, the limit is DefaultMaxBodyBytes (1 MiB). More than one argument, or a limit less than or equal to zero, returns an error. Pass an integer literal from a template, for example {{.Req.ReadBody 4096}}.
The body is read up to one byte past the limit. If it is larger than the limit, ReadBody returns an error wrapping ErrorStatus with http.StatusRequestEntityTooLarge so the buffered handler responds with HTTP 413 Request Entity Too Large instead of 500. A nil DotReq, a nil http.Request, or a nil body returns "" and a nil error.
On success the request body is replaced with a replay of the bytes just read (`io.NopCloser(bytes.NewReader(buf))`). A later ReadBody in the same request — including a second call in the same template — returns those bytes again when its limit is at least that length. Because the body is restored, FormValue and ParseForm still see the payload when ReadBody runs first. Pipe the string to Sprig's fromJson for JSON payloads: {{.Req.ReadBody | fromJson}}.
type DotResp ¶ added in v0.5.0
DotResp is used as the .Resp field in buffered template invocations.
A successful render defaults Content-Type to text/html; charset=utf-8 when the body has non-whitespace content and neither the template nor the response writer already set it. Empty and whitespace-only bodies, and statuses that must not include a body (1xx, 204, 304), do not get that default.
func (*DotResp) AddHeader ¶ added in v0.5.0
AddHeader adds a header field value, appending val to existing values for that field. It returns an empty string.
func (*DotResp) DelHeader ¶ added in v0.5.0
DelHeader deletes a header field. It returns an empty string.
func (*DotResp) RespondWith ¶ added in v0.12.0
RespondWith discards any template output buffered so far and finishes the request with the given HTTP status and body. Unlike DotResp.ReturnStatus, the template buffer is not sent. body is required (pass "" for an empty body). Supported types: string, template.HTML, []byte.
Headers set on .Resp before RespondWith (Location, Content-Type, etc.) are kept. If body is template.HTML, non-empty, and Content-Type is unset, it defaults to text/html; charset=utf-8. Empty bodies do not force a Content-Type.
func (*DotResp) ReturnStatus ¶ added in v0.5.0
ReturnStatus sets the HTTP response status and exits template rendering immediately. Unlike DotResp.RespondWith, the template buffer is kept and written as the response body.
func (*DotResp) ServeContent ¶ added in v0.5.0
ServeContent aborts execution of the template and instead responds to the request with content with any headers set by AddHeader and SetHeader so far but ignoring SetStatus. content must be a string, []byte, or io.ReadSeeker.
type DotVars ¶ added in v0.12.0
DotVars is the per-request scratch map at .Vars. It is map-shaped so FuncMaps that work on `map[string]any` work with it.
func (DotVars) Delete ¶ added in v0.12.0
Delete removes key if present. key must be non-empty. Returns an empty string.
func (DotVars) Get ¶ added in v0.12.0
Get returns the value for key, or nil if the key is missing. key must be non-empty.
type DotX ¶ added in v0.5.0
type DotX struct {
// contains filtered or unexported fields
}
DotX is used as the field at .X in all template invocations.
func (DotX) Func ¶ added in v0.5.0
Func returns a function by name to call manually. Can be used in combination with the call and try funcs.
func (DotX) StaticFileHash ¶ added in v0.5.0
StaticFileHash returns the sha-384 hash of the named asset file to be used for integrity or caching behavior.
func (DotX) Template ¶ added in v0.5.0
Template invokes the named template with the given dot value, returning the result as an HTML string.
Relative paths prefixed with "./" or "../" resolve against base (the caller's template file path). Template calls to .X.Template, $.X.Template, and try .X "Template" automatically prepend the current file path as base at parse time, so templates write {{.X.Template "name" .}}.
type Duration ¶ added in v0.11.0
Duration is a time.Duration that marshals to/from human-friendly strings (e.g. "30s", "1m30s") in JSON and text.
It implements encoding.TextUnmarshaler and encoding.TextMarshaler so go-arg CLI flags parse duration strings the same way.
func (Duration) MarshalJSON ¶ added in v0.11.0
MarshalJSON implements json.Marshaler. Zero encodes as "0s".
func (Duration) MarshalText ¶ added in v0.11.0
MarshalText implements encoding.TextMarshaler.
func (*Duration) UnmarshalJSON ¶ added in v0.11.0
UnmarshalJSON implements json.Unmarshaler. Accepts a duration string ("30s") or JSON null.
func (*Duration) UnmarshalText ¶ added in v0.11.0
UnmarshalText implements encoding.TextUnmarshaler.
type ErrorStatus ¶ added in v0.6.0
type ErrorStatus int
func (ErrorStatus) Error ¶ added in v0.6.0
func (e ErrorStatus) Error() string
type Finalizer ¶ added in v0.11.0
Finalizer is an optional capability for DotProvider work after template execution (commit/rollback, close request-scoped handles, write buffered response headers/status). value is what DotProvider.Value returned for the request; err is the template/construction error so far. The returned error replaces err for subsequent finalizers and the handler.
type HandlerRoute ¶ added in v0.9.0
type HandlerRoute struct {
// Pattern uses net/http.ServeMux syntax (e.g. "POST /foo/{bar}").
Pattern string
Handler http.Handler
}
HandlerRoute pairs a ServeMux pattern with an http.Handler.
type Initializer ¶ added in v0.11.0
Initializer is an optional capability for instance-scoped setup (open DB, connect, validate config, etc.). Init runs once per instance load with the instance context (cancelled on reload/stop). Providers that need that context at request time should retain it on the provider value.
type Instance ¶ added in v0.4.0
type Instance struct {
// contains filtered or unexported fields
}
Instance is a configured, immutable, xtemplate request handler ready to execute templates and serve static files in response to http requests.
The only way to create a valid Instance is to call the Config.Instance method. Configuration of an Instance is intended to be immutable. Instead of mutating a running Instance, build a new Instance from a modified Config and swap them.
See also Server which manages instances and enables reloading them.
func (*Instance) Close ¶ added in v0.11.0
Close releases instance-scoped provider resources (Closer), then runs WithOnClose callbacks. Invocations after the first return a memoized result and do not call Closer.Close or WithOnClose callbacks again.
If requests are still in flight (grace period expired or Stop skipped drain), Close logs this as a warning.
func (*Instance) Id ¶ added in v0.4.0
Id returns the id of this instance which is unique in the current process. This differentiates multiple instances, as the instance id is attached to all logs generated by the instance with the attribute name `xtemplate.instance`.
func (*Instance) Routes ¶ added in v0.4.0
func (x *Instance) Routes() []InstanceRoute
Routes returns a copy of all the routes registered with this instance.
func (*Instance) ServeHTTP ¶ added in v0.5.0
func (instance *Instance) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*Instance) Stats ¶ added in v0.4.0
func (x *Instance) Stats() InstanceStats
Stats returns the instance build stats.
type InstanceRoute ¶ added in v0.4.0
type InstanceStats ¶ added in v0.4.0
type MarkdownDoc ¶ added in v0.9.2
type MarkdownDoc struct {
Meta map[string]any `json:"meta,omitempty"`
Body template.HTML `json:"body,omitempty"`
}
MarkdownDoc is the result of rendering Markdown: the decoded front matter metadata and the rendered HTML body.
func FuncMarkdown ¶ added in v0.5.0
func FuncMarkdown(input any, configName ...string) (MarkdownDoc, error)
markdown parses front matter out of the input and renders the remaining Markdown to HTML in a single pass, returning both .Meta and .Body. input may be a string, []byte, or io.Reader. This uses the Goldmark library, which is CommonMark compliant. If an alternative markdown policy is not named, it uses the default policy which has these extensions enabled: YAML/TOML front matter, Github Flavored Markdown, Footnote, and syntax highlighting provided by Chroma.
type Meta ¶ added in v0.13.0
Meta is a single build-time {{meta "<name>" args...}} declaration extracted from the top level of a route template or hidden template file.
type MetaHandler ¶ added in v0.13.0
MetaHandler is an optional capability for providers that inspect registered routes and/or consume {{meta "<name>" args...}} template declarations at build time. HandleMeta runs once per instance load (and during Config.Check) before Initializer.Init, receiving every registered route plus any hidden template file containing top-level meta declarations.
Providers return the meta names they handle (e.g. []string{"authz"}). If any {{meta "<name>" ...}} declaration in templates is not claimed by at least one MetaHandler, instance build fails closed.
type Middleware ¶ added in v0.13.0
Middleware is an optional capability for providers that wrap the instance HTTP handler. Configured Middleware providers are applied in slice order so the first configured middleware is the outermost wrapper (runs first on the request and last on the response), inside CrossOriginConfig protection.
type Option ¶ added in v0.6.0
func WithContext ¶ added in v0.11.0
func WithController ¶ added in v0.11.0
func WithController(s ServerController) Option
WithController sets the ServerController. Rejected when building an Instance / Reload.
func WithFuncMaps ¶ added in v0.3.0
func WithHandler ¶ added in v0.9.0
WithHandler mounts h at pattern on the instance ServeMux (net/http.ServeMux syntax, e.g. "POST /api/{id}" or "GET /healthz"). Appends to Config.Handlers.
Intended for embedding foreign handlers (API, webhooks, probes) as peer routes beside templates and static files.
func WithLogger ¶ added in v0.3.0
func WithMinify ¶ added in v0.11.0
func WithOnClose ¶ added in v0.11.0
WithOnClose registers fn to run when the Instance built with this option is [Instance.Close]d (reload retire or stop). Multiple callbacks append; they run after provider [Closer]s, reverse registration order. Nil fns ignored.
Per instance, not once per Server: on the sticky base, fn runs for every retired instance. Use sync.Once for process-wide cleanup, or pass WithOnClose only on the Reload that owns a per-build resource (e.g. a temp clone dir).
func WithProvider ¶ added in v0.5.0
func WithProvider(f ProviderFactory) Option
WithProvider appends a factory that produces a provider on each Instance build. The factory must not return nil. Rejects a nil factory.
func WithTemplateDir ¶ added in v0.11.0
WithTemplateDir sets the private build-root FS to an OS directory.
func WithTemplateFS ¶ added in v0.3.3
WithTemplateFS sets the private build-root FS for the next Instance.
type OsFsController ¶ added in v0.11.0
type OsFsController struct {
// Path is the templates directory. Default "templates".
Path string `json:"path,omitempty" arg:"-t,--template-dir,--templates-dir" default:"templates"`
}
OsFsController serves templates from a local directory (JSON type "os").
func (*OsFsController) Init ¶ added in v0.11.0
Init returns a sticky BasePathFs rooted at Path (default "templates").
func (*OsFsController) Start ¶ added in v0.11.0
func (s *OsFsController) Start(_ *Server) error
type Provider ¶ added in v0.11.0
type Provider any
Provider is a pluggable component participating in an Instance's lifecycle and request pipeline. Every configured Provider must implement at least one capability interface: DotProvider, Middleware, MetaHandler, Initializer, or Closer.
Capabilities are asserted dynamically at instance build time (similar to Caddy modules), so a provider may contribute a dot field, wrap the HTTP router as middleware, inspect routes and {{meta}} declarations, or manage lifecycle resources in any combination.
Lifecycle order:
- Config decode (JSON via RegisterProvider) or Go factory (WithProvider).
- Capability validation (at least one of DotProvider, Middleware, MetaHandler, Initializer, Closer).
- Optional MetaHandler.HandleMeta runs once per instance load (and during Config.Check) before Initializer.Init.
- Optional Initializer.Init runs once per instance load in config order.
- Optional Closer.Close runs in reverse order when the instance is retired.
- DotProvider.FieldName and DotProvider.Prototype assemble the dot struct.
- Middleware.Wrap wraps the router in config order (first = outermost), inside CrossOriginConfig protection.
- Per request: Middleware → router → DotProvider.Value → template → optional Finalizer.Finalize.
type ProviderFactory ¶ added in v0.11.0
type ProviderFactory func() Provider
ProviderFactory constructs a fresh Provider value. Sticky Config.Providers hold factories so each Instance / Reload build materializes new providers (matching JSON [resolveProviders] + registry constructors).
type ReturnError ¶
type ReturnError struct{}
ReturnError is a sentinel value that indicates a successful/normal exit but causes template execution to stop immediately. Used by funcs and dot field methods to perform custom actions.
func (ReturnError) Error ¶
func (ReturnError) Error() string
type RouteInfo ¶ added in v0.13.0
type RouteInfo struct {
// Pattern is the Go http.ServeMux route pattern (e.g. "GET /{$}",
// "POST /notes", "GET /assets/app.css"), or "" for top-level meta declared
// in a hidden template file (e.g. "/.authz.html").
Pattern string
// Path is the source template or static file path (e.g. "/index.html",
// "/.authz.html", "/assets/app.css"), or "" for custom handlers registered
// via [WithHandler].
Path string
// Meta holds top-level {{meta}} declarations in source order.
Meta []Meta
}
RouteInfo describes a registered route (or a hidden template file carrying top-level meta declarations) passed to MetaHandler.HandleMeta at build time.
type Server ¶ added in v0.4.0
type Server struct {
// contains filtered or unexported fields
}
Server is a reloadable http.Handler that always routes to the current Instance, or responds 503 when none is loaded or the server has stopped.
Optional ServerController: Init supplies sticky base options, then Start may drive reloads. The sticky base is fixed at construction.
Server.Reload rebuilds from sticky plus ephemeral options. Server.Shutdown / Server.Stop tear down; with Server.Serve, cancelling the server context also drains the local http.Server (not stored on Server).
Create only via Config.Server.
func (*Server) Context ¶ added in v0.11.0
Context is cancelled on Stop/Shutdown. Controllers use it to halt background work.
func (*Server) Instance ¶ added in v0.4.0
Instance returns the current Instance. After calling Reload, previous calls to Instance may be stale. When not ready yet or after Stop/Shutdown, returns nil.
func (*Server) Logger ¶ added in v0.11.0
Logger returns the server logger (xtemplate group applied at construction).
func (*Server) Reload ¶ added in v0.4.0
Reload builds a new Instance from the sticky base plus options and swaps it in on success. Previous instance is cancelled, drained up to [defaultGrace], then closed (outside the mutex so concurrent Reload/Shutdown are not blocked). Ephemeral WithTemplateFS/Dir apply only to this build; empty Reload rebuilds from sticky. Fails if the final template root is nil. WithController is rejected.
func (*Server) Serve ¶ added in v0.4.0
Serve opens a net listener on `listen_addr` and serves requests from it. It returns when the listener fails or when the server context is cancelled (parent Config.Ctx or Server.Shutdown/Server.Stop), in which case the local http.Server is drained (default grace [defaultGrace]), the instance is retired, and Serve returns nil.
func (*Server) ServeHTTP ¶ added in v0.10.0
func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP routes the request to the current Instance, or responds 503 if no instance is loaded yet or the server has been stopped.
func (*Server) Shutdown ¶ added in v0.11.0
Shutdown stops the server gracefully.
- Nils the current instance (new requests get 503) and cancels serverCtx (cascades into the instance context so SSE/Flush observe stop).
- Waits for in-flight instance requests up to ctx, then Closes providers.
When Server.Serve is running, cancelling serverCtx also causes Serve to drain its local http.Server; Shutdown itself does not own or call into it.
ctx bounds only the in-flight wait; teardown always runs. Safe if Serve never ran (handler-only / Caddy). Idempotent.
type ServerController ¶ added in v0.11.0
type ServerController interface {
Init(ctx context.Context, log *slog.Logger) (sticky []Option, err error)
Start(server *Server) error
}
ServerController is attached once per Server by Config.Server:
- Init returns sticky [Option]s for the base config (no Server methods).
- Start may drive reloads via server.Reload (safe to call synchronously).
Built-in: os. Optional: controllers/watchfs, controllers/git.
func NewController ¶ added in v0.11.0
func NewController(name string) (ServerController, error)
NewController returns a new zero-value ServerController for a registered type name.
func ResolveController ¶ added in v0.11.0
func ResolveController(raw json.RawMessage) (ServerController, error)
ResolveController decodes raw JSON by peeking its "type" field, looking up the constructor, and re-decoding into the concrete type.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
standard
Package standard links the default Caddyfile parsers (providers + controllers), the pure-Go sqlite3 driver, and the xtemplate caddy module.
|
Package standard links the default Caddyfile parsers (providers + controllers), the pure-Go sqlite3 driver, and the xtemplate caddy module. |
|
cmd
module
|
|
|
xtemplate
command
Default xtemplate CLI: providers, watchfs, git; default controller is watchfs.
|
Default xtemplate CLI: providers, watchfs, git; default controller is watchfs. |
|
controllers
|
|
|
git
Package git is a ServerController that serves templates from a git repository via the installed `git` binary.
|
Package git is a ServerController that serves templates from a git repository via the installed `git` binary. |
|
git/caddyfile
Package caddyfile registers the git controller Caddyfile parser.
|
Package caddyfile registers the git controller Caddyfile parser. |
|
watchfs
Package watchfs is a ServerController that serves templates from a local directory and reloads when watched paths change.
|
Package watchfs is a ServerController that serves templates from a local directory and reloads when watched paths change. |
|
watchfs/caddyfile
Package caddyfile registers the watchfs controller Caddyfile parser.
|
Package caddyfile registers the watchfs controller Caddyfile parser. |
|
examples
|
|
|
dotprovider
command
Custom dot provider example: the "repository pattern".
|
Custom dot provider example: the "repository pattern". |
|
embedded
command
Embedded single-binary example: the templates dir is compiled into the binary via //go:embed, so this binary serves its templates with no templates dir on disk at runtime.
|
Embedded single-binary example: the templates dir is compiled into the binary via //go:embed, so this binary serves its templates with no templates dir on disk at runtime. |
|
internal
module
|
|
|
providers
|
|
|
dotauthz
Package dotauthz implements a lightweight, native ReBAC authorization provider for xtemplate.
|
Package dotauthz implements a lightweight, native ReBAC authorization provider for xtemplate. |
|
dotauthz/caddyfile
Package caddyfile registers the authz provider for Caddyfile use.
|
Package caddyfile registers the authz provider for Caddyfile use. |
|
dotbus
Package dotbus implements the bus core dot provider: a process-local multi-producer multi-consumer topic fan-out for templates.
|
Package dotbus implements the bus core dot provider: a process-local multi-producer multi-consumer topic fan-out for templates. |
|
dotbus/caddyfile
Package caddyfile registers the bus dot-provider for Caddyfile use.
|
Package caddyfile registers the bus dot-provider for Caddyfile use. |
|
dotflags/caddyfile
Package caddyfile registers the flags dot-provider for Caddyfile use.
|
Package caddyfile registers the flags dot-provider for Caddyfile use. |
|
dotfs
Package dotfs is the core filesystem xtemplate dot provider (type "fs").
|
Package dotfs is the core filesystem xtemplate dot provider (type "fs"). |
|
dotfs/caddyfile
Package caddyfile registers the fs dot-provider for Caddyfile use.
|
Package caddyfile registers the fs dot-provider for Caddyfile use. |
|
dotnats/caddyfile
Package caddyfile registers the nats dot-provider for Caddyfile use.
|
Package caddyfile registers the nats dot-provider for Caddyfile use. |
|
dotsmtp
Package smtp implements the smtp core dot provider, which exposes synchronous send-only SMTP mail delivery to templates via a dot field.
|
Package smtp implements the smtp core dot provider, which exposes synchronous send-only SMTP mail delivery to templates via a dot field. |
|
dotsmtp/caddyfile
Package caddyfile registers the smtp dot-provider for Caddyfile use.
|
Package caddyfile registers the smtp dot-provider for Caddyfile use. |
|
dotsql/caddyfile
Package caddyfile registers the sql dot-provider for Caddyfile use.
|
Package caddyfile registers the sql dot-provider for Caddyfile use. |
|
nats
module
|
|
|
register
module
|
|
|
test
module
|