mapget

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 19 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.

README

mapget

ci Go Reference Go Report Card Release Fuzzed in CI

Typed, self-describing endpoints on Go's standard http.ServeMux, for people who came from ASP.NET Core.

A request type that carries its route, and the answers it gives

Go 1.22 gave the standard mux methods and wildcards ("GET /orders/{id}"), which covers matching a request to a handler. ASP.NET Core does a good deal around its router that the mux leaves to you: route constraints, model binding, validation problem responses, link generation, route groups, a list of endpoints and an OpenAPI document. mapget is those parts, and nothing else. The mux still does all the routing, and the package has no dependencies outside the standard library.

go get github.com/AndyCross/mapget

Go 1.23 or later. The patterns arrived in 1.22, but on 1.22 Request.PathValue panics when a {rest...} wildcard's value is exactly *, which this package's fuzz test found, and 1.23 fixed it.

Try it in a minute

git clone https://github.com/AndyCross/mapget && cd mapget
go run ./example

Then open http://localhost:8080/docs. Nothing in the example describes its API by hand: the page below is Swagger UI reading the document mapget generated from the Go types and their tags.

Swagger UI showing the example's orders API

Before and after

One endpoint: an integer id in the path, a page that defaults to 1, a search term.

net/http alonewith mapget
func getOrder(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil {
        http.NotFound(w, r)
        return
    }
    q := r.URL.Query()
    page := 1
    if s := q.Get("page"); s != "" {
        if page, err = strconv.Atoi(s); err != nil {
            http.Error(w, "page must be an integer",
                http.StatusBadRequest)
            return
        }
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(find(id, page, q.Get("q")))
}

mux.HandleFunc("GET /orders/{id}", getOrder)
type GetOrder struct {
    mapget.Route `route:"GET /orders/{id}"`
    ID   int    `path:"id"`
    Page int    `query:"page" default:"1"`
    Q    string `query:"q"`
}

func getOrder(ctx context.Context, in GetOrder) (Order, error) {
    return find(in.ID, in.Page, in.Q), nil
}

mapget.Handle(app, getOrder)

The right-hand side also answers a bad page with problem details JSON, appears in the route table and the OpenAPI document, and can be linked to with app.Path(GetOrder{ID: 42}). It costs 46 ns a request more than the left (see What it costs).

The route goes on the request type

In C# the route is an attribute on the action and the parameters say where they come from:

[HttpGet("orders/{id:int}")]
public ActionResult<Order> Get(int id, [FromQuery] string[] expand)

Go has no attributes, but it has struct tags. A request type carries its route, 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) {
    o, ok := s.orders[in.ID]
    if !ok {
        return Order{}, mapget.NotFound("there is no order with that id")
    }
    return o, nil
}

func main() {
    mux := http.NewServeMux()
    app := mapget.New(mux)
    mapget.Handle(app, svc.GetOrder)
    http.ListenAndServe(":8080", mux)
}

Handle registers GET /orders/{id} on the mux. The handler is an ordinary function of a context and a value, so a test calls it without building a request.

Request Answer
GET /orders/42?expand=lines 200, the order as JSON
GET /orders/abc 404. ID is an int, so abc is not an order's address. This is what {id:int} does in ASP.NET Core
GET /orders/42?limit=ten (were limit an int) 400, problem details naming limit
DELETE /orders/42 405 with Allow: GET, HEAD, from the mux

If you would rather keep the pattern at the registration, as app.MapGet does, use HandleAt:

mapget.HandleAt(app, "GET /orders/{id}", svc.GetOrder)

Binding

Tag Reads
path:"id" a wildcard in the pattern. Never a pointer or a slice
query:"page" a query parameter. A slice field takes every value
header:"If-None-Match" a request header
cookie:"session" a cookie
body:"json" the body as JSON. One per type. A pointer makes it optional

query, header and cookie take ,required, and a separate default:"20" tag for an absent value. A pointer field is nil when the value is absent. A field of type *http.Request is given the request.

Fields can be strings, booleans, integers, floats, time.Duration, or anything that implements encoding.TextUnmarshaler, which covers time.Time, netip.Addr and the UUID packages. Named types work, so type OrderID int binds.

Every failing query, header and cookie value is reported in one answer, in the shape of ASP.NET Core's ValidationProblemDetails:

{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "page": ["must be an integer"],
    "size": ["is required"]
  }
}

A body with a content type other than JSON is answered with 415, one over the limit (1 MiB unless mapget.MaxBody says otherwise) with 413, and malformed JSON with 400.

Mistakes stop the program at startup

