The Go client#

The Go client is a package that calls the endpoints the Go output serves, from another Go program: each route, and with [tool.model.go.rest] each REST resource. Enable it with a [tool.model.go-client] table:

[tool.model.go-client]
out = "internal/catalogapi/client.go"
package = "catalogapi"
pascal-case = true

It is a package of its own, apart from the server’s, and needs no [tool.model.go] table to build. Without one it calls the routes only, since the REST endpoints are whatever that table serves. Its fields are unexported unless pascal-case is set, so a client used from outside its package wants it.

The generated code imports gitlab.com/terryp/model/go-runtime/client as mdlclient, beside the rest of the runtime module; is its reference.

Types#

The client declares every struct, enum, and union of the model, with the same JSON codecs, Validate, and Equal as the server’s, but in the shape a response has (see perms):

  • A field whose read is false never reaches a client, so the client’s struct has no such field.

  • A field whose read names a perm is left out of a response to a request without it, so it is not required, whatever its required says, and is an mdl.Optional. A list or map is still a plain slice or map, which is empty when the response leaves it out.

A struct whose rows say whether a hidden field is set gets a method for each such field, whether or not the struct has the field:

row, err := client.Dossier().Read(ctx, id)
if row.Value.InformantPresent().GetOrZero() {
    // Saving a new informant replaces one.
}

It returns an mdl.Optional[bool], which is None if the response did not say, as for a request not told about the field or a value built rather than decoded. Writing the value never sends this answer back.

The client’s types have no With methods for their rooted paths, which only the server can open; a resource’s FileURL gives the URL of the file instead.

It declares a ref type for every top_level struct with a single key, whether the model refers to it or not, so another model can refer into this one and import it. A ref resolves through the client the context carries:

ctx = authapi.WithClient(ctx, client.WithCookiesFrom(r))
account, err := note.Owner.Resolve(ctx)

Resolve reads the row with the REST resource’s Read, and returns mdlclient.ErrNoClient from a context WithClient gave no client. A struct the server serves no REST resource of, or one keyed by a path, does not resolve: its Resolve returns errors.ErrUnsupported.

The client#

NewClient takes the server’s base URL, whose path, if any, prefixes every endpoint’s, and the *http.Client to send with, or nil for http.DefaultClient:

api, err := catalogapi.NewClient("https://catalog.example", nil)

A Client is a small value that is safe to share between goroutines. Its WithCookies and WithCookiesFrom methods return a copy that also sends some cookies. WithCookiesFrom copies an incoming *http.Request’s cookies, so a server handling that request calls the API as its user:

func handlePage(w http.ResponseWriter, r *http.Request) {
    stop, err := api.WithCookiesFrom(r).RouteStop(r.Context(), req)
    // ...
}

Since it is a copy, two requests being handled at once never send each other’s cookies.

Calling a route#

Each route is a method of Client named after the route. It takes the request and returns the decoded success body, or just an error for a route without a success_response:

func (c Client) RouteStop(ctx context.Context, req StopLookup) (StopLookup, error)
func (c Client) RouteHealth(ctx context.Context, req OptimizedStop) error

The method builds the URL the way the server parses it:

  • Each {name} placeholder is its field’s text as one escaped segment, and an enum is written by its member name.

  • A {name...} wildcard keeps its path’s / separators. An absolute path’s leading / is written as %2F, and a . or .. segment as %2E or %2E%2E.

  • A field that fills a placeholder but is absent, or empty, is an error, and then nothing is sent; errors.Is matches the absent case as mdlclient.ErrMissingPathParam.

A merge_patch route’s method takes the patch as JSON bytes, as a REST resource’s Patch does, and sends it as it is, so its nulls reach the server:

func (c Client) RoutePreferences(ctx context.Context, patch []byte) (Preferences, error)

A route with a body sends the request as JSON. A GET or HEAD route sends each field its path does not name in the query string instead: a list repeats its key once per item, and an absent or "" value is left out (see query strings).

A success status is decoded as the success_response. Any other status is decoded as the error_response, and is returned as an *mdlclient.RouteError[E], which errors.As finds:

_, err := api.RouteOpChanges(ctx, req)
var refused *mdlclient.RouteError[catalogapi.ErrorResponse]
if errors.As(err, &refused) {
    refused.Status // the HTTP status
    refused.Body   // the decoded ErrorResponse
}

A body the client cannot read as either, such as the router’s 404, is an *mdlclient.HTTPError, which carries the status and the raw body.

REST resources#

Each REST resource is a <Struct>Resource, which the Client method named after the struct returns. Its methods call the REST endpoints:

row, err := api.Book().Read(ctx, *big.NewInt(42))
row.Value // the Book
row.ETag  // its entity tag, for a conditional write

Method

Request

Path()

The collection’s path.

URL(id)

The row’s absolute URL, built as the server parses it.

Create(ctx, value)

POST the collection.

List(ctx, options)

GET the collection: a page of the rows’ summaries.

Read(ctx, id)

GET the row.

Replace(ctx, id, value, options)

PUT the row.

Patch(ctx, id, patch, options)

PATCH the row with patch, an RFC 7386 JSON merge patch.

Remove(ctx, id, options)

DELETE the row.

Query(ctx, text, options)

QUERY the collection, for a table with a search index.

Queries()

The struct’s declared queries, for a struct that declares any.

Summary(ctx, id)

GET the row’s summary, its ListItem alone.

ReferencedBy(ctx, id, options)

GET the rows that refer to the row, for a struct some reference names.

FileURL(id, field, steps...)

The absolute URL of a file a rooted path in the row names, for a struct with rooted paths.

Upload(ctx, id, field, steps, path, body, contentType)

POST body as the file at path, and set the rooted path to it.

<Field>FileURL(id)

The absolute URL of a file field’s content, for each such field.

Upload<Field>(ctx, id, content)

POST content as the file field’s content, which the server sniffs, and return the updated row.

A table keyed by a path reads a row through Read(ctx, id, options) (Row, *Page, error). When no row has that path, the *mdlclient.Page listing the rows under it is non-nil. Client.Search queries every searchable table at once.

Queries() returns a <Struct>Queries, which has a method for each query that the struct declares, named for the query in PascalCase. A method sends a QUERY of the collection with a JSON body. Its params are a <Query><Struct>Params, which holds the query’s params as fields, and a query that takes no params has no params argument. A method returns a page of the rows that the query selects, or, for a query that finds one row, that row:

page, err := api.Record().Queries().InCity(ctx, catalogapi.InCityRecordParams{City: "Springfield"}, mdlclient.PageOptions{})
row, err := api.Account().Queries().ByLogin(ctx, catalogapi.ByLoginAccountParams{Login: "ada"})

When such a query finds no row, the error is a 404 *mdlclient.Problem.

A write takes mdlclient.WriteOptions. Its ETag is sent as If-Match, so the write is refused with a 412 when the row has changed since it was read. A listing takes mdlclient.PageOptions, and returns an mdlclient.Page: its Items, and the Next and Prev page tokens from its Link header. To get those pages, pass a token back as PageOptions.Page.

A refused request’s error is an *mdlclient.Problem, the RFC 9457 body the server answered with. A response that is not a problem document, such as the router’s, still becomes one, with its status, and its text as the title. A success whose body does not decode is an *mdlclient.HTTPError.

Queries users write#

With the find feature, a resource’s Find sends a query in the query language, and lists the page it matches. The client does not parse it: the server is the one implementation, and a *Problem’s Position says where a query it refused went wrong.

page, err := client.Record().Find(ctx, "priority = high ORDER BY due_on", mdlclient.PageOptions{})