rest

package
v0.0.0-...-164d735 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: 0BSD Imports: 51 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rest provides a REST API transport.

var API struct {
	api.Specification `www:"https://api.example.com/v1"`

	Echo func(message string) string `rest:"GET /echo?message=%v"`
}

The www tag names the host that a client linked by API calls when it is linked with none of its own. When Echo is called, it calls the function over HTTPS/REST to 'https://api.example.com/v1/echo' and returns the result (if there is an error and the function doesn't return one, it will panic).

The functions of an API that have rest tags are served by Handler, and by ListenAndServe:

API.Echo = func(message string) string { return message }
rest.ListenAndServe(":"+os.Getenv("PORT"), nil, &API)

This starts a local HTTP server and listens on PORT for requests to /echo and responds to these requests with the defined Echo function. Arguments and Results are automatically converted to the Content-Type where possible.

You can return receive-only channels which will be served to clients as a websocket, or as server-sent events when the client asks for text/event-stream. A browser may only open the websocket from the API's own origin, or the one the Auth's AccessControl allows: an AllowOrigin of '*', which for a plain request means any origin, serves only the API's own origin here, as a browser sends its cookies with a websocket from any page.

The same goes for any request that a form could send, a POST of a form, of text/plain or of no body at all, which a browser sends from any page with the cookies and credentials it holds for the API, without asking CORS first. From another site, such a request is refused with 403 Forbidden, unless the AllowOrigin names that site, or is '*'. An AllowOrigin of '*' says that any site may call the API, so its forms reach the API with the caller's cookies and credentials, as intended: an API whose Auth reads either should name the origins it trusts. A request that a browser has to ask CORS about first, such as a POST of JSON or a DELETE, is left to what the AccessControl answers.

A nil channel is answered with 204 No Content, which a client linked by API returns as a channel that is closed.

Tags

Each API function can have a rest tag that formats function arguments (%v) to query parameters. Each tag must follow the space-seperated pattern:

GET /path/to/endpoint/{object=%v}?query=%v (argument,mapping,rules) result,mapping,rules
[METHOD](CONTENT_TYPE) [PATH] (ARGUMENT_RULES) RESULT_RULES

It begins with a METHOD, followed by an optional body CONTENT_TYPE then with a PATH format string that descibes how the function arguments are mapped onto the HTTP path & query. This is an extension of http.ServeMux with support for fmt rules and content types.

The CONTENT_TYPE (when unspecified) defaults to application/json. A response is in the first type the client's Accept header lists that the API can encode. A client that sends no Accept header, or only the range that matches every type, is answered with:

  • text/plain for one result whose declared type is no struct, array, slice or map, when it has a text form: a string, number or boolean, nil, or a value with MarshalText, Error or String.
  • application/json for the rest, time.Time and []byte included.

A client that takes none of the types on offer is answered with 415, and the types there are in an Accept-Encoding header. application/xml is only on offer for a result that encoding/xml can write: not for a map, or for a struct that holds one, nor for what has no name to call its element by, as []byte has not.

As text/plain a list has a line to an element, but a []byte is its bytes, and a slice that reads itself with an UnmarshalJSON method is one value: it is written as it is in a query, as its JSON, without the quotes when that is a string. A text/plain body is read the same way, so a list is a line to an element. What holds other values and has no text form of its own, a struct, a map or an array, is JSON in a text/plain body, and a list of them a line of JSON to an element.

A nil pointer for the body is sent as null in JSON, which the function gets as a pointer to a zero value. No other type has a null, so the body is left empty, and the function gets nil again, unless an empty body is a value of what the pointer is to, as it is of a string.

The path can contain path expansion parameters {name=%v} or ordinary format parameters %v (similar to the fmt package). Think of the arguments of the function as the parameters that get passed to a printf call. Imagine it working like this:

http.Get(fmt.Sprintf("/path/with/%v?query=%v", value, query))

If the query parameter is untitled, then the value will be expanded as key-value query parameters. This applies to structs and maps:

GET /path/to/endpoint?%v

If a path or query expansion parameter omits a format parameter, the value will be considered to be nested within a struct argument and the name of the parameter will be used to look for the first matching field in subsequent body structures. Either by field name or by rest tag.

POST /path/to/endpoint/{ID}
{
	ID: "1234",
	Value: "something"
}

A GET, HEAD, DELETE, OPTIONS or TRACE has no body for the rest of such a struct to travel in: a client linked by API sends only the fields its path and query name, and a body that comes with one is still read. An argument that the path and query name no part of is the body of the request whatever the method, as the function is not called without it, and beside one the struct is sent whole, in its place among the arguments of the body. Not everything between a client and a server passes on the body of a GET, so a function with such an argument is better off as a QUERY or a POST.

If a path expansion parameter is suffixed with an asterisk, then it takes the rest of the path, ie. slashes in the value will be added to the path as-is. The value is all of what was sent, a trailing slash included, and http.Request.PathValue has it under its name with and without the asterisk. A value cannot start with a slash, as an absolute path does: the two slashes it makes in the path match no route, so a client linked by API returns an error in place of sending it.

POST /prefix/{path*=%v}

A client linked by API writes a value in a path, a query or a text/plain body with its type's own MarshalText or MarshalJSON method when it has one, and returns the error of a method that fails instead of sending the value empty. A value without one is written as %v prints it. A string, number or boolean whose type has a String method is written by its kind all the same, as that is how it is read, unless the type has one of the methods below to read what String prints. A time.Duration is written and read as it prints.

A value in a path, a query or a text/plain body is read by its type's own UnmarshalText, UnmarshalJSON or Scan method when it has one, whatever kind of type it is, and a value the method refuses is answered with 400 before the function is called. Only a type without one is read by its kind. JSON and XML bodies are read by encoding/json and encoding/xml, so UnmarshalText is the one method that every way in asks: a type that checks its values belongs there.

A number in a path, a query or a text/plain body is written in decimal. NaN and the infinities are answered with 400.

A value in the path cannot be empty, as the path without it is that of another resource. A client linked by API returns an error for an empty one, or a nil pointer, in place of sending it.

A list in a path is separated by commas, and a comma that is part of an element is sent escaped, as %2C. Handlers served by another router than Handler's see the path decoded, and split it at every comma.

A parameter that is sent empty counts as left out, and the function gets the zero value. So does an empty element of a list, nil in a list of pointers, unless the element's type has one of those methods to read it, when it is asked to. An empty value for a pointer to a string in a query is a pointer to the empty string.

ARGUMENT_RULES are optional, they are a comma separated list of names to give the remaining arguments in the JSON body of the request. By default, arguments are posted as an array, however if there are ARGUMENT_RULES, the arguments will be mapped into json fields of the name, matching the argument's position.

foo func(id int, value string) `rest:"POST /foo (id,value)"`
foo(22, "Hello World") => {"id": 22, "value":"Hello World"}

When the API implements api.WithSource (or api.RegisterSource has been called for its package) and every remaining body argument has a Go name, ARGUMENT_RULES default to those names. Explicit rules always win. A single body argument stays a raw body.

RESULT_RULES are much like ARGUMENT_RULES, except they operate on the results of the function instead of the arguments. They map named json fields to the result values.

getLatLong func() (float64, float64) `rest:"GET /latlong latitude,longitude"`
{"latitude": 12.2, "longitude": 15.0} => lat, lon := getLatLong()

RESULT_RULES similarly default to the Go result names when the API implements api.WithSource and every result is named.

As application/xml, arguments and results with rules are elements named by their rules, inside one named after the function. A list is its elements one after the other, with no element around them, and all of them are read back. The element of a value whose type has type arguments is named after the type without them.

Deleting

A client linked by API takes a 404 Not Found in answer to a DELETE for success, and returns no error: what was to be deleted is gone, which is what the call asked for. This is so whoever answered with the 404, so a DELETE sent to a server that does not have the route succeeds as well. Every other method returns an error for a 404.

Hidden Fields

A struct field tagged json:"-" is not part of the API in any format: it is left out of every response and never set from a request, and it is not a query parameter. Only a parameter that names the field in the rest tag reaches it. XML responses zero such a field, as XML tags alone decide which elements a struct has.

Limits

A request body decoded into arguments may be up to 32 MiB, a larger one is answered with 413. A body read by the function itself, through an io.Reader, io.ReadCloser or fs.File argument, is not limited.

A value of a stream, a websocket message or a server-sent event, may be up to 16 MiB to whoever reads it, the server and a client linked by API alike. The reader ends the stream at a larger one, which closes the channel: a channel has no way to say why it was closed, so a function that streams values is to keep them under the limit.

ListenAndServe reads a request's headers within 10 seconds and drops a connection that has sat idle for 2 minutes. A request that is in progress, such as a stream or a websocket, is never timed out.

Response Headers

In order to read and write HTTP headers in a request, values should implement the following interfaces.

type HeaderWriter interface {
	WriteHeadersHTTP(http.Header)
}

type HeaderReader interface {
	ReadHeadersHTTP(http.Header)
}

If multiple result values implement these interfaces, they will be called in the order they are returned. A server writes the headers of a result, which a client linked by API reads, and reads the headers of an argument from the request. The client does not write the headers of an argument: those are for the caller to send, with Header or the *http.Client the API is linked with. Here's an example:

type ProfilePicture struct {
	io.ReadCloser
}

func (ProfilePicture) WriteHeadersHTTP(header http.Header) {
	header.Set("Content-Type", "image/png")
}

type API struct {
	api.Specification

	GetProfilePicture func() (ProfilePicture, error)
}

Error Status and Retry-After

Errors may implement StatusHTTP() to set the HTTP status, and the following interface so the host writes a Retry-After header (delay-seconds) — typically on 429, 503, or 413. A non-positive duration omits the header. The REST client parses Retry-After from those error responses. A status below 200 or above 999 cannot end a response, and the error is sent as a 500.

type WithRetryAfter interface {
	RetryAfterHTTP() time.Duration
}

An error with a ContentTypeHTTP() string method that returns application/json is sent as its JSON encoding, where any other error is sent as its message. The status, headers and Retry-After are looked for inside an error that wraps another, but ContentTypeHTTP only on the error itself.

When the Auth's Redact replaces an error, all of the response is taken from the error it returns: nothing of the one it replaced is sent, its headers included.

Framework Compatibility

A handler of Handlers reads its path values with http.Request.PathValue. The routers of Echo and Gin set none, so a handler that was given none reads them from the path of the request, by the pattern it was yielded with. That works under a prefix the router adds as well, except for a pattern that ends in a remainder, which is only read from a path that starts with the pattern.

Echo

server := echo.New()
handlers, err := rest.Handlers(nil, &API, ":%s", "*")
if err != nil {
	t.Fatalf("failed to create handlers: %v", err)
}
for pattern, handler := range handlers {
	method, path, _ := strings.Cut(pattern, " ")
	server.Add(method, path, echo.WrapHandler(handler))
}

Gin

server := gin.New()
handlers, err := rest.Handlers(nil, &API, ":%s", "*%s")
if err != nil {
	t.Fatalf("failed to create handlers: %v", err)
}
for pattern, handler := range handlers {
	method, path, _ := strings.Cut(pattern, " ")
	server.Handle(method, path, gin.WrapH(handler))
}

Index

Constants

This section is empty.

Variables

View Source
var API api.Linker[string, *http.Client] = linker{}

API implements the api.Linker interface. Every function with a rest tag is linked: of two with one method and path, each calls that route.

Functions

func Handler

func Handler(auth api.Auth[*http.Request], impl any) (http.Handler, error)

Handler returns a HTTP handler that serves supported API types. Once it has matched a route, the request it hands on, which is what an Auth is given, has in its URL the part of the path that routing left, which is "/". RequestURI holds the path the client asked for.

func Handlers

func Handlers(auth api.Auth[*http.Request], impl any, param_format, remainder_format string) (iter.Seq2[string, http.Handler], error)

Handlers can be used to integrete with different HTTP routers, it returns an iterator over the endpoints in the API, with a path pattern of the form fmt.Sprintf("GET /path/"+param_format, param) so that parameter format can be transformed for compatibility with different routers. The remainder_format is used to format the path in the case that an asterisk is used at the end of a path to capture the remainder of the path (including slashes). Of two functions on one route, the one declared last serves it, and the route is yielded once.

func Header(name, value string) *http.Client

Header returns a new default HTTP client that injects the given header into each request.

func Interceptor

func Interceptor(ctx context.Context, fn func(req *http.Request, send func(*http.Request) (*http.Response, error)) (*http.Response, error)) context.Context

Interceptor returns a context in which every request that a linked REST API sends goes through fn. fn can inspect or change the request, send it (or a different one) with send, or not send it at all, and inspect, change or make up the response. A response fn returns is handled exactly as one from the network would be: decoded into the function's results, or into its error.

Interceptors nest: the outermost sees the request first and the response last. WebSocket connections are not intercepted.

func ListenAndServe

func ListenAndServe(addr string, auth api.Auth[*http.Request], impl any) error

ListenAndServe starts a HTTP server that serves supported API types. If the [Authenticator] is nil, requests will not require any authentication, and an error the app returns is answered with its status text alone, as there is no Redact to declare what of it the caller may see.

The server reads a request's headers within 10 seconds and drops a connection that has sat idle for 2 minutes, but never times out a request that is in progress, so a stream or a websocket is served for as long as it lasts.

Types

type RequestWriter

type RequestWriter struct {
	io.Writer
	// contains filtered or unexported fields
}

func (RequestWriter) Header

func (w RequestWriter) Header() http.Header

func (RequestWriter) WriteHeader

func (w RequestWriter) WriteHeader(status int)

Jump to

Keyboard shortcuts

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