The HTTP services post in this series gave routing a section called “The Weak Spot”, showed four lines of the Go 1.22 mux, and moved on to chi, gorilla and gin. This post covers what that section left out: the pattern language set against attribute routing, and the things ASP.NET Core does around its router that Go's mux does not attempt. It then fills most of that list with a small library I wrote for the purpose, mapget. Every snippet and every response below was run on go1.27.3.
What you had in C#
[ApiController]
[Route("orders")]
public class OrdersController : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult<Order> Get(int id, [FromQuery] string[] expand) { ... }
[HttpPost]
public ActionResult<Order> Create(NewOrder body)
{
...
return CreatedAtAction(nameof(Get), new { id = order.Id }, order);
}
}
That controller uses six separate features. The route template is matched. :int is a constraint, so /orders/abc is a 404 before the action runs. id and expand are bound from the path and the query string and converted. NewOrder is bound from the JSON body, and a body that fails is answered with a 400 ValidationProblemDetails that the action never sees. CreatedAtAction generates the new order's address from the route table. And the whole controller can be described as OpenAPI from what is already written there.
Only the first of those is routing in the narrow sense. Go's mux does the first and stops there.
What the mux matches
mux := http.NewServeMux()
mux.HandleFunc("GET /orders", listOrders)
mux.HandleFunc("POST /orders", createOrder)
mux.HandleFunc("GET /orders/{id}", getOrder)
mux.HandleFunc("GET /orders/latest", latestOrder)
mux.HandleFunc("GET /files/{path...}", getFile)
mux.HandleFunc("GET /docs/", docs)
mux.HandleFunc("GET /{$}", home)
A pattern is [METHOD ][HOST]/[PATH]. I registered those seven and sent requests at them:
| Request | Answer | Why |
|---|---|---|
GET /orders/42 |
getOrder, r.PathValue("id") is "42" |
{id} matches one segment |
GET /orders/latest |
latestOrder |
The most specific pattern wins, whatever order they were registered in |
HEAD /orders/42 |
getOrder |
A GET pattern also matches HEAD |
DELETE /orders/42 |
405, Allow: GET, HEAD |
The path matched and the method did not |
PUT /orders |
405, Allow: GET, HEAD, POST |
|
GET /files/a/b/c.txt |
getFile, path is "a/b/c.txt" |
{path...} takes the rest |
GET /docs/a/b |
docs |
A trailing slash is an anonymous ... |
GET /docs |
307 to /docs/ |
|
GET / |
home |
{$} matches the end of the path only. Without it, / matches everything |
GET /orders//42 |
307 to /orders/42 |
The path is cleaned first |
GET /Orders/42 |
404 | Literals are case-sensitive. ASP.NET Core's are not |
GET /orders/42/ |
404 | No pattern has that trailing slash |
Precedence is the part I like most. ASP.NET Core orders candidates by how literal each segment is, with Order to override it, and when two endpoints still tie it throws AmbiguousMatchException on the request that hits both. The mux has one rule: a pattern beats another if it matches a strict subset of the other's requests. If neither does and they overlap, registering the second one panics, and the message says why with examples:
pattern "GET /a/b/{y}" conflicts with pattern "GET /a/{x}/c":
GET /a/b/{y} and GET /a/{x}/c both match some paths, like "/a/b/c".
But neither is more specific than the other.
GET /a/b/{y} matches "/a/b/y", but GET /a/{x}/c doesn't.
GET /a/{x}/c matches "/a/x/c", but GET /a/b/{y} doesn't.
That is the mux's message with the file positions trimmed. An ambiguous route table stops the program at startup, where ASP.NET Core's surfaces on the first request that hits both endpoints.
What it leaves to you
I tried the things a C# developer reaches for next.
mux.HandleFunc("GET /items/{id:int}", h) // panic: bad wildcard name "id:int"
mux.HandleFunc("GET /items/item-{id}", h) // panic: bad wildcard segment (must start with '{')
There are no constraints, and a wildcard is a whole segment or nothing, so report-{year}.{ext} cannot be written either. GET /orders/abc reaches getOrder with id set to "abc", and the handler decides what that means.
r.PathValue("idd") on a pattern with {id} compiles, runs and returns "". Nothing connects the name in the pattern to the name in the handler.
The rest of the list:
- Binding. Path values are strings. The query string, headers and body are yours to read and convert.
- Error bodies. The mux's own 404 and 405 are
text/plain. Anything for a bad parameter is whatever each handler writes. - Link generation. There are no route names, and no equivalent of
LinkGeneratororCreatedAtAction. Addresses are built withfmt.Sprintfin a second place. - Groups. There is no
MapGroup. A sub-mux behindhttp.StripPrefixworks, and the patterns inside it then no longer say where they live. - A list of routes. The mux cannot be asked what it holds, so there is nothing to print at startup and nothing to build an OpenAPI document from.
Here is one endpoint with an integer id, a page parameter that defaults to 1 and a search term, written against the mux with care:
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")))
}
That is thirteen lines before any work is done, none of them routing, and each endpoint will write them slightly differently.
Putting the route on the request type
Go has no attributes. It does have struct tags, which encoding/json already uses to say where a field comes from. mapget uses them for the whole request, route included:
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 reads the tags once, registers GET /orders/{id} on the mux you gave it, and wraps the function in an http.Handler that binds, calls and writes. The mux still does all the matching, so every row of the table above still holds. The handler is a plain function of a context and a value, and a test calls it without building a request.
If you prefer the pattern at the registration, in the style of app.MapGet, mapget.HandleAt(app, "GET /orders/{id}", svc.GetOrder) does that with an untagged type.
The field's type is the constraint
ID is an int, so there is nothing to add to the pattern. These are from the example service in the repository:
$ curl -s localhost:8080/api/orders/abc
{"status":404,"title":"Not Found"}
$ curl -s 'localhost:8080/api/orders?status=open&limit=abc'
{"errors":{"limit":["must be an integer"]},"status":400,"title":"One or more validation errors occurred."}
$ curl -s --json '{"customer":5}' localhost:8080/api/orders
{"errors":{"customer":["must be a string"]},"status":400,"title":"One or more validation errors occurred."}
A path value that does not parse is a 404, which is what {id:int} does. A query value, header or cookie that does not parse is a 400, and every failing field is reported in one answer. The bodies are RFC 9457 problem details, with the title, status and errors members that ASP.NET Core's ValidationProblemDetails has.
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. A narrower constraint is a type of your own whose UnmarshalText rejects what it should. There are header, cookie and body:"json" tags beside path and query, a ,required option and a default tag.
Rules go in tags too
DataAnnotations ([Range], [StringLength], [RegularExpression]) have a counterpart in tags named after the JSON Schema keywords: minimum, maximum, minLength, maxLength, pattern, enum, minItems and maxItems. They go on parameters and on any field inside a JSON body:
type ListOrders struct {
mapget.Route `route:"GET /orders"`
Status string `query:"status" enum:"open,shipped"`
Limit int `query:"limit" default:"20" minimum:"1" maximum:"100"`
}
type NewOrder struct {
Customer string `json:"customer" minLength:"1" maxLength:"80"`
Lines []Line `json:"lines" minItems:"1" maxItems:"50"`
}
type Line struct {
SKU string `json:"sku" pattern:"^[A-Z]{2,6}-[0-9]+$"`
Qty int `json:"qty" minimum:"1"`
}
$ curl -s 'localhost:8080/api/orders?status=lost&limit=500'
{"errors":{"limit":["must be at most 100"],"status":["must be one of open, shipped"]},"status":400,"title":"One or more validation errors occurred."}
$ curl -s --json '{"customer":"","lines":[{"sku":"tile","qty":0}]}' localhost:8080/api/orders
{"errors":{"customer":["must be at least 1 character"],"lines[0].qty":["must be at least 1"],"lines[0].sku":["must match the pattern ^[A-Z]{2,6}-[0-9]+$"]},"status":400,"title":"One or more validation errors occurred."}
On a path field a rule is a route constraint: ID int tagged path:"id" minimum:"1" answers 404 for /orders/0, as {id:int:min(1)} does. The same tags are written into the OpenAPI schemas. A rule that a tag cannot state, such as one comparing two fields, goes in a Validate() error method on the request type, which runs after the tags have passed.
Mistakes are found at startup
The pattern and the fields are checked against each other when the route is registered, and a mismatch panics, as a conflicting pattern does in the mux:
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
A link is a value of the request type
Url.Action and LinkGenerator take names and an object of route values, and return null at run time when the two do not fit. Here the type that declares the route also builds its address:
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 prefix, and every link either follows or stops compiling. The create handler in the example uses it for its Location header:
func (s *service) create(_ context.Context, in CreateOrder) (mapget.Created[Order], error) {
// ... store the order as o ...
o.Self = s.links.MustPath(GetOrder{ID: o.ID})
return mapget.Created[Order]{Location: o.Self, Body: *o}, nil
}
$ curl -si --json '{"customer":"Ada","lines":[{"sku":"TILE-4","qty":12}]}' localhost:8080/api/orders
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/orders/2
Groups, the route table and OpenAPI
app := mapget.New(mux)
api := app.Group("/api", logging)
mapget.Handle(api, s.list)
mapget.Handle(api, s.get)
mapget.Handle(api, s.create)
mapget.Handle(api, s.ship)
app.Handle("GET /openapi.json", app.OpenAPI(mapget.Info{Title: "Orders", Version: "1.0.0"}))
app.WriteRoutes(os.Stdout)
Group is MapGroup: a prefix and some ordinary func(http.Handler) http.Handler middleware. Because registration goes through mapget, it knows what the mux holds and can print it:
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 - -
The same table, with the tags and the Go types, is enough for an OpenAPI 3.1 document: parameters from the path and query tags, schemas from the types as encoding/json reads them, 201 and 204 from Created and NoContent, and a problem details response on every operation. This is the operation for GET /api/orders/{id}, trimmed of its error response:
{
"operationId": "getOrder",
"summary": "Fetch one order",
"tags": ["orders"],
"parameters": [
{ "name": "id", "in": "path", "required": true,
"schema": { "type": "integer", "format": "int64" } }
],
"responses": {
"200": {
"description": "OK",
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Order" } } }
}
}
}
What it costs
The tags are read with reflect at registration. Per request, the wrapper sets a few struct fields through reflect on top of the parsing the hand-written handler does anyway. I benchmarked the hand-written handler above against the mapget version of the same endpoint, both through a real ServeMux:
| go1.27.3, Apple M4 Max | Time | Allocated | Allocations |
|---|---|---|---|
| By hand | 371 ns | 528 B | 8 |
| mapget | 417 ns | 560 B | 9 |
Those are medians of five runs of go test -bench. The difference is 46 nanoseconds and one allocation a request.
What the fuzz test found in the mux
Path and binding are meant to be inverses: whatever address Path writes for a value, a request for it should bind to the same value. That is a property, so I gave it to go test -fuzz with a real ServeMux in the loop. It found two things, both in the mux.
On go1.27.3, a path segment that is exactly %2F matches no {wildcard}:
Request to GET /trip/{name}/{n} |
Answer |
|---|---|
/trip/a%2Fb/1 |
200, name is "a/b" |
/trip/%2Fa/1 |
200, name is "/a" |
/trip/%2F%2F/1 |
200, name is "//" |
/trip/%2F/1 |
404 |
The mux unescapes each segment before matching and uses the string "/" internally to mean a trailing slash, which single wildcards are written to skip (routing_tree.go, if seg != "/"). A segment that unescapes to exactly "/" is skipped with it. Path now returns an error for a path value of "/".
The second turned up in CI, on the oldest Go I had said I supported. On go1.22.12, r.PathValue("rest") for the pattern /trip/{name}/{n}/{rest...} and the request /trip/0/-83/* panics with an index out of range. Go 1.23 returns "*". Go 1.22 has been out of support since February 2025, so mapget asks for 1.23 and the fuzz test runs in CI on both ends of the range.
Since then the fuzz test has run more than fifteen million round trips on 1.23 and 1.27 without another failure.
When a router package is still worth it
- You need matching the mux cannot express. chi takes a regular expression in the pattern and wildcards inside a segment. I checked both on chi v5.5.0:
/orders/{id:[0-9]+}answers 404 for/orders/abc, and/files/report-{year}.{ext}matchesreport-2026.csv. If your addresses look like that and cannot change, use chi. - You want a framework. gin and echo bring their own context type, binding, rendering and a large set of middleware written against that context. That is a different decision from routing, closer to choosing MVC over minimal APIs, and it is a reasonable one for a team that wants the conventions decided for it.
- You need case-insensitive paths. The mux will not do it, and lowercasing in middleware means redirecting or rewriting every request.
If none of those apply, the standard mux is enough. Binding, error bodies, links and the OpenAPI document are separate from matching, and mapget adds them without replacing it.
Huma already does most of this
Most of mapget exists already. Huma has typed handlers, path and query struct tags, problem details and an OpenAPI 3.1 document. It runs on the standard mux through an adapter, validates from tags (minimum, maxLength, pattern), and has adapters for chi, gin, echo and others. I ran the same endpoint on Huma v2.41.0: /orders/42 binds, /orders/abc is a 422 where mapget answers 404, and the document is served at /openapi.json. If you want this for work, use Huma.
I wrote mapget anyway, for fun and to learn, and it may not deserve to exist beside Huma. I wanted to know how much of ASP.NET Core's routing could be rebuilt from struct tags on the standard mux, and writing a library is a good way to find out what one has to decide. The two parts I have not seen elsewhere are the route on the request type and the link built from that same type.
Whether a route belongs on a type is a fair question in Go. The habit there is to register every route in one visible place and to be sparing with reflection, and a route in a struct tag goes against the first of those. HandleAt keeps the pattern at the registration for anyone who prefers that. The rest is in keeping with the standard library: it is reflection over struct tags, as encoding/json is, and it panics at registration on a mistake, as the mux does.
What mapget does not do
It has no constraint syntax in the pattern and no partial-segment wildcards, because the mux has neither. A regular expression constraint is written as a type whose UnmarshalText rejects everything else, and the README has an example. It has no dependency injection: handlers are methods on a struct that holds what they need. It reads JSON bodies only, so a form or an upload takes a *http.Request field or a plain handler registered beside the typed ones. Authentication is middleware. The OpenAPI document carries the rules written as tags and knows nothing of the ones in a Validate method.
It is at version 0.2 and was written for this post: about 2,150 lines with no dependencies outside the standard library. The API may still change before 1.0.
go get github.com/AndyCross/mapget
The source, the fuzz test and an example service with Swagger UI over its generated document are at github.com/AndyCross/mapget, and the reference is on pkg.go.dev.