← News & analysis

GUIDE · GO HTTP ROUTING · 22 MIN READ

Choosing a Go HTTP router in 2026: ServeMux patterns, chi or Gin

Go 1.22+ ServeMux patterns, chi v5 and Gin compared on one tested API: precedence, 405s, middleware, binding, httptest suites and migration.

Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

An original turquoise rodent engineer compares three different routing switchboards that all feed the same inspection tunnel.
Conceptual illustration for Choosing a Go HTTP router in 2026: ServeMux patterns, chi or Gin AI-generated conceptual illustration.

Routing in 2026 is a choice of handler type, not of features

Before Go 1.22 the standard library's http.ServeMux matched path prefixes and nothing else, so most teams added a router the moment they needed GET /items/{id}. That reason has gone. ServeMux patterns now carry a method, wildcards and an end-of-path anchor, and Request.PathValue returns what a wildcard matched. The real question in 2026 is which handler type you want your code to depend on, which middleware model your team will maintain, and which defaults you are prepared to test.

This is the 28 November 2026 edition, researched and first published on 30 November 2026. We built one small JSON API three times: with the standard library ServeMux, with chi v5.5.0 and with Gin v1.12.0, which were the latest tags of both modules on the Go module proxy when we checked. One table-driven httptest suite runs against all three implementations, a second test pins the behaviour that legitimately differs, and each router has its own focused tests. Everything was run with Go 1.27.3 under go vet, gofmt and go test -race -count=3, and the dependency versions are pinned in go.mod and go.sum.

The API is deliberately ordinary: a root document, a health check, a collection of items with create, read and delete, a latest shortcut that overlaps the {id} wildcard, a file endpoint that needs a remainder wildcard, bearer-token protection for writes and an admin prefix. Ordinary is the point. The differences that matter in production rarely show up in a hello-world comparison. They appear at the edges: a trailing slash, a HEAD request, an escaped slash, a wrong method, an unknown path under a protected prefix.

What ServeMux patterns express since Go 1.22

A pattern has the shape [METHOD ][HOST]/[PATH]. GET /items/{id} matches GET and HEAD requests whose first segment is items and that have exactly one more segment, and r.PathValue("id") returns that segment. {path...} must be the last segment and captures the remainder, slashes included. {$} anchors the end of the path, so GET /{$} matches only /, while a bare / is still the catch-all it always was. A pattern without a method matches every method, and a pattern with a host, such as api.example.com/, matches only that host. This is the lab's complete standard-library wiring:

go
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", a.Root)
mux.HandleFunc("GET /healthz", a.Health)
mux.HandleFunc("GET /items", a.ListItems)
mux.Handle("POST /items", auth(http.HandlerFunc(a.CreateItem)))
mux.HandleFunc("GET /items/latest", a.LatestItem)
mux.HandleFunc("GET /items/{id}", a.GetItem)
mux.Handle("DELETE /items/{id}", auth(http.HandlerFunc(a.DeleteItem)))
mux.HandleFunc("GET /files/{path...}", a.Files(func(r *http.Request) string {
	return r.PathValue("path")
}))

// A prefix-wide group: every request under /admin/ passes the token
// check before the inner mux routes it, including unknown paths.
admin := http.NewServeMux()
admin.HandleFunc("GET /admin/stats", a.Stats)
mux.Handle("/admin/", auth(admin))

return mw.Chain(mux, mw.RequestID)

Several details are easy to miss. Wildcards must be whole segments, so /b_{bucket} is invalid and panics on registration. Matching works on unescaped segments: /items/a%2Fb is one segment whose value is a/b, not two segments. A trailing slash in a pattern acts as an anonymous remainder wildcard, and a request for the subtree root without the slash is redirected; since Go 1.26 that redirect uses 307 instead of 301. Go 1.23 added Request.Pattern, which holds the pattern that matched and makes a stable label for logs and metrics. The pre-1.22 matching rules are still available through GODEBUG=httpmuxgo121=1, which is worth knowing when you upgrade an old service that registered literal braces in its paths.

