Go#
The Go generator writes one file, into the package you name. Enable it with a
[tool.model.go] table:
[tool.model.go]
out = "internal/catalog/catalog.go"
package = "catalog"
Every struct gets JSON codecs and a Validate() method. Everything beyond
that is an opt-in feature — see Configuration.
The runtime module#
Generated Go is not self-contained. The support types it leans on live in one
module, gitlab.com/terryp/model/go-runtime, and every generated file imports
it. Add it to the module that holds the generated file:
go get gitlab.com/terryp/model/go-runtime
Generation itself needs the dependency in place: a model with routes type-checks the target package between passes, and that fails if the import cannot be resolved.
The support types used to be copied into each generated file. That made a
small output mostly scaffolding, and it made two generated packages in one
program unable to talk to each other — each had its own Optional[T] and its
own ValidationError, distinct types as far as Go was concerned. Sharing one
module fixes both.
The generator imports each package under a fixed alias, so generated declarations read the way this table spells them.
Import path |
Alias |
What it holds |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
— |
|
|
|
|
|
— |
|
|
— |
|
Generated code never imports the last two, though the REST handlers write
an upload through fsedit; you call them yourself.
The go-runtime API documents all seven.
Everything under …/go-runtime/gen is a generator implementation detail: the
validation walk, the yaml, toml and etree helpers, the pgx converters, the
REST handlers. Those identifiers are exported only because generated code sits in
your package and cannot reach unexported ones. They carry no compatibility
promise and may change in any release. Nothing outside generated code should
name them.
Only the root package is unconditional. It needs
github.com/shopspring/decimal, which a decimal map key uses. The feature
packages are separate so a consumer who enables no features never compiles
fyne or pgx: yamlx needs gopkg.in/yaml.v3, tomlx needs
github.com/pelletier/go-toml/v2 (v2.4.3 or later, for its unstable
marshaler interfaces), mapx needs both, xmlx needs
github.com/beevik/etree, fyne needs fyne.io/fyne/v2, pg, pgconv
and rest need github.com/jackc/pgx/v5, and fsedit, which rest
imports for uploads, needs golang.org/x/sys/unix. txn needs nothing
outside the standard library. Go only builds the ones your code actually
imports.
Structs#
type Product struct {
sku string
name string
price decimal.Decimal
tags []string
}
Fields are unexported and snake_case by default. The generated file
therefore has to live in the package that uses it — that is the whole design,
and it is why you add your own methods in sibling files of the same package.
Set pascal-case = true to get exported PascalCase fields instead; the
serialized keys do not change either way.
An optional field — required: false, and not a list or map — becomes
mdl.Optional[T]. Read it with IsSome, Get, or GetOrZero, and
build one with mdl.Some or mdl.None[T](). A list stays a plain []T and a
map becomes an mdl.Map[K, V], with absence carried by emptiness.
Each struct gets UnmarshalJSON and MarshalJSON always, plus
UnmarshalYAML/MarshalYAML under the yaml feature,
UnmarshalTOML/MarshalTOML under the toml feature, and FromXMLElement
under xml.
Datetimes#
A datetime field is a time.Time, and its Location is the zone it was
written in. On the wire it is RFC 9557
text, the timestamp followed by the zone’s IANA name in brackets, in JSON,
YAML and TOML alike, and as a map key:
2026-10-06T21:00:00-04:00[America/New_York]
A plain RFC 3339 timestamp decodes too, as do a TOML offset datetime and a
YAML timestamp. Z is the zone UTC, and a numeric offset is a zone fixed at
that offset, written back as 2026-10-06T21:00:00-04:00[-04:00]. Decoding
fails on a timestamp with no offset, an unknown zone name, or an offset the
zone does not have at that instant. A zone with no IANA name, such as
time.Local or a time.FixedZone, is written as its offset;
mdl.ZoneName gives the name a time is written with, and mdl.LoadZone
reads it back. Two datetimes compare by instant, so a map holds one key per
instant whatever its zone. PostgreSQL keeps the zone in a column of its own
(see Datetimes).
The zone names come from time.LoadLocation, which reads the system’s zone
files. A program that may run without them, in a scratch container or on
Windows, embeds Go’s copy: import time/tzdata in its main package, or
build with -tags timetzdata. The runtime leaves that choice to the program.
import _ "time/tzdata"
Maps#
A map field is an mdl.Map[K, V], not a Go map[K]V. A Go map compares
keys with ==, and Go gives no way to change that. Some key types cannot use
== at all: a big.Int and an mdl.Path hold slices. Others compare the
wrong things: two time.Time values for one instant in different zones are
not ==, and neither are the decimals 1.5 and 1.50. An mdl.Map compares
keys by their value, so each of these pairs is one key.
var levels mdl.Map[big.Int, string]
levels.Set(*big.NewInt(2), "low")
levels.Get(*big.NewInt(2)) // mdl.Some("low")
levels.SetDefault(*big.NewInt(3), "mid")
levels.Delete(*big.NewInt(2))
for height, label := range levels.All() { /* ... */ }
The methods follow Python’s MutableMapping: Get returns an
mdl.Optional[V], and there are Set, SetDefault, Delete, Pop,
Has, Len and Clear, and the iterators All, Keys and Values.
mdl.FromMap builds one from a Go map literal, and mdl.Collect from an
iterator.
The key type must be one of mdl.KeyType. That is a string, int, bool or
float64 kind, which includes every generated enum, or one of the types a
model field becomes: big.Int, mdl.Integer, decimal.Decimal,
time.Time, mdl.Date, mdl.TimeOfDay, mdl.Path, mdl.ISBN and
mdl.UUID. It is
also a generated reference type, such as AuthorRef, whose target’s key is
one of those. Two references are the same key when their Keys are. A plain
string key stays a string, so m.Get(name) needs no conversion.
A map keeps the order its keys were first set in, like a Python dict. It iterates, and writes JSON and YAML, in that order. TOML tables have no order, and a database reads a map back in key order.
Like a Go map, an mdl.Map is a handle: copies share their entries. The zero
value is an empty map that is ready to use. Its first Set allocates, so
call Set on the field or through a pointer, not on a copy of a zero map.
mdl.Map has a JSON codec but no YAML or TOML one, which keeps
gopkg.in/yaml.v3 and go-toml out of the root package. Encode a map through
the generated struct that holds it. With the yaml or toml feature
enabled, that struct’s Raw holds its maps in the generator-internal
mapx.Map, which adds both codecs.
The Raw wire form#
Every struct also gets an exported <Name>Raw: the same fields, exported
and tagged for encoding/json, gopkg.in/yaml.v3 and
github.com/pelletier/go-toml/v2, each in the Go type those libraries read
and write as the model’s wire form. It is the Go counterpart of the Python
*Raw pattern.
// A product with a required sku, an integer stock, an optional rating,
// and a list of tags.
type ProductRaw struct {
Sku *string `json:"sku" yaml:"sku" toml:"sku"`
Stock *mdl.Integer `json:"stock" yaml:"stock" toml:"stock"`
Rating *float64 `json:"rating,omitempty" yaml:"rating,omitempty" toml:"rating,omitempty"`
Tags []string `json:"tags,omitempty" yaml:"tags,omitempty" toml:"tags,omitempty"`
}
func (self *Product) FromRaw(raw *ProductRaw) error
func (self *Product) ToRaw() ProductRaw
A required or optional field is a pointer, nil when the key is absent or
null. A list or map that is not required carries its absence by being empty
instead. A referenced struct is its own Raw, a referenced union is its
<Union>Raw, an integer is mdl.Integer, which reads any integer-valued
number (30, 30.0, 1e2) and rejects a fraction, and a datetime is
mdl.ZonedTime, which writes its zone (see Datetimes). Every other type
is the one the struct holds.
FromRaw sets every field of the struct from the raw value, turning a nil
optional into mdl.None and an optional list that is nil or [] into nil. A
required list or map that is absent, null or empty reads as an empty, non-nil
value, so code holding a decoded value need not guard against nil, and it is
Validate that reports it, as required. Any other nil required field is an
error, a *mdl.ValidationError of kind required, so a document
that leaves one out fails to decode rather than reading as its zero value. Its
DataPath is the field’s dot path from the value decoded, as Validate
writes it: customer.email, products.0.price for an item of a list, or
prices.'usd'.amount for an entry of a map with string keys, the key quoted
as Python’s repr quotes it so it reads apart from a field. A map with any
other key names its entry by the key’s text form, unquoted.
Every missing field is reported, joined, so mdl.ValidationErrorsOf lists
them all.
A blank value, "" of a string type, is no value: a required field holding
one is missing, and an optional one is mdl.None. The string types are
string, path, url, password, secret, isbn, uuid, and a
reference whose key is one of these. An item of a list, or a key or value of a
map, can not be absent, so a blank one is reported missing at its own path, as
tags.1. The zero value of any other type, such as 0 or false, is a
value. A map is an mdl.Map in the Raw
too, or a mapx.Map wrapping one when YAML or TOML is enabled,
and an absent one is empty. ToRaw is the reverse. Every generated codec is
those two calls around the library: UnmarshalJSON is json.Unmarshal into
the Raw then FromRaw, and MarshalJSON is ToRaw then json.Marshal.
The YAML and TOML methods are the same, except that MarshalTOML edits the
document that a value was decoded from (see TOML documents). So a Raw
value nested in your own decoded type converts with FromRaw, and a format
this generator does not emit only needs the library that encodes it.
TOML documents#
A struct that UnmarshalTOML decodes remembers the document that it read.
MarshalTOML then edits that document instead of writing a new one. It
rewrites only the keys whose values changed, adds the keys that are new, and
removes the keys that are gone. Everything else stays as written: comments,
key order, dotted keys, inline tables, and the spelling of each value, such
as 'literal' and """multi-line""" strings, 0xFF and 1_000. So a
program can read a configuration file, change one setting, and write it back
without disturbing the rest.
var cfg Config
if err := cfg.UnmarshalTOML(data); err != nil {
return err
}
cfg.port = 9090
data, err := cfg.MarshalTOML() // only the port line changes
The edit is made by tomledit, which lays out the whitespace of an edited document again: the space before a trailing comment, inside an inline table, and between sections. A value that has not changed gives back the document byte for byte.
A value that changed is written as go-toml writes it. A changed string is
'quoted'again, whatever its quotes were.A changed array is written whole. An array of tables whose length did not change is edited one table at a time. One whose length changed is written again, as new
[[sections]]at the end of its table.When a change has no place in the document, or the edited document does not read back as the value,
MarshalTOMLwrites a new document as though the value had none.A value that you make, rather than decode, has no document, and
MarshalTOMLwrites a new one. The other codecs never use the document.The document is an unexported field. Like the stored key,
==andreflect.DeepEqualcompare it: two values decoded separately are not equal, even from one document.
Source files#
A top_level struct with a source path
is read from a file of its own, and the source field holds that file’s path.
The Raw keeps the field, so REST and PostgreSQL carry it like any other. A
file does not: the struct also gets <Name>RawFile, its Raw without the
source field, and four methods that use it.
// A manuscript whose file field is its source path.
type ManuscriptRawFile struct { /* every field but file */ }
func (self *Manuscript) ToRawFile() ManuscriptRawFile
func (self *Manuscript) FromRawFile(file *ManuscriptRawFile) error
func (self *Manuscript) ReadFile(fsys fs.FS, name string) error
func (self *Manuscript) MarshalFile() ([]byte, error)
ReadFile reads name from fsys, decodes the file form, and sets the
source field to name’s absolute path in fsys: drafts/a.toml becomes
/drafts/a.toml. A source key in the file is ignored. FromRawFile keeps
the source field’s current value, and sets every other field.
MarshalFile encodes the file form, so the source path is never written.
It writes nothing: write the bytes with os.WriteFile, or with
fsedit.Write to commit them with the request’s transaction. An optional
source field that is not set returns mdl.ErrNoValue.
Both methods pick the format from the file’s extension with
mdl.FormatOf, which looks up the extension’s media type the way Python’s
mimetypes does: Go’s mime table and the system’s MIME database, then a
fallback for .yaml, .yml and .toml. JSON is always read and written.
YAML and TOML need their features. XML is read with the xml feature, for a
struct with an XML binding, and is never written. Any other format returns
an error wrapping errors.ErrUnsupported.
A path relative_to the source field resolves in the directory of the file,
so files kept beside it open with their With<Field> methods; see
Path roots. The source field always names a file, so it is not looked
up: a path beside a row’s file resolves before that file is written, as when
a new row is inserted with its file.
Validation#
func (self *Product) Validate() error
Validate collects rather than fails fast. It returns nil when the value is
clean, and otherwise an errors.Join of *mdl.ValidationError
values, one per violated constraint. Unpack them with
mdl.ValidationErrorsOf, or reach for a single one with errors.As:
if err := product.Validate(); err != nil {
for _, verr := range mdl.ValidationErrorsOf(err) {
log.Printf("%s: %s", verr.DataPath, verr.Message)
}
}
A struct with no constraints still gets a Validate — it just always returns
nil, so calling it is never conditional on which struct you hold.
Equality#
func (self *Product) Equals(other *Product) bool
Every struct, enum and union variant has an Equals that compares values
field by field. An optional field is equal when both are unset or both hold
equal values, a list when its items are equal in order, and a map when it
has the same keys, in any order, with equal values. A reference compares its
key, and a nested struct or union its own Equals. A datetime must have the
same instant and zone.
A secret compares in constant time inside guarded memory, so neither plaintext is copied out. A password equals another holding the same plaintext, or the same hash, but never a plaintext equal to its hash: telling those apart would mean checking the plaintext against the hash.
The field perms a REST endpoint checks compare a
field’s value with Equals.
Destroying secrets#
func (self *Credential) Destroy()
Every struct and union variant has a Destroy that wipes and releases the
guarded memory its secret and password fields hold. It reaches into the
structs and unions a field embeds, a list’s items, a map’s values, and a
set optional field. Copies share that memory, so a value must not be used
after it or any copy of it is destroyed. A password keeps a hash
already made from it, but Destroy never makes one. Every Destroy is safe
to call on a nil or zero value, and more than once. A struct with nothing to
wipe still has one, which does nothing.
The route wrappers destroy each request once the response is written.
Summaries#
A struct that declares a summary gets a type
holding what its summary reads, PersonSummary for Person, and methods to
fill and render it:
type PersonSummary struct {
Id big.Int // a top-level struct's primary key
Name string
Employer mdl.Optional[mdlsummary.Ref[CompanyRef, CompanySummary]]
Tags []string
}
func (self *Person) SummaryTitle() (mdlsummary.Markdown, error)
func (self *Person) SummarySubtitle() (mdlsummary.Markdown, error)
func (self *Person) SummaryData() PersonSummary
func (self *PersonSummary) RenderTitle() (mdlsummary.Markdown, error)
func (self *PersonSummary) RenderSubtitle() (mdlsummary.Markdown, error)
func (self *PersonSummary) ToRaw() PersonSummaryRaw
func (self *PersonSummary) MarshalJSON() ([]byte, error)
A summary holds only its summary fields, plus, for a top_level struct, its
primary key. Fields are named as the struct’s own are. An embedded struct is
held as its own summary type, and a ref as an mdlsummary.Ref: the
reference, and the summary of the row it names when that row was read.
RenderTitle and RenderSubtitle render the summary’s two lines from the
same fields. A summary with no subtitle has no RenderSubtitle or
SummarySubtitle. An embedded struct or a read ref shows its title.
SummaryData copies a value’s summary fields, its references unread, and
SummaryTitle and SummarySubtitle render that, so each ref in them shows
its key. With the postgres feature, GetSummaryT, ListSummariesT, and
SearchSummariesT read summaries from the database with every row they
refer to; see Summaries.
PersonSummaryRaw is the wire form of the summary’s fields, which
MarshalJSON writes. Each field is written the way PersonRaw writes it,
so a ref is its key. An embedded struct is written as its summary’s wire
form, and a url is always absolute. The rendered lines are not part of
the wire form. The REST listings send them beside the
fields, as Markdown and as HTML.
The result is inline Markdown. Its HTML method renders it as an HTML
fragment, with no <p> around the line and raw HTML omitted. For a terminal,
render it with any CommonMark renderer, such as
glamour.
The template is parsed when the package initializes, and a template that does
not parse panics there, so the first test that imports the package finds it.
An error from Render is an error executing the template, such as list
given a conjunction other than "and" or "or".
Enums#
type Priority int
const (
PriorityLow Priority = 0
PriorityMedium Priority = 1
PriorityHigh Priority = 2
)
var ErrInvalidPriority = errors.New("not a valid Priority")
func (self Priority) String() string
func (self Priority) Display() string
func (self Priority) IsValid() bool
func (self Priority) Equals(other Priority) bool
func ParsePriority(name string) (Priority, error)
func (self Priority) MarshalText() ([]byte, error)
func (self *Priority) UnmarshalText(text []byte) error
Go has one namespace per package, so each member is prefixed with its enum’s
name, as the standard library does it: member low is PriorityLow. A member
is exported exactly when its enum is. pascal-case does not change these
names.
String is a member’s name, and Display is its display, for showing to a
person.
Unions#
A union becomes a sealed interface plus one type per variant. A variant that
holds a struct or a union is a struct embedding it. Any other variant is a
type defined on its value’s type, such as type ReadingLabels []string.
Nothing outside the generated file can implement the interface, so the set of
variants is closed.
type Animal interface{ isAnimal() }
type AnimalTag string
const (
AnimalTagDog AnimalTag = "dog"
AnimalTagCat AnimalTag = "Cat"
)
type AnimalDog struct{ Pet }
type AnimalCat struct{ Pet }
Each variant has an Equals(other Animal) bool, true only for the same
variant holding an equal value, which the interface requires too.
Each variant also has a Destroy(), which the
interface requires too.
Each variant has a Validate() error, which reports a violation under the
value key its value is written with, such as value.name. An inlined
variant reports it at the struct’s own path, such as name.
Go has no match expression, so dispatch comes as two generated helpers — one for side effects, one that returns a value:
func MatchAnimalR0(value Animal, f0 func(*AnimalDog), f1 func(*AnimalCat))
func MatchAnimalR1[R any](value Animal, f0 func(*AnimalDog) R, f1 func(*AnimalCat) R) (zero R)
Both are exhaustive by construction: adding a variant to the model changes
their signatures, so every call site fails to compile until it handles the new
case. A nil value is a no-op for MatchAnimalR0 and the zero value for
MatchAnimalR1.
Serialization is by function rather than method, because the interface is what you hold:
func AnimalFromJSON(data []byte) (Animal, error)
func AnimalToJSON(value Animal) ([]byte, error)
func AnimalToYAML(value Animal) ([]byte, error) // yaml feature only
func AnimalToTOML(value Animal) ([]byte, error) // toml feature only
TOML has no null, so AnimalToTOML(nil) is an error rather than an encoded
form — unlike AnimalToJSON/AnimalToYAML, which encode a nil union as
null.
A union’s wire form is AnimalRaw, with one pointer per variant, holding the
wire form of the variant’s value. At most one is set, and none is a nil union.
It carries the discriminator: its UnmarshalJSON, UnmarshalYAML and
UnmarshalTOML read the tag and decode the value key into the matching
variant, and its marshalers write the tag and the value. An inlined variant
is decoded from, and written as, the object itself, its struct’s fields beside
the tag. AnimalFromRaw and
AnimalToRaw convert it. In TOML a union is written as an inline table,
because that is valid both under a key and in an array.
type AnimalRaw struct {
Dog *PetRaw
Cat *PetRaw
}
func AnimalFromRaw(raw AnimalRaw) (Animal, error)
func AnimalToRaw(value Animal) AnimalRaw
File unions#
A file union reads a file whose struct is named by its tag, and sets that struct’s source path as in Source files. It gets two functions:
func ReadHoldingFile(fsys fs.FS, name string) (Holding, error)
func MarshalHoldingFile(value Holding) ([]byte, error)
ReadHoldingFile reads the tag from the file, then decodes the rest of the
file as that variant’s struct, the same as its ReadFile, and sets the
source field. A missing or unknown tag is an error.
MarshalHoldingFile encodes the variant’s file form with the tag beside its
fields, in the format of the struct’s source path. A nil value, or a struct
whose optional source is not set, returns mdl.ErrNoValue. Both take JSON,
and YAML and TOML with their features. XML is not read or written through a
union, and returns an error wrapping errors.ErrUnsupported.
Path roots#
A path field with a root gets a With<Field> method, which opens the file
the path names. Roots and bases sets out how a
value resolves. [tool.model.go.roots] in model.toml maps each root name to
an opener, a function you write in the package that receives the
generated file:
[tool.model.go.roots]
books = "OpenBooks" # called as OpenBooks()
epub = "OpenEpub" # called as OpenEpub(ctx, self)
An opener returns (fs.FS, error). It takes an optional context.Context,
then optionally the struct that owns the path, as the method’s self: (),
(self), (ctx) or (ctx, self). The generator reads only whether the first
parameter is a context.Context and how many follow, so the Go compiler checks
the struct parameter’s type. It may be *Ebook, any, or a type parameter, so
one opener can serve several structs:
var books *os.Root // opened once, at startup
func OpenBooks() (fs.FS, error) {
return books.FS(), nil
}
// OpenEpub opens the .epub a book's archive field names, once per call.
func OpenEpub(ctx context.Context, self *Ebook) (fs.FS, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
rc, err := zip.OpenReader(self.archive)
if err != nil {
return nil, err
}
return rc, nil
}
The generator looks the openers up the way it reads route handlers, after its
first write. A root the table does not name, an opener it cannot find in the
package, or one taking any other parameters fails the build. The first write
stays behind, with each With method returning errors.ErrUnsupported, so the
package still compiles while you write the opener.
A plain path field’s method opens the field’s own value. A list of paths, or a
map keyed by paths, holds many values, so its method takes the one to open.
When the root’s opener takes a context, the method takes one first and passes
it on. Here cover and images are in the epub root:
func (self *Ebook) WithCover(ctx context.Context, use func(fsys fs.FS, name string) error) error
func (self *Ebook) WithImages(ctx context.Context, p mdl.Path, use func(fsys fs.FS, name string) error) error
Each call runs the opener once, resolves the value in the filesystem it
returns, and calls use with that filesystem and an fs.ValidPath name, which
fs.ReadFile, fs.Stat, fs.ReadDir and fsys.Open all take:
err := book.WithCover(ctx, func(fsys fs.FS, name string) error {
data, err := fs.ReadFile(fsys, name)
...
})
A path whose base is a field of its root (Root bases)
cannot find that field from its own struct. So its method takes the root
first, after any ctx, and then the index or key of the element that each *
in the dot path stands for:
func (self *Passage) WithFile(root *Anthology, storiesIndex int, use func(fsys fs.FS, name string) error) error
An optional field that is not set returns mdl.ErrNoValue without calling
the opener. A relative value whose optional base field is not set returns
mdl.ErrNoBase, and so does a root base whose index or key is not in the
root. A base that is not in the filesystem returns fs.Stat’s
error.
Closing. After use returns, the method closes the filesystem if it is
an io.Closer. So an opener either returns a new filesystem for each call,
like the *zip.ReadCloser above, or a shared one with no Close, like an
os.Root’s FS(). A shared one must be safe for concurrent use; os.Root
is. An opener that opens an .epub from another root has to keep that file
open until its own Close.
Symbolic links are the filesystem’s to follow. os.Root refuses a link
that leads outside the root, and any absolute link, rather than keeping it
inside. .. in the value itself is kept inside: it stops at the top of the
root.
Writing. A file upload writes into a root
whose opener returns an mdl.DirFS, a filesystem that is a directory on
disk and names it with Dir(). mdl.RootFS makes one of an os.Root:
func OpenBooks() (fs.FS, error) {
return mdl.RootFS(books), nil
}
The path resolves in the filesystem, so os.Root refuses a link out of the
root as it does for a read, and the file is written under Dir().
Recursion. An opener that opens a field in its own root calls itself without end. The generator cannot see inside an opener, so nothing checks this.
Serving a root#
A root endpoint serves a whole root over
HTTP. RegisterAllEndpoints registers it beside the routes, wrapped in the
same middleware and, with the auth feature, guarded by its perm.
Middleware sees it once, as an mdl.Route with method GET and the
endpoint’s path, whichever of its patterns a request matched.
Its root’s opener is the one [tool.model.go.roots] names, called once per
request and closed after it as for a With method. There is no struct to
hand it, so the opener must take nothing or only a context.Context; one that
takes a struct fails the build.
For path: /files/books/{path...}, a request for:
A file,
/files/books/a/b.txt, gets its content, withRange,If-Modified-SinceandHEADanswered byhttp.ServeContent, andX-Content-Type-Options: nosniffso a stored page cannot run as one of the server’s.A directory,
/files/books/a/, ends in/, as underhttp.FileServer. Without one,/files/books/ais redirected toa/, and a file asked for with one is redirected back to its own URL. The root itself is/files/books/, and/files/booksredirects there.When the request prefers HTML to JSON and YAML, as a browser’s
Acceptdoes, and the directory has anindex.html, that file is the answer.Otherwise the answer is the directory’s entries, sorted by name, as a list of
mdl.DirEntry: JSON, or YAML when theyamlfeature is on and the request asks for it.
[
{"name": "b.txt", "dir": false, "size": 1024, "modified": "2026-11-08T12:00:00Z"},
{"name": "sub", "dir": true, "size": 0}
]
A name that is not in the root is answered 404, one the filesystem refuses
with fs.ErrPermission 403, and any other error 500, each with an
application/problem+json body. A segment holding an escaped /, or a name
fs.ValidPath refuses, is a 404 before the opener is called. Links are the
filesystem’s to follow, as for a With method; serve an os.Root’s FS()
to keep them inside the root.
Routes#
Go is the only language that generates working HTTP serving from a route
type. You write the handler function named by the route’s go.handler; the
generator reads its signature and emits a wrapper that matches.
That is a two-pass build. model writes a compiling stub, runs a Go analyzer
over the output’s own package to read your handler signatures, then rewrites
the file with the real wrappers. So out must sit in the package that defines
the handlers. A handler the analyzer cannot find is reported as a route analysis: warning on standard error, and the stub is left in place — the
package still compiles.
Four handler shapes are accepted:
// Bare: nothing to decode, return, or encode. RouteHealth has no
// success_response, so a handler of it cannot return a model on success.
func HandleRouteHealth(w http.ResponseWriter, r *http.Request)
// Raw bytes, with a typed error response.
func HandleRouteBytes(r *http.Request) ([]byte, *ErrorResponse, error)
// Text, with an explicit status and headers.
func HandleRouteMessage(r *http.Request) (string, int, http.Header, error)
// A decoded request body and a model response.
func HandleRouteOpChanges(
w http.ResponseWriter,
r *http.Request,
req OptimizedStop,
) (RouteResponse, int, error)
Register them on an mdl.Router, and serve it:
router := mdl.NewRouter()
catalog.RegisterAllEndpoints(router)
http.ListenAndServe(":8080", router)
The _wrapHandle… functions RegisterAllEndpoints names are implementation
details. Do not call them.
Middleware#
RegisterAllEndpoints takes any number of mdl.Middleware after the router, and
wraps each route’s handler in them, the first outermost. A middleware is called
once per route, when the route is registered, with an mdl.Route describing
it: its model name, method, and path. So it decides per route, not per
request, and returns next unchanged for a route it leaves alone:
func requireLogin(route mdl.Route, next http.Handler) http.Handler {
if route.Name == "RouteHealth" {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !loggedIn(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
catalog.RegisterAllEndpoints(router, requireLogin)
When the model enables an extension,
RegisterAllEndpoints also takes a RouteExtensions before the middleware.
Each of its fields wraps the routes that set that extension’s key, outside the
middleware above, and is given each route’s value for the key:
catalog.RegisterAllEndpoints(router, catalog.RouteExtensions{RateLimit: ratelimit.Enforce}, requireLogin)
Middleware that wraps the whole router, such as DBMiddleware, still wraps it as
before, and so runs outside every route’s own.
Route perms#
With the auth feature, RegisterAllEndpoints takes an mdl.Authorizer
right after the router, and panics when it is nil:
catalog.RegisterAllEndpoints(router, auth, catalog.RouteExtensions{...}, requireLogin)
Each route checks its perm outside all
other middleware, extensions included. A route with no perm lets every
request through. Every request’s context carries auth, so a handler can
check perms of its own with mdl.Allowed.
Request bodies#
The wrapper decodes the body by content type: JSON, plus application/yaml
under the yaml feature and application/toml under the toml feature. A
body that fails to decode, or leaves out a required field, is answered 400
and never reaches your handler. A field a path placeholder
fills may be left out of the body, since the URL gives it. A body that
decodes but fails Validate() is logged as a warning and does reach your
handler — an invalid request is still a request, and only the
handler knows whether it can be served.
Once the response is written, the wrapper calls the request’s
Destroy, which wipes its passwords and secrets. It
does this even for a body that failed to decode. Your handler need not
destroy them itself, and must not keep them past its return. To keep a
password, store it, or call Hash first: a destroyed password keeps its hash
only if it already had one.
Merge patch bodies#
A merge_patch route’s handler takes
a <Request>Patch rather than the request. The generator declares that
type in the output, so a handler can name it before its wrappers exist:
func HandleRoutePreferences(r *http.Request, patch PreferencesPatch) (Preferences, error) {
prefs, err := loadPreferences(r.Context())
if err != nil {
return Preferences{}, err
}
if err := patch.Apply(&prefs); err != nil {
return Preferences{}, err
}
return prefs, savePreferences(r.Context(), prefs)
}
Apply merges the patch into the value, as a REST resource’s PATCH merges
into a row. A field the patch sets to null is cleared, and a field it
leaves out is unchanged. When the result does not decode, for example because
the patch clears a required field, Apply returns the error and leaves the
value as it was.
The wrapper takes the body as application/merge-patch+json or as
application/json, and answers any other content type 415 with an
Accept-Patch header. A body that isn’t a JSON object, or that doesn’t fit
the request struct (a string where it holds an integer, say), is answered
400. Neither reaches your handler.
Path placeholders#
A route whose path has {name} placeholders fills those request fields from
r.PathValue, after the body is decoded, so the URL wins over any value the
body gave. Such a route may have an empty body, which leaves every other field
absent: a GET whose required fields the URL all names needs none. A required
field the URL does not name must still be in the body, or the request is
answered 400. A segment that does not parse as its field’s type,
such as forty-two for an integer or an unknown enum member name, is answered
400 and never reaches your handler.
A {name...} wildcard fills a path field with mdl.ParsePath of the
segments it matches. The router unescapes that value, so %2Fa/b becomes the
absolute path /a/b. A value that is not a valid path, such as a%2F%2Fb,
which unescapes to a//b, is answered 400. The wildcard matches at least one
non-empty segment, so the empty path cannot be sent, and a URL that would
leave it none, such as /route/owners/3/tree/ or a trailing /, is answered
404.
The fields are filled only when your handler takes the request. A handler that
does not can still read r.PathValue itself.
Query strings#
A GET or HEAD request has no body a browser can send, so such a route
reads each request field its path does not name from the query string, after
the body and the path, so the query string wins over a body that a
non-browser client sent anyway. A field is read like a
path placeholder is: a string as it is, an integer
parsed, a UUID with mdl.ParseUUID, an enum by member name, a path with
mdl.ParsePath. A list of one
takes each repeat of its key as an item, in order, so ?tags=a&tags=b is
["a", "b"]. Any other field type cannot travel in a query string, and the
model fails to load. A key that is absent, or blank, leaves its field absent,
so a required one is answered 400, as is a value that does not parse.
Routing#
mdl.Router routes every endpoint the generator emits, routes and
REST endpoints alike, so one set of rules decides between them.
Serve it as the server’s handler, or mount it on a ServeMux with
mux.Handle("/", router), next to handlers of your own. It cleans a path
the way ServeMux does, redirecting a URL with a //, . or .. segment to
its cleaned form. Your handlers read r.PathValue and r.Pattern as they
would under ServeMux.
A path is written like a ServeMux pattern, with these differences:
{name}matches one non-empty segment.{name...}matches one or more non-empty segments, in any position, such as/route/owners/{owner}/tree/{location...}/meta.A path may hold several
{name...}wildcards, with a literal segment between each two, such as/move/{from...}/to/{to...}.A path may not end in
/: there are no subtree patterns. Write{name...}for one, or end the path in{$}to match exactly the trailing slash. The router also takes{name...}/{$}, one or more segments and a trailing slash, which{name...}alone never matches, for a root endpoint’s directories; a route’spathmay not use it.
A URL can split between several {name...} wildcards more than one way, so
each wildcard says how it splits: {name...} is greedy and takes as many
segments as the rest of the pattern allows, and {name...?} is lazy and takes
as few. For /move/a/to/b/to/c, {from...} gives from=a/to/b, to=c, and
{from...?} gives from=a, to=b/to/c. An escaped %2F stays inside its
segment, so a%2Fto%2Fb is never split. On the last wildcard the ? changes
nothing.
The most specific matching pattern wins, as under ServeMux. Two patterns are
compared segment by segment from the left, and the first difference decides: a
literal beats {name}, and {name} beats {name...}. When both have
{name...} in the same position and neither has another after it, the
segments after it are compared from the right in the same way, and the
pattern with more segments after it wins. So
/route/owners/{owner}/tree/{location...}/meta wins over the bare
/route/owners/{owner}/tree/{location...} for a URL that ends in /meta
after at least one more segment, and a location of two or more segments
whose last is meta cannot reach the bare route.
When either pattern has another {name...} after the shared one, the pattern
with more literal segments after it wins, then the one with fewer {name...}
after it. So /move/{from...}/to wins over /move/{from...}/to/{to...} for
/move/a/to. When they tie on both, the segments up to the next {name...} are
compared from the left again. Laziness plays no part in precedence.
Patterns that overlap are fine; precedence picks between them. Two patterns
with the same method and the same path up to wildcard names and laziness
match exactly the same URLs, so the model fails to load with two such routes,
generation fails when a route has the pattern of a REST endpoint, and
Router.Handle panics on one.
A GET pattern also serves HEAD. A URL that only other methods match is
answered 405, with an Allow header that lists them. A URL that no pattern
matches is answered 404. Both carry an application/problem+json body,
the shape the REST endpoints answer errors in.
A handler you register on a ServeMux that the router is mounted on, such as
mux.HandleFunc("GET /status", …), is more specific to ServeMux than the
router’s /, and takes precedence over it without an error. Register a
handler with router.HandleFunc("GET", "/status", …) instead to have it
follow the router’s rules.
Error responses and status#
Your error-response type is where a Go error becomes a response body. Two interfaces in the runtime module are the contract, and you implement them in the same package:
// Fill the response from an error.
func (e *ErrorResponse) FromError(err error)
// Optionally give the response its own status; 0 means "no opinion".
func (e *ErrorResponse) HttpStatus() int
The wrapper picks a status in a fixed order, taking the first that gives one:
the status your handler returned explicitly,
the error response’s
HttpStatus(),the error’s own
HttpStatus(), if it implementsmdl.StatusCoder,422for a validation error, and409for a unique or foreign-key violation,500.
A request the wrapper cannot read reaches FromError as an
*mdl.RequestError. That covers a body that does not decode and a path
parameter that does not parse. It is answered with 400 before any handler
runs. Its HttpStatus() says so too, so a FromError that tells client faults
from server faults finds it with errors.As, whether it asks for
*mdl.RequestError or for any mdl.StatusCoder.
An invalid struct response is logged as an error and sent anyway. The alternative — replacing your answer with a 500 — hides the bug behind a different one.
Next#
The go-runtime API — the
go-runtimemodule’s API.Go and PostgreSQL — reading and writing tables with the
postgresfeature.Go REST endpoints — generated REST endpoints for
top_levelstructs.The Go client — a Go client of the routes and REST endpoints.
Transactional file edits — editing files atomically, in step with the database.
Time input behavior — how a time-of-day entry reads what people type.