Documentation
¶
Overview ¶
Package ui renders the pages of a template store as HTML with html/template, with layouts, partials and fragments for HTMX swaps, and serves static files.
Service implements gas.Service, gas.ReadyReporter and Provider, the contract this package owns. A service that renders pages takes a ui.Provider. Templates come from a gas.TemplateProvider, such as a store of gas/template.
Usage ¶
In an app, the container builds the service from New, with the template store registered as gas.TemplateProvider, and calls its Init:
gas.WithSingletonService[gas.TemplateProvider](memory.NewStore()), gas.WithSingletonService[ui.Provider](ui.New[gas.TemplateProvider]()),
By hand, with a configuration given in code and no static files:
store, err := memory.NewStore()()
if err != nil {
return err
}
err = store.Register(ctx, "layouts/base.html",
[]byte(`{{define "base"}}<main>{{block "content" .}}{{end}}</main>{{end}}`))
err = store.Register(ctx, "users.html",
[]byte(`{{define "content"}}<h1>{{.}}</h1>{{end}}`))
cfg := ui.DefaultConfig()
s, err := ui.New[gas.TemplateProvider](ui.WithConfig(cfg))(store, gas.NewRouter(), nil, logger)
if err != nil {
return err
}
if err := s.Init(ctx); err != nil {
return err
}
defer s.Close(ctx)
err = s.Render(ctx, w, "users", "Users")
err = s.RenderFragment(ctx, w2, "users", "Users")
After this w holds `<main><h1>Users</h1></main>` and w2 holds `<h1>Users</h1>`, each with `Content-Type: text/html; charset=utf-8`.
Contract ¶
Every Provider, and any implementation that wants to be one, keeps these rules:
- Render executes a page through its layout, and RenderFragment executes the page's fragment without it, as under Layout and Fragments. Both write the result to the response writer whole.
- On any error, neither writes anything to the response writer: no header, no status, no byte. A handler that returns the error has the response written once, by its error handler. A failed write is the one exception, as under Status and writes.
- Neither calls WriteHeader unless asked with WithStatus, so a status the handler wrote stands, and the default 200 comes from the first write.
- RegisterFuncs adds functions every page can call from the next render on, checks each first, and adds none when one fails.
- A page's error never fails another page.
- The methods are safe for concurrent use. Render and RenderFragment take the request's context, which bounds what they read from the store.
The package's conformance tests run the service through these rules over the memory, fs and dir stores of gas/template. The mock of gas/ui/uitest keeps none of them, as its package describes.
Names ¶
The store's templates are read by name, and only those whose name ends in one of the `ui.extensions`, so that a store shared with gas/email keeps its `.txt` templates out. A template is:
- a layout, when its name starts with LayoutsPrefix, `layouts/`;
- a partial, when its name starts with PartialsPrefix, `partials/`;
- a page, when its name starts with `ui.pagesprefix`, empty by default.
Any other template is not read.
A page's name is its store name without the pages prefix and the longest extension it ends in: `users.html` is `users`, and `admin/users.html` is `admin/users`. These fail to compile:
- two store names that make the same page name, such as `a.htm` and `a.html`;
- a store name that makes no page name, such as `.html`.
A page name is valid UTF-8 without a NUL byte or a backslash, and a clean slash path, as fs.ValidPath accepts. Any other name is ErrInvalidName, which gives the reason and never the name. A valid name that is no page, such as `users.html` or `layouts/base`, is ErrPageNotFound, with the name quoted.
Template sets ¶
Each page compiles into a set of its own: every layout and partial, in byte order of their names, and then the page.
Each file's top-level text is the template of its store name, such as `layouts/base.html`, and each `{{define}}` adds a template of its name to the set. A later definition of a name replaces an earlier one, unless it is empty, as in html/template. So a page overrides a layout's `{{block}}` by defining it, and a partial defined twice keeps the later one.
A template that defines a name ending in one of the extensions fails to compile, so that no file can replace another file's top-level text.
The set is never executed. Each template a render executes, the layout, the fragment or a name given to WithBlock or WithLayout, runs in a copy of the set of its own, made on its first render and kept. The reason: html/template escapes a template for the context it is first executed in, and keeps the result. With a copy each:
- a template's output never depends on which others ran before it;
- a template that fails to escape alone, such as a partial that opens an attribute its caller closes, fails each time without breaking the page.
Layout ¶
Render executes the template of the layout's name, `ui.layoutname` unless WithLayout gives another, in the page's set.
When the store holds no layout and WithLayout is not given, Render executes the page's top-level text instead, so a site without layouts renders its pages whole, even when a partial or the page defines a template of the layout's name. Otherwise a set without the layout's name is ErrLayoutNotFound.
Fragments ¶
RenderFragment executes the page's fragment. So one page serves both the full document and the HTMX swap of its content. The fragment is, in order of preference:
- the block named `ui.fragmentblock`, `content` by default, when the page itself defines it;
- else the page's top-level text, when it has any;
- else nothing, with ErrNoFragment.
A layout's or a partial's top-level text is never a page's fragment. A define with nothing in it does not count, as html/template keeps the layout's non-empty one in its place.
A page that does not define the block but has top-level text has that text as the block too. So under a layout Render shows what RenderFragment does, unless a partial defines the block or the text calls it with `{{template}}`, directly or through the templates it calls, such as the layout.
Blocks ¶
WithBlock executes any template of the page's set instead of the fragment, such as a partial's define or a layout's block. A name the set lacks is ErrBlockNotFound.
WithBlock applies to RenderFragment, and WithLayout to Render. The other method refuses each with ErrInvalidOption, as it does a nil option.
The name given to WithBlock or WithLayout picks the code that runs. Take it from a fixed list in the app, never from the request, such as an HX-Target header: it would run a template the page reaches only behind a guard such as `{{if .IsAdmin}}`.
Status and writes ¶
A render runs these steps:
- A render whose context has ended before it starts returns the context's error and writes nothing.
- A status given with WithStatus must be 200 to 599 and allow a body, so not 204 or 304. Any other is ErrInvalidStatus, before the page executes.
- The page executes into a buffer first, so an execute error writes nothing.
- The method sets `Content-Type: text/html; charset=utf-8` unless the handler set a Content-Type.
- It calls WriteHeader only with the status of WithStatus.
- It writes the page. A failed write is ErrWrite; the response has started by then, often with the client gone.
Buffers are reused, but for those that grew past 1 MiB.
Functions ¶
Every page can call html/template's built-in functions and these:
- `upper`, `lower`, `trimSpace`, `contains`, `hasPrefix`, `hasSuffix`, `replace` (strings.ReplaceAll), `join`, `split`.
- `truncate n s`: the first n runes of s and `...` when s has more; an error for a negative n.
- `now`; `formatTime layout t`; `formatTimePtr layout t`, empty for a nil t.
- `add`, `sub`: on ints.
- `dict k v ...`: a map of string keys; an error for an odd count or a key that is not a string.
- `list v ...`.
- `json v`: v as JSON; an error when it cannot be encoded.
- `buildId`: an ID of the build, the same for every call within it and new with each, to bust caches of assets.
There is no `title`: the rules of title case depend on the language. An app that needs it registers its own, such as one built on golang.org/x/text/cases.
Adding functions ¶
WithFuncs and Service.RegisterFuncs add functions over the default ones, replacing one of the same name, which RegisterFuncs logs at warn level. A call is ErrInvalidFunc, where html/template would panic, unless:
- the function's name is a Go identifier;
- its value is a non-nil function with one result, or two with an error second.
The names `html`, `urlquery` and those that start with `_html_template_` are ErrInvalidFunc too: html/template escapes through them, and a replacement would write data unescaped.
A function named as another built-in of text/template, such as `len` or `printf`, replaces it. Init or RegisterFuncs then logs `template func replaces a builtin` at warn level.
The functions given to RegisterFuncs belong to the Service, not to one Init. They outlive Close and every later Init, so a dependent that registers its functions in its own Init need not run again after a restart.
Builds and Reload ¶
A build lists the store once, reads each template once and compiles every page, within the context of the call that runs it.
Init builds nothing: the first render does, so the functions dependents register in their Init are in. Renders that need a build at once run one build.
Outside reload mode, the set is kept until a function is registered or Service.Reload runs. A change to the store, such as a row of the gas/template db store edited at runtime, is seen on Reload only. Reload builds now with its own context and returns the build's error.
With `ui.reload` true, every render builds anew from the store. This suits development, and costs a read of every template per request.
Build failures ¶
A build fails as a whole when:
- the store cannot list;
- a layout or a partial cannot be read (ErrLoad) or compiled (ErrCompile);
- its context ends.
Outside reload mode, renders then keep the set of the build before it. When there is none, they fail with the error and build again on the next render.
A page that cannot be read or compiled fails its own renders only. Outside reload mode, such a page keeps its version of the build before, when that one compiled. A page that could not be read and has none is read again by the next render that needs it.
How a failed build is reported:
- A build with any error is logged once at error level, `template build failed`, when a set is kept or other pages compiled.
- Reload returns its error.
- A build its context ended is neither kept nor reported.
- In reload mode nothing is logged, and a render fails with its own build's error.
Readiness ¶
Service.CheckReady runs the first build within its own context when none has been tried, as a render would. It fails only while no set exists that renders can use: the first build failed as a whole, or, in reload mode, the last one did. A page that fails to compile does not fail it.
Static files ¶
Static files are served with `ui.staticdir` set, or a file system given to WithStaticFS. Init then registers a GET route, which serves HEAD too, on each static route, and the files are served as StaticHandler serves them.
Init opens `ui.staticdir` with os.OpenRoot, wherever it is:
- A directory that is missing, or is not one, fails Init.
- No path or symlink can reach a file outside it.
- The directory is opened once, so moving it, or changing the working directory, changes nothing until the next Init.
Through the service's routes, a method other than GET and HEAD never reaches the handler. The router of gas answers 405 in its unified error shape, with one `Allow` field per method of the route, GET and HEAD.
The prefix the service's handler removes is the first of these that applies:
- `ui.staticstripprefix`;
- nothing, with `ui.staticpaths` set;
- `ui.staticpath` up to the last `/` before its first `*` or `{`: `/static/*` removes `/static/`.
Static handler ¶
StaticHandler serves the files of an fs.FS under a URL path prefix: it removes the prefix and serves the regular file the rest names.
It answers 404 Not Found for:
- a path outside the prefix, or an empty rest;
- a rest that is not clean as path.Clean makes it, so with a `.` or `..` element, an empty one as in `a//b`, or a trailing `/`, also when they came percent-encoded;
- a rest that holds a NUL byte or a backslash, or is not valid UTF-8;
- a directory, so nothing is listed and nothing redirects;
- a file that is not regular;
- unless dotfiles are on, a path with an element that starts with `.`, such as `.env` or `.git/config`;
- a file that leaves the root through a symlink;
- a file it may not read, so that no response tells a file that exists from one that does not.
The dotfile rule applies to the URL path, not to where a symlink leads: a symlink inside the root named without a dot, to a dotfile inside the root, serves that file.
Its other answers:
- 503 Service Unavailable once the root is closed.
- 405 Method Not Allowed, with `Allow: GET, HEAD`, for any other method than GET and HEAD.
- 500 for any other error, which is given to WithErrorFunc; the service logs it at error level.
Static responses ¶
Every response carries `X-Content-Type-Options: nosniff`. A file is served with http.ServeContent:
- its type by extension, else sniffed, HTML included;
- ranges;
- conditional requests, by Last-Modified for a file with a mod time, and else by an ETag, a hash of its content, which suits an embed.FS.
The handler keeps ETags under these rules:
- It keeps the ETags of the first 4096 files it serves. A file it has no room for is served without an ETag, never hashed.
- A tag is computed on a GET without a Range header only. So a HEAD or a range request for a file without a kept tag is served without one.
- A tag is computed again when a file's size changes. So an fs.FS whose files change in place without a mod time, and keep their size, keeps its old tag.
With a max age, set by WithMaxAge or `ui.staticmaxage`, every file carries `Cache-Control: public, max-age=N`.
Configuration ¶
The settings live in the `ui` section, in Settings:
- `ui.extensions`: the extensions of the templates read, each a dot and one or more characters, none a slash, a backslash or NUL. Default: `.html`, DefaultExtension.
- `ui.pagesprefix`: the prefix of every page's store name, empty or a clean slash path ending in `/` outside `layouts/` and `partials/`. Default: none.
- `ui.layoutname`: the template Render executes. Default: `base`, DefaultLayoutName.
- `ui.fragmentblock`: the block RenderFragment executes. Default: `content`, DefaultFragmentBlock.
- `ui.reload`: build on every render. Default: false.
- `ui.staticdir`: the directory of static files, empty for none. Default: none, DefaultStaticDir.
- `ui.staticpath`: the route of static files, needed when they are served and `ui.staticpaths` is empty. Default: `/static/*`, DefaultStaticPath.
- `ui.staticpaths`: the routes of static files, instead of `ui.staticpath`. Default: none.
- `ui.staticstripprefix`: the prefix removed before a file is looked up, empty or starting and ending with `/`. Default: derived, as under Static files.
- `ui.staticdotfiles`: serve paths with an element that starts with `.`. Default: false.
- `ui.staticmaxage`: the max-age of static files, 0 for no Cache-Control or at least 1s, in whole seconds. Default: 0.
A route starts with `/`, holds `*` only at its end, and holds `{` and `}` only in pairs that do not nest; the router would refuse any other when the app starts. The static rules apply only when static files are served.
Service.Init resolves the configuration each time it runs:
- Without WithConfig, it binds DefaultConfig from the gas.ConfigProvider, which checks the `validate` tags. A nil ConfigProvider is ErrNoConfigProvider.
- With WithConfig, it takes a copy of the given Config, slices included, never changing the caller's struct, and checks the same tags. A nil Config is ErrNilConfig.
Then the rules above run. A failure wraps ErrInvalidConfig and names the setting, never its value.
Service.Config returns a copy of the configuration the last successful Init resolved, defaults and slices included, or the zero Config before one. A failed Init and Close leave it as it was.
Lifecycle ¶
New's constructor checks the dependencies:
- A nil logger is ErrNilLogger, and a nil store ErrNilTemplateProvider.
- A nil ConfigProvider is accepted, and Init then requires WithConfig.
- A nil router is accepted, and Init then fails with ErrNilRouter when static files are on.
WithStaticFS with a nil file system fails Init with ErrNilFS.
A successful Init runs these steps, in order:
- It resolves the configuration.
- It checks the functions of WithFuncs.
- It opens the static files.
- It registers the static routes.
- It logs `service initialized` at info level, with `reload` and `static`.
Service.Close makes the service closed, closes the static directory, and logs `service closed` at info level. Renders in progress complete. Close ignores its context.
Init after Close starts the service again: the configuration is resolved afresh, the first render builds anew, and the static routes are registered again. Through an app, core answers 503 on the static routes while the service is closed.
Out of the usual order:
- Before the first successful Init, every method but Init, Close, Name and Config returns an error wrapping ErrNotInitialized.
- After Close, until Init succeeds, they return ErrClosed, and a static route answers 503.
- Init on an initialized service returns ErrAlreadyInitialized and changes nothing.
- Close on a service that is not initialized returns nil and logs nothing.
Concurrency ¶
A Service is safe for concurrent use:
- Its state is swapped whole by Init and Close, so a call sees one Init's state. A call that runs beside Close completes or returns ErrClosed.
- Compiled sets never change once built, and each page's copies are made under a lock of the page. Renders execute them concurrently, WithBlock included.
- Builds run one at a time. A render that waited while another build finished takes that build's outcome, unless functions were registered since.
- RegisterFuncs takes a lock the builds read the functions under.
A panic while a page executes is returned as ErrExecute.
Security ¶
html/template escapes data for the context it lands in: text, attributes, URLs, scripts and styles. None of the default functions returns a trusted type such as template.HTML, so none bypasses it.
A function given to WithFuncs or RegisterFuncs that returns template.HTML, template.JS, template.URL or another trusted type writes its result unescaped. It must never return data from a user unescaped.
Templates are code: a template can call every function and reach every value passed to it. The store's source is trusted as the app's own, as gas/template describes.
Errors carry what html/template gives: the file, the position and the action, such as `at <.User.Name>`, and the text of a function's error. They reach the app's logs, not the client, through core's error handler. Keep secrets out of the errors of your functions.
A page name from a request is quoted in an error only when it is valid, and only ever reaches the store's pages. Map user input to a fixed set of names instead.
Static files are served:
- from inside their root only;
- without dotfiles unless asked, and without listings;
- with nosniff, so a browser never runs a file as another type;
- with their own type. So an `.html` file is HTML on the app's origin, an `.svg` file is an image that runs its scripts when opened, and a file without an extension whose content looks like HTML is sniffed as HTML.
Never let users write to the static directory.
Errors ¶
The sentinel errors of this package, to be tested with errors.Is:
- ErrNotInitialized, ErrAlreadyInitialized, ErrClosed: as under Lifecycle.
- ErrNilLogger, ErrNilTemplateProvider, ErrNilRouter, ErrNilFS, ErrNilConfig, ErrNoConfigProvider: a dependency is missing, as under Lifecycle.
- ErrInvalidConfig: the configuration failed to bind, its tags or a rule.
- ErrInvalidFunc: a function's name or value, as under Adding functions.
- ErrInvalidName, ErrPageNotFound: as under Names.
- ErrLayoutNotFound, ErrBlockNotFound, ErrNoFragment: the template to execute is not in the page's set.
- ErrInvalidOption, ErrInvalidStatus: as under Blocks and Status and writes, and StaticHandler's options.
- ErrInvalidPrefix: StaticHandler's prefix.
- ErrLoad: the store failed to list or read; it wraps the store's error.
- ErrCompile: a template failed to parse, defines a name reserved for files, or shares or lacks a page name; it wraps html/template's parse error.
- ErrExecute: a page failed to execute; it wraps html/template's error, so that errors.As reaches a text/template.ExecError or an html/template *Error, and a function's own error.
- ErrWrite: the response writer failed; it wraps its error.
Every error starts with ServiceName and the operation, and, for a render of a valid name, the quoted page name. Reload joins the errors of the pages that failed, one per line.
A configuration that fails its tags gets the validator's error after `gas/ui: init: invalid config: validate config: `, such as:
Key: 'Config.UI.LayoutName' Error:Field validation for 'LayoutName' failed on the 'required' tag
The other errors, as returned, with `render` standing for each operation that can fail the same way:
gas/ui: logger is nil
gas/ui: template provider is nil
gas/ui: init: config is nil
gas/ui: init: no config provider
gas/ui: init: invalid config: UI.Extensions must hold at least one extension
gas/ui: init: invalid config: UI.Extensions[0] must be a dot and characters, none a slash, backslash or NUL
gas/ui: init: invalid config: UI.PagesPrefix must be empty or a clean path ending in /, not in layouts/ or partials/
gas/ui: init: invalid config: UI.StaticPath must be set when static files are served and UI.StaticPaths is empty
gas/ui: init: invalid config: UI.StaticPath must start with `/`, hold `*` only last, and pair `{` with `}`
gas/ui: init: invalid config: UI.StaticPaths[0] must start with `/`, hold `*` only last, and pair `{` with `}`
gas/ui: init: invalid config: UI.StaticStripPrefix must be empty or start and end with `/`
gas/ui: init: invalid config: UI.StaticMaxAge must be 0 or at least 1s
gas/ui: init: invalid config: UI.StaticDir cannot be opened as a directory: no such file or directory
gas/ui: init: invalid func: "bad-name": not a Go identifier
gas/ui: init: router is nil
gas/ui: init: file system is nil
gas/ui: init: service already initialized
gas/ui: init: context canceled
gas/ui: register funcs: invalid func: "f": nil
gas/ui: register funcs: invalid func: "f": not a function
gas/ui: register funcs: invalid func: "f": must return one value, or a value and an error
gas/ui: register funcs: invalid func: "html": reserved by html/template
gas/ui: register funcs: service closed
gas/ui: render: invalid name: empty
gas/ui: render: invalid name: not valid UTF-8
gas/ui: render: invalid name: holds a NUL byte
gas/ui: render: invalid name: holds a backslash
gas/ui: render: invalid name: not a clean slash path
gas/ui: render "users": service not initialized
gas/ui: render "users": service closed
gas/ui: render "users": context canceled
gas/ui: render "users": page not found
gas/ui: render "users": invalid option: nil
gas/ui: render "users": invalid option: WithBlock applies to RenderFragment only
gas/ui: render fragment "users": invalid option: WithLayout applies to Render only
gas/ui: render "users": invalid status: must be 200 to 599, and not 204 or 304
gas/ui: render "users": layout not found: "base"
gas/ui: render fragment "users": block not found: "sidebar"
gas/ui: render fragment "users": no fragment: the page defines no "content" block and has no top-level text
gas/ui: render "users": load templates failed: store down
gas/ui: render "users": load templates failed: "users.html": store down
gas/ui: render "users": compile failed: template: users.html:1: function "nope" not defined
gas/ui: render "u": compile failed: u.html defines "home.html", a name ending in an extension, which only files have
gas/ui: render "a": compile failed: "a.htm" and "a.html" are both page "a"
gas/ui: reload: compile failed: ".html" leaves no page name
gas/ui: render "u": execute failed: template: u.html:1:2: executing "u.html" at <fail>: error calling fail: boom
gas/ui: render "users": write failed: client gone
gas/ui: ready: load templates failed: store down
gas/ui: static handler: file system is nil
gas/ui: static handler: invalid prefix: must be empty or start and end with `/`
gas/ui: static handler: invalid option: nil
gas/ui: static handler: invalid option: max age must be 0 or at least 1s
Index ¶
- Constants
- Variables
- func New[T gas.TemplateProvider](opts ...Option) func(T, *gas.Router, gas.ConfigProvider, gas.Logger) (*Service, error)
- func StaticHandler(prefix string, fsys fs.FS, opts ...StaticOption) (http.Handler, error)
- type Config
- type Option
- type Provider
- type RenderOption
- type RenderOptions
- type Service
- func (s *Service) CheckReady(ctx context.Context) error
- func (s *Service) Close(context.Context) error
- func (s *Service) Config() Config
- func (s *Service) Init(ctx context.Context) error
- func (*Service) Name() string
- func (s *Service) RegisterFuncs(funcs template.FuncMap) error
- func (s *Service) Reload(ctx context.Context) error
- func (s *Service) Render(ctx context.Context, w http.ResponseWriter, name string, data any, ...) error
- func (s *Service) RenderFragment(ctx context.Context, w http.ResponseWriter, name string, data any, ...) error
- type Settings
- type StaticOption
Constants ¶
const ( // DefaultStaticDir is the directory static files are served from in // DefaultConfig: none, so that no static files are served unless // configured. DefaultStaticDir = "" // DefaultStaticPath is the route static files are served on in // DefaultConfig. DefaultStaticPath = "/static/*" // DefaultLayoutName is the name of the template Render executes in // DefaultConfig. DefaultLayoutName = "base" // DefaultFragmentBlock is the name of the block RenderFragment // executes in DefaultConfig. DefaultFragmentBlock = "content" // DefaultExtension is the one template extension of DefaultConfig. DefaultExtension = ".html" // LayoutsPrefix starts the name of every layout in the template // store. LayoutsPrefix = "layouts/" // PartialsPrefix starts the name of every partial in the template // store. PartialsPrefix = "partials/" )
const ServiceName = "gas/ui"
ServiceName is the name of the service, returned by Service.Name and prefixed to every error the package returns.
Variables ¶
var ( // ErrNotInitialized indicates that a method was called before the // service's first successful Init. ErrNotInitialized = errors.New("service not initialized") // ErrAlreadyInitialized indicates that Init was called on a service // that is initialized. ErrAlreadyInitialized = errors.New("service already initialized") // ErrClosed indicates that a method was called after Close, before // Init succeeded again. ErrClosed = errors.New("service closed") // ErrNilLogger indicates that the constructor was given a nil logger. ErrNilLogger = errors.New("logger is nil") // ErrNilTemplateProvider indicates that the constructor was given a // nil gas.TemplateProvider. ErrNilTemplateProvider = errors.New("template provider is nil") // ErrNilRouter indicates that Init has static files to serve and no // router to serve them on. ErrNilRouter = errors.New("router is nil") // ErrNilFS indicates that WithStaticFS or StaticHandler was given a // nil fs.FS. ErrNilFS = errors.New("file system is nil") // ErrNilConfig indicates that WithConfig was given a nil // configuration. ErrNilConfig = configsrc.ErrNilConfig // ErrNoConfigProvider indicates that there is neither a configuration // given to WithConfig nor a ConfigProvider to bind one from. ErrNoConfigProvider = configsrc.ErrNoConfigProvider // ErrInvalidConfig indicates that the configuration failed to bind, // failed its validate tags, or broke one of the service's rules. ErrInvalidConfig = configsrc.ErrInvalidConfig // ErrInvalidFunc indicates that a template function has a name that is // not a Go identifier, or a value that is nil, not a function, or a // function html/template cannot call. ErrInvalidFunc = errors.New("invalid func") // ErrInvalidName indicates that a page name is not one a page can // have. ErrInvalidName = errors.New("invalid name") // ErrPageNotFound indicates that the template store holds no page of // the name. ErrPageNotFound = errors.New("page not found") // ErrLayoutNotFound indicates that a page's set defines no template of // the layout's name. ErrLayoutNotFound = errors.New("layout not found") // ErrBlockNotFound indicates that a page's set defines no template of // the name given to WithBlock. ErrBlockNotFound = errors.New("block not found") // ErrNoFragment indicates that a page has neither the fragment block // nor top-level text. ErrNoFragment = errors.New("no fragment") // ErrInvalidOption indicates that a render or static option is nil, // does not apply to the method, or holds a value out of its bounds. ErrInvalidOption = errors.New("invalid option") // ErrInvalidStatus indicates that WithStatus was given a status that is // not 200 to 599, or that allows no body. ErrInvalidStatus = errors.New("invalid status") // ErrInvalidPrefix indicates that StaticHandler was given a prefix // that is not empty and does not start and end with `/`. ErrInvalidPrefix = errors.New("invalid prefix") // ErrLoad indicates that the template store failed to list or read // templates. ErrLoad = errors.New("load templates failed") // ErrCompile indicates that a template failed to parse, defines a name // reserved for files, or shares its page name with another. ErrCompile = errors.New("compile failed") // ErrExecute indicates that executing a page failed. ErrExecute = errors.New("execute failed") // ErrWrite indicates that writing a rendered page to the response // failed. ErrWrite = errors.New("write failed") )
The sentinel errors of the package, as described in the package documentation. An error the package returns starts with ServiceName and the operation, and wraps one of these, or a context's error.
Functions ¶
func New ¶
func New[T gas.TemplateProvider]( opts ...Option, ) func(T, *gas.Router, gas.ConfigProvider, gas.Logger) (*Service, error)
New returns the constructor of a Service with opts applied, in the shape the gas container expects: T is the type the template store is registered as, usually gas.TemplateProvider. The constructor returns an error wrapping ErrNilLogger for a nil logger and ErrNilTemplateProvider for a nil store; a nil ConfigProvider is accepted, and Init then requires WithConfig; a nil router is accepted, and Init then requires that no static files are served.
func StaticHandler ¶
StaticHandler returns a handler that serves the files of fsys under the URL path prefix, as described under Static handler in the package documentation. prefix is empty, to remove nothing, or starts and ends with `/`; anything else is ErrInvalidPrefix. A nil fsys is ErrNilFS. To serve a directory, pass the FS of an os.Root, which keeps every file, through symlinks too, inside it.
Types ¶
type Config ¶
type Config struct {
// UI holds the settings.
UI Settings
}
Config holds the service's configuration, read from the `ui` section.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns the configuration the service starts from before binding: DefaultExtension, DefaultStaticDir, DefaultStaticPath, DefaultLayoutName and DefaultFragmentBlock, and every other setting zero.
type Option ¶
type Option func(*Service)
Option configures a Service. Options only record what they are given; Init checks it.
func WithConfig ¶
WithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init copies *cfg, and its slices, each time it runs and never changes it; the copy is checked against its validate tags as a bound configuration is. A nil cfg makes Init fail with ErrNilConfig.
Default: bind the `ui` section from the ConfigProvider over DefaultConfig.
func WithFuncs ¶ added in v0.6.0
WithFuncs adds funcs to the template functions, over the defaults, as RegisterFuncs does. Init checks them, and fails with ErrInvalidFunc for one RegisterFuncs refuses. The map is copied; a nil map adds nothing.
Default: the default functions only.
func WithStaticFS ¶
WithStaticFS makes the service serve static files from fsys, such as an embed.FS, instead of the StaticDir setting. A nil fsys makes Init fail with ErrNilFS.
Default: the StaticDir setting.
type Provider ¶ added in v0.6.0
type Provider interface {
// Render executes the page name through its layout and writes it to
// w, or writes nothing and returns an error.
Render(
ctx context.Context,
w http.ResponseWriter,
name string,
data any,
opts ...RenderOption,
) error
// RenderFragment executes the fragment of the page name, without its
// layout, and writes it to w, or writes nothing and returns an error.
RenderFragment(
ctx context.Context,
w http.ResponseWriter,
name string,
data any,
opts ...RenderOption,
) error
// RegisterFuncs adds funcs to the functions every page can call, or
// adds none and returns an error.
RegisterFuncs(funcs template.FuncMap) error
}
Provider renders the pages of a template store as HTML, as described under Contract in the package documentation. Service implements it, and uitest.MockUI mocks it.
type RenderOption ¶ added in v0.6.0
type RenderOption func(*RenderOptions)
RenderOption configures one Render or RenderFragment call, as described in the package documentation.
func WithBlock ¶ added in v0.6.0
func WithBlock(name string) RenderOption
WithBlock makes RenderFragment execute the template name of the page's set instead of the page's fragment. An empty name keeps the fragment. Render refuses it with ErrInvalidOption.
func WithLayout ¶ added in v0.6.0
func WithLayout(name string) RenderOption
WithLayout makes Render execute the template name of the page's set instead of the LayoutName setting. An empty name keeps the setting. RenderFragment refuses it with ErrInvalidOption.
func WithStatus ¶ added in v0.6.0
func WithStatus(status int) RenderOption
WithStatus makes Render and RenderFragment write status before the page. It must be 200 to 599 and allow a body, so not 204 or 304, or the call fails with ErrInvalidStatus and writes nothing. 0 writes no status.
Default: no status; the response writer sends 200 on the first write unless the handler wrote another.
type RenderOptions ¶ added in v0.6.0
type RenderOptions struct {
// Layout is from WithLayout: the template Render executes, empty for
// the LayoutName setting.
Layout string
// Block is from WithBlock: the template RenderFragment executes,
// empty for the page's fragment.
Block string
// Status is from WithStatus: the status written before the page, 0
// for none.
Status int
}
RenderOptions are the options of a render, resolved, as ApplyRenderOptions returns them.
func ApplyRenderOptions ¶ added in v0.6.0
func ApplyRenderOptions(opts ...RenderOption) RenderOptions
ApplyRenderOptions returns opts resolved in order, a later option overriding an earlier one; nil options are skipped. Render and RenderFragment refuse a nil option instead.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service renders the pages of a template store as HTML and serves static files, as described in the package documentation. It is safe for concurrent use.
func (*Service) CheckReady ¶
CheckReady reports readiness: an error wrapping ErrNotInitialized or ErrClosed when the service is not initialized, the context's error when ctx has ended, and the error of the last build when no set renders can use exists, and else nil. When no build has been tried, it runs the first within ctx, as a render would. A page that fails to compile does not fail it.
func (*Service) Close ¶
Close makes every later call but Init return an error wrapping ErrClosed and the static routes answer 503, and closes the static directory. In-flight renders and files complete. The functions given to RegisterFuncs stay. Close on a service that is not initialized returns nil and logs nothing. It ignores its context.
func (*Service) Config ¶ added in v0.6.0
Config returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Its slices are copies too, so nothing done to the result reaches the service.
func (*Service) Init ¶
Init resolves and checks the configuration, opens the static directory and registers the static routes, as described in the package documentation. It compiles no template. On an initialized service it returns ErrAlreadyInitialized and changes nothing. A failed Init closes what it opened and leaves the service as it was.
func (*Service) RegisterFuncs ¶
RegisterFuncs adds funcs to the functions every page can call, as described in the package documentation. It checks every function first and adds none when one fails, with an error wrapping ErrInvalidFunc. A name already registered, or a default's, is replaced, and a warn-level log says so. The next render compiles the pages again. The functions outlive Close and every later Init.
func (*Service) Reload ¶ added in v0.6.0
Reload compiles every page again now, reading the store within ctx, as described in the package documentation. It returns the error of a build that failed as a whole, after which renders keep the set before it, or the joined errors of the pages that failed to compile.
func (*Service) Render ¶
func (s *Service) Render( ctx context.Context, w http.ResponseWriter, name string, data any, opts ...RenderOption, ) error
Render executes the page name with data through its layout and writes it to w, as described in the package documentation. On error it writes nothing.
func (*Service) RenderFragment ¶
func (s *Service) RenderFragment( ctx context.Context, w http.ResponseWriter, name string, data any, opts ...RenderOption, ) error
RenderFragment executes the fragment of the page name with data, without its layout, and writes it to w, as described in the package documentation. On error it writes nothing.
type Settings ¶
type Settings struct {
StaticDir string
StaticPath string
StaticStripPrefix string
PagesPrefix string
LayoutName string `validate:"required"`
FragmentBlock string `validate:"required"`
Extensions []string
StaticPaths []string
StaticMaxAge time.Duration `validate:"min=0"`
StaticDotfiles bool
Reload bool
}
Settings are the service's settings, as described in the package documentation.
type StaticOption ¶ added in v0.6.0
type StaticOption func(*staticOptions)
StaticOption configures a static handler.
func WithDotfiles ¶ added in v0.6.0
func WithDotfiles(allow bool) StaticOption
WithDotfiles makes the handler serve, when allow is true, files whose path holds an element that starts with `.`, such as `.well-known/x` or `.env`.
Default: false; such a path is not found.
func WithErrorFunc ¶ added in v0.6.0
func WithErrorFunc(f func(r *http.Request, err error)) StaticOption
WithErrorFunc makes the handler call f with the request and the error of each file it answers with 500 Internal Server Error, such as a read that failed; f may log it. A nil f is no call.
Default: no call.
func WithMaxAge ¶ added in v0.6.0
func WithMaxAge(d time.Duration) StaticOption
WithMaxAge makes the handler send `Cache-Control: public, max-age=N` with every file, N being d in whole seconds. d must be 0 or at least a second, or StaticHandler fails with ErrInvalidOption; 0 sends no header.
Default: 0.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
configsrc
Package configsrc resolves the ui service's configuration: from a copy of the one given to its WithConfig option, or else by binding its defaults from a gas.ConfigProvider.
|
Package configsrc resolves the ui service's configuration: from a copy of the one given to its WithConfig option, or else by binding its defaults from a gas.ConfigProvider. |
|
conformance
Package conformance holds the tests of the ui.Provider contract that the ui service keeps over every template store: the rules of the ui package documentation, checked against a service over a store built by the caller.
|
Package conformance holds the tests of the ui.Provider contract that the ui service keeps over every template store: the rules of the ui package documentation, checked against a service over a store built by the caller. |
|
Package uitest holds a mock of ui.Provider, MockUI, for tests of code that renders pages.
|
Package uitest holds a mock of ui.Provider, MockUI, for tests of code that renders pages. |