Documentation
¶
Overview ¶
Package mapget puts typed, self-describing endpoints on the standard library's http.ServeMux.
Go 1.22 gave ServeMux methods and wildcards, which covers matching a request to a handler. mapget adds what ASP.NET Core does around its router and the mux leaves to you: binding the request to a typed value, answering a malformed one, generating links, grouping routes, listing them and describing them as OpenAPI. The mux still does all the routing, and the package has no dependencies outside the standard library.
A request type carries its route, in the way a C# action carries [HttpGet("{id}")], and its fields say where each value comes from:
type GetOrder struct {
mapget.Route `route:"GET /orders/{id}"`
ID int `path:"id"`
Expand []string `query:"expand"`
}
func (s *Service) GetOrder(ctx context.Context, in GetOrder) (Order, error)
mux := http.NewServeMux()
app := mapget.New(mux)
mapget.Handle(app, svc.GetOrder)
Handle registers "GET /orders/{id}" on the mux. A request for /orders/42 calls GetOrder with ID 42 and writes the Order as JSON. A request for /orders/abc is answered with 404, because the field's type is the route constraint. A query value that does not parse is answered with a 400 problem details body that names every failing field.
The same type builds links, so an address is written in one place:
app.Path(GetOrder{ID: 42, Expand: []string{"lines"}}) // "/orders/42?expand=lines"
Tags ¶
Each exported field of a request type takes one of these tags. A field with none is left alone, except a field of type *http.Request, which is given the request.
path:"name" a wildcard from the pattern; never a pointer or slice query:"name" a query parameter; a slice takes every value header:"Name" a request header cookie:"name" a cookie body:"json" the request body, decoded as JSON
query, header and cookie take a ",required" option, and a separate default:"value" tag for when the value is absent. A pointer field is nil when the value is absent. Field types can be strings, booleans, integers, floats, time.Duration, or anything that implements encoding.TextUnmarshaler, such as time.Time or a UUID type.
A mistake in the tags is a panic when the route is registered, in the way the mux itself panics on a conflicting pattern: a path tag that names no wildcard, a wildcard with no field, a default that does not parse.
Validation ¶
If the request type has a Validate() error method, it runs after binding. Return FieldErrors for a 400 with messages by field, a *Problem for any other answer, or a plain error for a 400 with its text.
Results and errors ¶
A handler's result is written as JSON with status 200. Created, Accepted and NoContent choose other statuses, an empty struct answers 204, and a result that is an http.Handler writes the response itself. An error that is a *Problem or FieldErrors is written as RFC 9457 problem details; any other error is logged and answered with a 500 that says nothing about it.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/AndyCross/mapget"
)
type Order struct {
ID int `json:"id"`
Lines []string `json:"lines,omitempty"`
}
// The request type carries its route. The field types are the constraints.
type GetOrder struct {
mapget.Route `route:"GET /orders/{id}"`
ID int `path:"id"`
Expand []string `query:"expand"`
}
func getOrder(_ context.Context, in GetOrder) (Order, error) {
if in.ID > 100 {
return Order{}, mapget.NotFound("there is no order with that id")
}
o := Order{ID: in.ID}
if len(in.Expand) > 0 {
o.Lines = []string{"12 x TILE-4"}
}
return o, nil
}
func main() {
mux := http.NewServeMux()
app := mapget.New(mux)
mapget.Handle(app, getOrder)
get := func(target string) {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", target, nil))
fmt.Printf("%d %s", rec.Code, rec.Body)
if rec.Code >= 400 {
fmt.Println()
}
}
get("/orders/42?expand=lines")
get("/orders/abc") // not an int, so not a route
get("/orders/101")
}
Output: 200 {"id":42,"lines":["12 x TILE-4"]} 404 {"status":404,"title":"Not Found"} 404 {"detail":"there is no order with that id","status":404,"title":"Not Found"}
Index ¶
- func Handle[In, Out any](r *Router, h func(context.Context, In) (Out, error))
- func HandleAt[In, Out any](r *Router, pattern string, h func(context.Context, In) (Out, error))
- type Accepted
- type Created
- type Document
- type FieldErrors
- type Info
- type Middleware
- type Mux
- type NoContent
- type Option
- type Problem
- type Route
- type RouteInfo
- type Router
- func (r *Router) Group(prefix string, mw ...Middleware) *Router
- func (r *Router) Handle(pattern string, h http.Handler)
- func (r *Router) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request))
- func (r *Router) MustPath(in any) string
- func (r *Router) OpenAPI(info Info) Document
- func (r *Router) Path(in any) (string, error)
- func (r *Router) Routes() []RouteInfo
- func (r *Router) Use(mw ...Middleware)
- func (r *Router) WriteRoutes(w io.Writer) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Handle ¶
Handle registers h at the route written on its request type, the type's embedded Route field. It panics if In has no route, if the pattern's wildcards and the type's path fields differ, or if the mux refuses the pattern.
Each request is bound to a new In: path values, query parameters, headers, cookies and a JSON body, by the field tags path, query, header, cookie and body. A path value that does not parse as its field's type is answered with 404, as a failed route constraint is in ASP.NET Core. Anything else that does not parse is answered with a 400 Problem that lists every failing field.
The result is written as JSON with status 200, unless Out is Created, Accepted or NoContent, an empty struct (204), or an http.Handler, which is left to write the response itself. An error is written as a Problem.
func HandleAt ¶
HandleAt is Handle with the pattern given at the call, in the style of ASP.NET Core's MapGet, for request types that carry no route of their own.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/AndyCross/mapget"
)
func main() {
mux := http.NewServeMux()
app := mapget.New(mux)
// The pattern at the call, as with ASP.NET Core's MapGet.
type in struct {
Name string `path:"name"`
Loud bool `query:"loud"`
}
mapget.HandleAt(app, "GET /hello/{name}", func(_ context.Context, in in) (string, error) {
if in.Loud {
return "HELLO, " + in.Name, nil
}
return "hello, " + in.Name, nil
})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/hello/ada?loud=true", nil))
fmt.Print(rec.Body)
}
Output: "HELLO, ada"
Types ¶
type Accepted ¶
Accepted is a handler result that answers 202 with Body as JSON, and a Location header when Location is set.
type Created ¶
Created is a handler result that answers 201 with a Location header and Body as JSON.
type Document ¶
Document is an OpenAPI 3.1 document. It marshals to JSON with its keys in a fixed order, and it is an http.Handler that serves itself.
type FieldErrors ¶
FieldErrors is a set of validation messages by field name. Returned from a handler or from a request type's Validate method, it becomes a 400 Problem with the messages under "errors".
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/AndyCross/mapget"
)
func main() {
mux := http.NewServeMux()
app := mapget.New(mux)
type in struct {
Page int `query:"page" default:"1"`
Size int `query:"size,required"`
}
mapget.HandleAt(app, "GET /tiles", func(_ context.Context, in in) (int, error) { return in.Page * in.Size, nil })
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/tiles?page=two", nil))
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
fmt.Println(rec.Body)
}
Output: 400 application/problem+json {"errors":{"page":["must be an integer"],"size":["is required"]},"status":400,"title":"One or more validation errors occurred."}
func (FieldErrors) Add ¶
func (e FieldErrors) Add(field, message string)
Add records a message against a field.
func (FieldErrors) Error ¶
func (e FieldErrors) Error() string
type Middleware ¶
Middleware wraps a handler, in the usual net/http shape.
type NoContent ¶
type NoContent struct{}
NoContent is a handler result that answers 204 with no body.
type Option ¶
type Option func(*root)
An Option configures a Router made by New.
type Problem ¶
type Problem struct {
Type string // a URI naming the kind of problem; "about:blank" when empty
Title string // short and the same for every occurrence; the status text when empty
Status int
Detail string // specific to this occurrence
Instance string
// Errors holds messages by field name, in the shape of ASP.NET Core's
// ValidationProblemDetails.
Errors map[string][]string
// Extensions are written as extra top-level members.
Extensions map[string]any
}
Problem is an RFC 9457 problem details object, the error body ASP.NET Core calls ProblemDetails. It is an error, so a handler returns one to choose the status and body of a failure, and it is an http.Handler, so it can be registered on a mux directly.
func Unprocessable ¶
Unprocessable returns a 422 Problem.
func (*Problem) MarshalJSON ¶
MarshalJSON writes the standard members, then Errors, then the extensions.
type Route ¶
type Route struct{}
Route marks a request type with the route it answers. Embed it and give it a route tag holding a net/http pattern:
type GetOrder struct {
mapget.Route `route:"GET /orders/{id}" summary:"Fetch one order" tags:"orders"`
ID int `path:"id"`
}
The summary and tags are optional and go into the OpenAPI document.
type RouteInfo ¶
type RouteInfo struct {
Method string // empty when the pattern matches every method
Host string // empty when the pattern matches every host
Path string // the path as net/http writes it, wildcards included
Pattern string // the whole pattern, as given to the mux
In, Out reflect.Type // nil for a plain http.Handler
Summary string
Tags []string
}
RouteInfo describes one registered route.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
A Router registers handlers on a Mux and remembers what it registered. The Mux still does all the routing. A Router made by Group shares its parent's route table, so links and the OpenAPI document cover the whole tree.
func (*Router) Group ¶
func (r *Router) Group(prefix string, mw ...Middleware) *Router
Group returns a Router whose routes all begin with prefix and run inside the given middleware, after any the receiver already has. The prefix may hold wildcards, such as "/tenants/{tenant}". It is ASP.NET Core's MapGroup.
func (*Router) Handle ¶
Handle registers a plain handler, with the router's prefix and middleware applied, and lists it in the route table.
func (*Router) HandleFunc ¶
HandleFunc is Handle for a function.
func (*Router) MustPath ¶
MustPath is Path for values known to be good, such as an id just read from a database. It panics where Path returns an error.
func (*Router) OpenAPI ¶
OpenAPI describes every route registered so far that has a method. The parameters come from the request types' tags and the schemas from the Go types, read the way encoding/json reads them. A field's doc tag becomes its description. Call it after the routes are registered.
func (*Router) Path ¶
Path returns the address of the route registered for in's type, with in's path fields in the path and its query fields in the query string. It is the inverse of binding: a request for the result binds to a value equal to in, for the path and query fields.
A query field is left out when it holds its default, or its zero value if it has no default. Header, cookie and body fields play no part.
It returns an error if the type has no route on this router or has more than one, or if a path field holds a value no request path could carry: an empty string or a lone "/", or for a {name...} wildcard a value with an empty segment.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/AndyCross/mapget"
)
type Order struct {
ID int `json:"id"`
Lines []string `json:"lines,omitempty"`
}
// The request type carries its route. The field types are the constraints.
type GetOrder struct {
mapget.Route `route:"GET /orders/{id}"`
ID int `path:"id"`
Expand []string `query:"expand"`
}
func getOrder(_ context.Context, in GetOrder) (Order, error) {
if in.ID > 100 {
return Order{}, mapget.NotFound("there is no order with that id")
}
o := Order{ID: in.ID}
if len(in.Expand) > 0 {
o.Lines = []string{"12 x TILE-4"}
}
return o, nil
}
func main() {
app := mapget.New(http.NewServeMux())
api := app.Group("/api/v1")
mapget.Handle(api, getOrder)
fmt.Println(app.Path(GetOrder{ID: 42}))
fmt.Println(app.Path(GetOrder{ID: 42, Expand: []string{"lines", "customer"}}))
}
Output: /api/v1/orders/42 <nil> /api/v1/orders/42?expand=lines&expand=customer <nil>
func (*Router) Routes ¶
Routes returns every route registered through r, its parents and its groups, ordered by path and then method.
func (*Router) Use ¶
func (r *Router) Use(mw ...Middleware)
Use adds middleware to every route registered through r from now on.
func (*Router) WriteRoutes ¶
WriteRoutes writes the route table as aligned text, one route a line.
Example ¶
package main
import (
"context"
"net/http"
"os"
"github.com/AndyCross/mapget"
)
type Order struct {
ID int `json:"id"`
Lines []string `json:"lines,omitempty"`
}
// The request type carries its route. The field types are the constraints.
type GetOrder struct {
mapget.Route `route:"GET /orders/{id}"`
ID int `path:"id"`
Expand []string `query:"expand"`
}
func getOrder(_ context.Context, in GetOrder) (Order, error) {
if in.ID > 100 {
return Order{}, mapget.NotFound("there is no order with that id")
}
o := Order{ID: in.ID}
if len(in.Expand) > 0 {
o.Lines = []string{"12 x TILE-4"}
}
return o, nil
}
func main() {
app := mapget.New(http.NewServeMux())
api := app.Group("/api/v1")
mapget.Handle(api, getOrder)
app.HandleFunc("GET /healthz", func(http.ResponseWriter, *http.Request) {})
app.WriteRoutes(os.Stdout)
}
Output: GET /api/v1/orders/{id} mapget_test.GetOrder mapget_test.Order GET /healthz - -