The admin block shows the standard-library idiom for a group: a second ServeMux mounted under a prefix and wrapped in middleware. There is no router-specific concept involved, only handlers wrapping handlers.

Precedence by specificity, and conflicts that fail at startup

When two patterns match a request, ServeMux chooses the more specific one, meaning the pattern whose requests are a strict subset of the other's. GET /items/latest beats GET /items/{id} for /items/latest, and GET /items/{id} beats a method-less /items/{id} for a GET. In the lab, DELETE /items/latest falls through to DELETE /items/{id} and receives 400 invalid_id, because the literal route exists only for GET. All three routers produce that outcome, and the shared suite checks it.

When neither pattern is more specific, the patterns conflict and Handle panics during registration. Registering the same pattern twice is the simplest case. The message is unusually helpful: it names both patterns and where each was registered, and for a partial overlap it gives an example path that both would match.

go
func TestConflictingPatternsPanicAtRegistration(t *testing.T) {
	tests := []struct {
		name   string
		first  string
		second string
		want   string
	}{
		{"duplicate", "GET /items/{id}", "GET /items/{id}", "matches the same requests"},
		{"same shape, different name", "GET /items/{id}", "GET /items/{name}", "matches the same requests"},
		{"neither more specific", "/posts/{id}", "/{resource}/latest", "neither is more specific"},
		{"method versus path specificity", "GET /", "/index.html", "matches more methods"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			msg := registrationPanic(func() {
				mux := http.NewServeMux()
				mux.HandleFunc(tt.first, func(http.ResponseWriter, *http.Request) {})
				mux.HandleFunc(tt.second, func(http.ResponseWriter, *http.Request) {})
			})
			if !strings.Contains(msg, "conflicts with pattern") || !strings.Contains(msg, tt.want) {
				t.Fatalf("panic = %q, want a conflict mentioning %q", msg, tt.want)
			}
		})
	}
}

Treat these panics as a feature. A conflicting route table fails when the process starts or, better, when a test constructs the router, and the lab constructs every router in every test case. The other routers behave differently. Gin v1.12.0 panics when the same method and path are registered twice and when, for the same method, two different wildcard names compete for one position, such as :id and :name. chi v5.5.0 does neither. In the lab, a second registration of the same method and path silently replaced the first, and {id} followed by {name} left only the later route in place. With chi, your route tests are the only thing that will notice a duplicate.

A four-panel diagram headed MATCH, WRAP, BIND and TEST summarizes routing, middleware, binding and shared testing.
A four-panel diagram headed MATCH, WRAP, BIND and TEST summarizes routing, middleware, binding and shared testing. Conceptual illustration. AI-generated conceptual illustration.

405 responses, Allow headers and the catch-all trap

ServeMux answers a request whose path matches but whose method does not with 405 Method Not Allowed and an Allow header. Because a GET pattern also serves HEAD, the header includes HEAD: in the lab, PUT /items/1 produced Allow: DELETE, GET, HEAD. chi v5 returns 405 by default with one Allow header value per registered method, collected from a map, so their order is not stable from run to run. Gin reports 405 only when you set HandleMethodNotAllowed = true. With the default engine, the same request is a 404. Once enabled, Gin sends one comma-separated value in method registration order.

The trap is specific to ServeMux. Register a method-less catch-all / to render a JSON 404, and every unmatched method now matches the catch-all, so the mux never reaches its 405 logic:

go
// A method-less catch-all matches every method, so ServeMux never reaches
// its 405 logic: the wrong method gets the catch-all's 404 instead.
func TestCatchAllHidesMethodNotAllowed(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /items/{id}", func(http.ResponseWriter, *http.Request) {})

	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest("PUT", "/items/1", nil))
	if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != "GET, HEAD" {
		t.Fatalf("without catch-all: %d Allow=%q", rec.Code, rec.Header().Get("Allow"))
	}

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, `{"error":"not_found"}`, http.StatusNotFound)
	})
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest("PUT", "/items/1", nil))
	if rec.Code != http.StatusNotFound {
		t.Fatalf("with catch-all: %d, want 404", rec.Code)
	}
}