r.PathValue("idd") on a pattern with {id} compiles, runs and returns an empty string. With mapget the pattern and the fields are checked against each other when the route is registered, and a mismatch panics, in the way the mux itself panics on a conflicting pattern:

mapget: main.GetOrder.ID reads path value "idd", which is not in the pattern "GET /orders/{id}"
mapget: pattern "GET /orders/{id}/{rev}" has the wildcard {rev} and main.GetOrder has no field tagged path:"rev"
mapget: main.ListOrders.Page: default "one" is not an integer

ASP.NET Core has LinkGenerator and Url.Action, which take a route or action name and an object of values, and return null at run time when the two do not fit. Here the request type is the route, so a link is a value of that type:

app.Path(GetOrder{ID: 42})                              // "/orders/42"
app.Path(GetOrder{ID: 42, Expand: []string{"lines"}})   // "/orders/42?expand=lines"

Rename the field, change its type or move the route under a group and every link follows or fails to compile. Path and binding are inverses, and a fuzz test in the repository holds them to it: whatever address Path writes, a request for it through a real ServeMux binds to the same value.

Path returns an error for a path value no request can carry, such as an empty string. MustPath panics instead, for values known to be good.

Groups and middleware

app := mapget.New(mux)
api := app.Group("/api/v1", requireAuth)
tenant := api.Group("/tenants/{tenant}", loadTenant)

mapget.Handle(tenant, svc.GetOrder)                 // GET /api/v1/tenants/{tenant}/orders/{id}
api.HandleFunc("GET /healthz", healthz)             // plain handlers join in

This is MapGroup. Middleware is the usual func(http.Handler) http.Handler. A wildcard in a prefix needs a field like any other, so GetOrder above would need Tenant string tagged path:"tenant" or registration panics.

Validation

If the request type has a Validate() error method it runs after binding:

func (c CreateOrder) Validate() error {
    errs := mapget.FieldErrors{}
    if c.Body.Customer == "" {
        errs.Add("customer", "is required")
    }
    if len(errs) > 0 {
        return errs
    }
    return nil
}

FieldErrors becomes the same 400 as a binding failure. A *mapget.Problem is written as it is. Any other error is a 400 with its text.

Results and errors

Handler returns Answer
any value 200, JSON
mapget.Created[T]{Location, Body} 201, Location header, JSON
mapget.Accepted[T]{Location, Body} 202, JSON
mapget.NoContent{} or struct{}{} 204
an http.Handler, such as http.RedirectHandler(...) whatever it writes
*mapget.Problem, or mapget.NotFound(...), Conflict(...) and the rest, as the error that status, as RFC 9457 problem details
mapget.FieldErrors as the error 400 with errors
any other error 500 with no detail. The error goes to mapget.OnError, which logs it with slog by default

The route table

app.WriteRoutes(os.Stdout)
GET   /api/orders            main.ListOrders   []main.Order
POST  /api/orders            main.CreateOrder  mapget.Created[main.Order]
GET   /api/orders/{id}       main.GetOrder     main.Order
POST  /api/orders/{id}/ship  main.ShipOrder    mapget.NoContent
GET   /openapi.json          -                 -

app.Routes() returns the same as values.

OpenAPI

app.Handle("GET /openapi.json", app.OpenAPI(mapget.Info{Title: "Orders", Version: "1.0.0"}))

An OpenAPI 3.1 document from what is already written down: parameters from the tags, schemas from the Go types as encoding/json reads them, 201 and 204 from Created and NoContent, and a default problem details response on every operation. summary and tags on the Route field and doc on any field add the words:

type ListOrders struct {
    mapget.Route `route:"GET /orders" summary:"List orders" tags:"orders"`
    Status string `query:"status" doc:"Only orders in this state."`
    Limit  int    `query:"limit" default:"20"`
}

What it costs

One endpoint with a path value, two query parameters and a small JSON answer, through a real ServeMux, against the same endpoint written by hand with r.PathValue and strconv. Go 1.27.3, Apple M4 Max, go test -bench . -count 5, median:

Time Allocated Allocations
By hand 371 ns 528 B 8
mapget 417 ns 560 B 9

The tags are read once, at registration. A request costs a few reflect field sets on top of the parsing it needed anyway.

What it does not do

  • Route. The mux does that, so precedence, conflicts, 405, host patterns and trailing-slash redirects are exactly the standard library's.
  • Regular expression constraints. The field's type is the constraint. For anything narrower, implement encoding.TextUnmarshaler on a type of your own and have it reject what it should.
  • Dependency injection. Handlers are methods on a struct that holds what they need.
  • Form and multipart bodies, content negotiation, XML. Take a *http.Request field, or register a plain handler beside the typed ones.
  • Authentication. That is middleware.