There are two honest options. Accept each router's plain-text 404 and 405 bodies and assert only status codes and headers, which is what the lab does. Or move error rendering out of routing: chi has NotFound and MethodNotAllowed, Gin has NoRoute and NoMethod, and with ServeMux you can wrap the mux and rewrite error responses by status. Whichever you choose, Allow is the contract worth testing, and it should be compared as a set of methods. The three routers disagree on the header's shape and order, not on its meaning.

Middleware composition with plain net/http

The standard library has no middleware type and does not need one. A middleware is func(http.Handler) http.Handler: it receives the next handler, can act before and after calling it, and can stop the chain simply by returning without calling it. A small Chain helper fixes the order so that the first argument is the outermost layer:

go
// Chain applies middleware so that the first argument is the outermost layer:
// Chain(h, a, b) is a(b(h)), and a request passes through a, then b, then h.
func Chain(h http.Handler, ms ...Middleware) http.Handler {
	for i := len(ms) - 1; i >= 0; i-- {
		h = ms[i](h)
	}
	return h
}

// RequireBearer rejects requests without the expected bearer token. It does
// not call next on failure; that early return is the whole mechanism.
func RequireBearer(token string) Middleware {
	want := "Bearer " + token
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get("Authorization") != want {
				w.Header().Set("WWW-Authenticate", "Bearer")
				WriteError(w, http.StatusUnauthorized, "unauthorized", "missing or invalid bearer token")
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

Where you apply a middleware decides what it can see. Wrapping the whole mux runs the middleware for every request, including the router's own 404 and 405 responses, which is what you want for request IDs, access logs and panic recovery. The lab's request ID appears on every response in the shared suite, router errors included. But a layer outside the mux runs before matching, so r.Pattern and r.PathValue are still empty when it starts.

Route-aware middleware, such as latency metrics labelled by route, per-route timeouts or authorization by resource, belongs at registration time, wrapped around the individual handler, where r.Pattern is already set. A lab test shows the outer layer seeing an empty pattern while the per-route layer sees GET /items/{id}. Per-route deadlines are a good example: a timeout around a slow export endpoint, and not around the health check, makes the budget visible exactly where the route is declared.

Groups need no framework either. A prefix-wide group is a nested mux wrapped in middleware, like the admin block earlier. A per-route group is a helper that wraps several handlers with the same stack before registering them.

chi v5 keeps the standard handler type

chi's case in 2026 is that it changes the routing layer and nothing else. Handlers are http.HandlerFunc, middleware is func(http.Handler) http.Handler, and a *chi.Mux is an http.Handler. The lab's chi implementation reuses the exact handlers and middleware written for ServeMux; only the wiring differs:

go
r := chi.NewRouter()
r.Use(mw.RequestID) // the same net/http middleware stdapi uses

r.Get("/", a.Root)
r.Get("/healthz", a.Health)

r.Route("/items", func(r chi.Router) {
	r.Get("/", a.ListItems)
	r.Get("/latest", a.LatestItem)
	r.Get("/{id}", a.GetItem)

	// Group adds middleware to the routes declared inside it only.
	r.Group(func(r chi.Router) {
		r.Use(auth)
		r.Post("/", a.CreateItem)
		r.Delete("/{id}", a.DeleteItem)
	})
})

r.Get("/files/*", a.Files(func(r *http.Request) string {
	return chi.URLParam(r, "*")
}))

// Route mounts a sub-router; its Use applies before the sub-router
// matches, so unknown /admin/... paths are rejected with 401 too.
r.Route("/admin", func(r chi.Router) {
	r.Use(auth)
	r.Get("/stats", a.Stats)
})

return r

r.Route mounts a sub-router under a prefix, and middleware added inside it with Use runs before the sub-router matches. r.Group creates an inline group on the current prefix, and its middleware is attached only to the routes declared inside it. The difference is observable: because the admin block uses Route, an unknown /admin/whatever without a token receives 401 before the sub-router looks for a route. chi requires Use to come before the routes on a mux and panics otherwise, which prevents half-applied middleware stacks.

chi.URLParam(r, "id") reads a parameter from chi's route context. chi v5.5.0 also copies every URL parameter into Request.SetPathValue and sets Request.Pattern before calling the handler, so r.PathValue("id") works as well, and that is why one GetItem function serves both implementations. The remainder parameter is the naming exception: chi calls it *, so the file handler receives a small accessor instead of hard-coding a name. Two chi behaviours deserve tests in your own code. Routing uses RawPath when it is set, so /files/a%2Fb/c yields a%2Fb/c rather than a/b/c. And a collection mounted with Route answers both /items and /items/. chi also supports regular-expression parameters such as {articleSlug:[a-z-]+}, which ServeMux does not.

Gin is a framework with its own context

Gin is a different kind of dependency. Its handlers are func(*gin.Context), and gin.Context carries the request, the response writer, route parameters, the position in the middleware chain, a key-value store, and helpers for binding and rendering. That convenience is real, and so is the coupling: a handler written for Gin calls Gin APIs throughout, and moving it elsewhere is a rewrite rather than a rewiring.

go
// gin.New has no middleware; gin.Default would add Logger and Recovery.
r := gin.New()
// Off by default, which turns every wrong-method request into a 404.
r.HandleMethodNotAllowed = true
// Added in v1.12.0: route on the escaped path so %2F stays in one segment.
r.UseEscapedPath = true

// Reuse the net/http middleware through an adapter. Register it before
// any route: Engine.Use only reaches routes added after the call.
r.Use(FromStd(mw.RequestID))

h := &api{store: st}
r.GET("/", h.root)
r.GET("/healthz", h.health)

items := r.Group("/items")
items.GET("", h.list)
items.GET("/latest", h.latest)
items.GET("/:id", h.get)

writes := items.Group("", RequireBearer(token))
writes.POST("", h.create)
writes.DELETE("/:id", h.delete)

r.GET("/files/*path", h.files)

// Group middleware is attached to the routes in the group, so an
// unknown /admin/... path is a plain 404, not a 401.
admin := r.Group("/admin", RequireBearer(token))
admin.GET("/stats", h.stats)

return r

Parameters use the :id and *path syntax and are read with c.Param. A catch-all value keeps its leading slash, so /files/docs/readme.md yields /docs/readme.md, which the lab trims. Groups such as r.Group("/items") share a prefix and attach middleware to the routes registered through them. Unlike chi's Route, Gin group middleware never runs for unmatched paths, so an unknown /admin/whatever is a 404 even without a token.

Middleware is a gin.HandlerFunc in the same chain as the handler. c.Next() runs the rest of the chain and then returns, which is how before-and-after logic is written. c.Abort() stops the remaining handlers but not the current function, so code after it still runs unless you return. Engine.Use copies middleware into routes registered after the call; a route registered earlier silently misses it, as a lab test shows. Defaults matter as well. gin.New() installs no middleware while gin.Default() adds a logger and panic recovery, HandleMethodNotAllowed is off, and gin.SetMode is process-wide, so the tests set it once in TestMain. Gin v1.12.0 added UseEscapedPath, which the lab enables so that %2F stays inside one segment. Without it, /items/a%2Fb routes on the decoded path and becomes a 404. Finally, Engine.Run builds an http.Server with only an address and a handler. Serve the engine from your own http.Server so you control timeouts and graceful shutdown.

Binding and validation rules you still have to pin down

Binding is Gin's strongest feature for API work. c.ShouldBindJSON(&in) decodes the body and then applies the go-playground/validator rules declared in binding tags. The lab maps the three failure classes onto the same error envelope that the other implementations produce:

go
func (h *api) create(c *gin.Context) {
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, handlers.MaxBodyBytes)
	var in CreateItemRequest
	if err := c.ShouldBindJSON(&in); err != nil {
		var tooBig *http.MaxBytesError
		var invalid validator.ValidationErrors
		switch {
		case errors.As(err, &tooBig):
			abortError(c, http.StatusRequestEntityTooLarge, "body_too_large", "request body exceeds 1 KiB")
		case errors.As(err, &invalid):
			abortError(c, http.StatusUnprocessableEntity, "invalid_item", invalid.Error())
		default:
			abortError(c, http.StatusBadRequest, "invalid_json", "request body must be a JSON object")
		}
		return
	}
	it, err := h.store.Create(itemstore.NewItem{Name: in.Name, Quantity: in.Quantity})
	if err != nil {
		abortError(c, http.StatusUnprocessableEntity, "invalid_item", err.Error())
		return
	}
	c.Header("Location", "/items/"+strconv.FormatInt(it.ID, 10))
	c.JSON(http.StatusCreated, it)
}

Validation tags have semantics you should test rather than assume. max=64 on a string counts runes, not bytes, so a 64-character name made of two-byte letters passes, and the shared suite includes exactly that case. required rejects the zero value, which for an integer means 0, so a quantity that may legitimately be zero needs gte and lte instead; a lab test pins that pitfall. Decoder switches such as binding.EnableDecoderDisallowUnknownFields are package-level variables, so they apply to the whole process rather than to one route. ShouldBindJSON hands the error back to you, while BindJSON aborts the request itself with 400, or 413 for an oversized body, before your handler can choose the response. Gin's source also notes that when Gin is built with the sonic or go-json encoders, http.MaxBytesError is not propagated, so a size limit test is worth keeping if you change encoders.

The lab exposed a subtler problem. The store validates again after binding, which is sound defence in depth, but it also means a drifted tag such as max=65 produces exactly the same HTTP responses, because the store rejects what the tag let through. The HTTP suite cannot see that drift. A parity test that runs the same inputs through binding.Validator.ValidateStruct and NewItem.Validate does, and we confirmed it by changing the tag and watching that test fail. With ServeMux or chi you write the decode-and-validate step yourself, using http.MaxBytesReader, json.Decoder and a Validate method. It is more code, but every rule is visible in one place.

One table-driven httptest suite for three routers

Router-independent tests are what make the choice reversible. Each implementation has the same constructor shape, func(*itemstore.Store, string) http.Handler, and the suite loops over all of them:

go
func Implementations() []Impl {
	return []Impl{
		{Name: "stdlib", New: stdapi.New},
		{Name: "chi", New: chiapi.New},
		{Name: "gin", New: ginapi.New},
	}
}

func TestSharedSuite(t *testing.T) {
	for _, impl := range routerfit.Implementations() {
		t.Run(impl.Name, func(t *testing.T) {
			t.Parallel()
			for _, tc := range cases {
				t.Run(tc.name, func(t *testing.T) {
					t.Parallel()
					runCase(t, impl, tc)
				})
			}
		})
	}
}

Each of the 36 cases describes one request and the response contract. A few rows show the style:

go
{name: "literal latest beats wildcard", seed: []string{"bolt", "nut"}, method: "GET", target: "/items/latest", status: 200,
	wantJSON: `{"id":2,"name":"nut","quantity":0}`, storeLen: 2},
{name: "latest with no items", method: "GET", target: "/items/latest", status: 404, wantError: "not_found", storeLen: 0},
{name: "DELETE latest falls through to the wildcard", method: "DELETE", target: "/items/latest", auth: "ok", status: 400, wantError: "invalid_id", storeLen: -1},

{name: "delete", seed: []string{"bolt"}, method: "DELETE", target: "/items/1", auth: "ok", status: 204, storeLen: 0},
{name: "delete without token", seed: []string{"bolt"}, method: "DELETE", target: "/items/1", status: 401, wantError: "unauthorized", storeLen: 1},
{name: "delete missing", method: "DELETE", target: "/items/7", auth: "ok", status: 404, wantError: "not_found", storeLen: 0},

{name: "405 lists allowed methods", method: "PUT", target: "/items/1", status: 405, wantAllow: []string{"DELETE", "GET"}, storeLen: -1},
{name: "405 on a literal route", method: "POST", target: "/items/latest", status: 405, wantAllow: []string{"DELETE", "GET"}, storeLen: -1},

Every case gets a fresh store, an httptest.NewRequest, an httptest.NewRecorder and a direct ServeHTTP call, so all 108 combinations run in parallel without opening a port. The suite asserts what the API promises: status codes, JSON compared as decoded values rather than bytes, the error code in the shared envelope, the media type, the Location of a created item, the store's state afterwards, a request ID on every response, and the set of methods in Allow. It deliberately ignores router-generated 404 and 405 bodies, which are not part of this API's contract.

For real HTTP/1.1 round trips, Go 1.27 added httptest.NewTestServer. It serves over an in-memory network, registers its own cleanup, fails the test if a handler panics, and returns a client that sends every request to the server whatever the host name. The lab uses it for a create-then-follow-Location test against each router. To check that the suite has teeth, we broke the implementations one at a time: removing Gin's HandleMethodNotAllowed or UseEscapedPath, adding a ServeMux catch-all, dropping chi's request-ID middleware, removing the token check from chi's write group, and accepting a zero ID in the shared handlers. Every change failed specific, named cases.

Three differently built cable bundles pass through one shared set of calibrated inspection rings watched by the mascot.
One shared suite holds three routers to the same API contract. AI-generated conceptual illustration.

Differences the lab pins instead of hiding

Some behaviour should not be forced into agreement. TestDocumentedDifferences records it per router, so an upgrade that changes a row fails loudly instead of drifting silently. With the lab's configuration:

  • HEAD on a GET route: ServeMux serves it. chi and Gin answer 405 with Allow: GET. chi's optional middleware.GetHead routes HEAD to GET handlers; in Gin you register HEAD routes explicitly.
  • Trailing slash on a collection: /items/ is a 404 in ServeMux, a 200 in chi, whose mounted sub-router treats it as its root, and a 301 redirect to /items in Gin, whose RedirectTrailingSlash is on by default.
  • Remainder root without a slash: /files is a 307 redirect to /files/ in ServeMux, a 404 in chi and a 301 redirect in Gin.
  • Escaped slash in a remainder: /files/a%2Fb/c yields a/b/c in ServeMux and in Gin with UseEscapedPath, and a%2Fb/c in chi.
  • Unknown path under a protected prefix: /admin/unknown without a token is a 401 in ServeMux and chi and a 404 in Gin.
  • Double slash: ServeMux cleans /items//1 and redirects with 307; chi and Gin return 404.
  • Allow header shape: ServeMux sends one sorted, comma-separated value that includes HEAD; chi sends one value per method in no fixed order; Gin sends one comma-separated value in registration order.

None of these is a bug. Each is a default that clients, proxies, caches and security scanners will observe. Decide which of them your API promises, document those, and test them. The rest can stay router-specific, as long as a test notices when they change.

Migration paths between the three

Moving from ServeMux to chi is mostly rewiring. Handlers and middleware stay as they are, {path...} becomes *, and Route or Group replace nested muxes. Handlers that read r.PathValue keep working because chi v5.5.0 fills it. Before switching traffic, check the edges listed above, especially trailing slashes and escaped paths.

Moving from chi to ServeMux is also mostly rewiring, with three things to find first: regular-expression parameters, which become validation inside the handler; Route-level middleware, which becomes a wrapped sub-mux; and chi.URLParam calls, which become r.PathValue. Most of chi's middleware package is ordinary net/http middleware that you can keep importing; check the few that depend on chi's route context, such as GetHead, which only works under a chi router.

Moving away from Gin means rewriting handlers, so do it gradually. Keep the domain free of gin.Context, as itemstore is here, and keep handlers thin. Gin can host standard handlers during the transition, with one catch the lab found: gin.WrapF passes the request through, but Gin does not fill Request.PathValue, so a handler that reads r.PathValue("id") sees an empty string. Copy the parameters first:

go
// WithPathValues serves a net/http handler from a Gin route during a
// migration. gin.WrapF passes the request through but Gin does not fill
// Request.PathValue, so handlers that read r.PathValue("id") would see "".
// Copying c.Params first lets the same handler run under all three routers.
func WithPathValues(h http.HandlerFunc) gin.HandlerFunc {
	return func(c *gin.Context) {
		for _, p := range c.Params {
			c.Request.SetPathValue(p.Key, p.Value)
		}
		h(c.Writer, c.Request)
	}
}

Standard middleware can run inside Gin through an adapter such as the lab's FromStd, which continues the Gin chain with the possibly replaced request and aborts when the middleware never calls next. It cannot help middleware that wraps the ResponseWriter, because Gin handlers keep writing to c.Writer; those need Gin-native versions. In the other direction, *gin.Engine is an http.Handler, so a Gin application can sit under a ServeMux prefix while routes move one at a time. Whatever the direction, the shared suite is the acceptance test for the migration: move a route, run the suite, ship.

Performance: what to measure instead of quoting benchmarks

This guide publishes no router speed numbers. Figures that circulate usually measure route lookup in isolation on someone else's hardware, while a JSON API tends to spend its time decoding and encoding bodies, in middleware that allocates, and waiting for databases and other services. A router with faster lookup can still be slower in your service if its logging, context or binding layers allocate more per request.

Measure the whole stack with your own route table. The lab's benchmark sends a representative request through middleware, routing and JSON encoding for each implementation, using b.Loop and allocation reporting:

go
func BenchmarkRouters(b *testing.B) {
	for _, impl := range routerfit.Implementations() {
		b.Run(impl.Name, func(b *testing.B) {
			st := itemstore.New()
			if _, err := st.Create(itemstore.NewItem{Name: "bolt"}); err != nil {
				b.Fatal(err)
			}
			h := impl.New(st, token)
			req := httptest.NewRequest("GET", "/items/1", nil)
			b.ReportAllocs()
			for b.Loop() {
				rec := httptest.NewRecorder()
				h.ServeHTTP(rec, req)
				if rec.Code != 200 {
					b.Fatalf("status %d", rec.Code)
				}
			}
		})
	}
}

Run it several times with -count, compare runs with benchstat, and profile with -cpuprofile before drawing conclusions. In production, label latency histograms by route pattern, using r.Pattern, chi's RoutePattern() or Gin's c.FullPath(), never by raw path, which multiplies cardinality with every ID.

One cost can be measured exactly: the dependency graph. Running go list -deps over each implementation package, excluding the standard library and the lab itself, reported no third-party packages for ServeMux, one package from one module for chi, and 101 packages from 19 modules for Gin v1.12.0, with the same counts for darwin/arm64, linux/amd64 and linux/arm64. Gin's requirements include QUIC, protobuf, YAML, TOML and MongoDB BSON support. That is not automatically a problem, but it is more code to build, audit and keep updated.

A decision table based on concrete needs

Choose by the needs you can name today, not by popularity:

  • A new JSON service with a modest route table: ServeMux. Methods, wildcards, 405 responses and conflict detection cover the routing. Write a short Chain helper and an explicit decode-and-validate step, and you have no routing dependency at all.
  • Many groups with different middleware stacks, prefix-wide authentication, mounted sub-applications or regular-expression parameters: chi. You keep standard handlers, so leaving later costs little.
  • An existing Gin codebase, or a team that relies on binding, validation and rendering helpers: Gin, with HandleMethodNotAllowed set deliberately, gin.New plus explicit middleware, the domain kept free of gin.Context, and a parity test for validation tags.
  • Packages meant to be embedded in other services: expose http.Handler and standard handlers so that any of the three can host them.
  • A strict dependency budget or a constrained build target: ServeMux, or chi when its routing features earn their single module.
  • Still unsure: start with ServeMux and write the shared suite first. Moving to chi later is rewiring.

Whatever you pick, serve it from your own http.Server, write down the edge behaviour you promise, and keep one suite that any implementation must pass.

GopherForge has net/http JSON API, chi and Gin REST API project templates; on a phone, the Gin template runs on a bundled Gin-compatible subset rather than the upstream module, so use it to learn Gin's API, not to judge its dependency graph. The Gin course covers the framework in depth. The complete lab is in the routerfit folder of the engineering lab download; run go test -race ./... there with Go 1.27 or later.

Primary sources & editorial method

We checked these primary references on 30 November 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.