One more thing the fuzz test found that is the mux's and not mapget's: on Go 1.27 a path segment that is exactly %2F matches no {wildcard} and is answered with 404, though a%2Fb matches and gives a/b. Path returns an error for a path value of "/" for that reason.

Example

example/ is an orders API with all of the above.

go run ./example
curl -s localhost:8080/api/orders/1
curl -s 'localhost:8080/api/orders?limit=abc'
curl -s --json '{"customer":"Ada","lines":[{"sku":"TILE-4","qty":12}]}' localhost:8080/api/orders
curl -s localhost:8080/openapi.json

Swagger UI is at http://localhost:8080/docs. The example loads it from a CDN; the library itself serves only the JSON document.

Tests

87% of statements are covered. FuzzPathRoundTrip checks that link generation and binding are inverses through a real ServeMux, and runs in CI on Go 1.23 and the current release.

go test ./...
go test -run '^$' -fuzz FuzzPathRoundTrip -fuzztime 30s .
go test -run '^$' -bench . .

Licence

MIT.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handle

func Handle[In, Out any](r *Router, h func(context.Context, In) (Out, error))

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

func HandleAt[In, Out any](r *Router, pattern string, h func(context.Context, In) (Out, error))

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

type Accepted[T any] struct {
	Location string
	Body     T
}

Accepted is a handler result that answers 202 with Body as JSON, and a Location header when Location is set.

type Created

type Created[T any] struct {
	Location string
	Body     T
}

Created is a handler result that answers 201 with a Location header and Body as JSON.

type Document

type Document map[string]any

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.

func (Document) ServeHTTP

func (d Document) ServeHTTP(w http.ResponseWriter, _ *http.Request)

ServeHTTP writes the document as JSON.

type FieldErrors

type FieldErrors map[string][]string

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 Info

type Info struct {
	Title       string
	Version     string
	Description string
}

Info is the title block of an OpenAPI document.

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware wraps a handler, in the usual net/http shape.

type Mux

type Mux interface {
	Handle(pattern string, handler http.Handler)
}

Mux is the part of *http.ServeMux that mapget uses.

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.

func MaxBody

func MaxBody(n int64) Option

MaxBody sets the largest JSON request body a typed handler will read. The default is 1 MiB. A larger body is answered with 413.

func OnError

func OnError(f func(*http.Request, error)) Option

OnError sets what happens to an error that is not a Problem or FieldErrors before the client is sent a 500 with no detail. The default logs it with slog.

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 BadRequest

func BadRequest(detail string) *Problem

BadRequest returns a 400 Problem.

func Conflict

func Conflict(detail string) *Problem

Conflict returns a 409 Problem.

func Forbidden

func Forbidden(detail string) *Problem

Forbidden returns a 403 Problem.

func NotFound

func NotFound(detail string) *Problem

NotFound returns a 404 Problem.

func Status

func Status(status int, detail string) *Problem

Status returns a Problem with the given status and detail.

func Unauthorized

func Unauthorized(detail string) *Problem

Unauthorized returns a 401 Problem.

func Unprocessable

func Unprocessable(detail string) *Problem

Unprocessable returns a 422 Problem.

func (*Problem) Error

func (p *Problem) Error() string

func (*Problem) MarshalJSON

func (p *Problem) MarshalJSON() ([]byte, error)

MarshalJSON writes the standard members, then Errors, then the extensions.

func (*Problem) ServeHTTP

func (p *Problem) ServeHTTP(w http.ResponseWriter, _ *http.Request)

ServeHTTP writes the problem as application/problem+json.

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 New

func New(mux Mux, opts ...Option) *Router

New returns a Router that registers on mux, which is usually an *http.ServeMux.

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

func (r *Router) Handle(pattern string, h http.Handler)

Handle registers a plain handler, with the router's prefix and middleware applied, and lists it in the route table.

func (*Router) HandleFunc

func (r *Router) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request))

HandleFunc is Handle for a function.

func (*Router) MustPath

func (r *Router) MustPath(in any) string

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

func (r *Router) OpenAPI(info Info) Document

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

func (r *Router) Path(in any) (string, error)

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

func (r *Router) Routes() []RouteInfo

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

func (r *Router) WriteRoutes(w io.Writer) error

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             -                     -

Directories

Path Synopsis
Command example is a small orders API on the standard library's ServeMux, with mapget doing what the mux leaves to you.
Command example is a small orders API on the standard library's ServeMux, with mapget doing what the mux leaves to you.

Jump to

Keyboard shortcuts

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