Libraries that matter
A Go backend needs few libraries. Here is each one with a verdict, a reason and its current version, and the standard-library code for each row where the standard library wins.
- 1Each dependency needs a reason that the standard library cannot meet. Routing and test assertions no longer pass that test.
- 2Add a library for a contract or a hard algorithm: pgx, sqlc, connect-go, x/sync, JWT parsing.
- 3Pin security options yourself. A library default is not your threat model.
- 4A version below 1.0 is a reason to pin, not a reason to refuse.
package main
import (
"fmt"
"net/http"
"strings"
)
func ok(http.ResponseWriter, *http.Request) {}
func main() {
defer func() {
// The first line of the panic names source files. Skip it.
_, why, _ := strings.Cut(fmt.Sprint(recover()), "\n")
fmt.Println("panic:")
fmt.Println(why)
}()
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}"1, ok)
fmt.Println("first route added")
mux.HandleFunc("GET /{kind}/7"2, ok)
fmt.Println("second route added")
}- 1Matches /items/7, and /items/x.
- 2Also matches /items/7. Neither pattern is more specific, so this line panics.
first route added
panic:
GET /{kind}/7 and GET /items/{id} both match some paths, like "/items/7".
But neither is more specific than the other.
GET /{kind}/7 matches "/kind/7", but GET /items/{id} doesn't.
GET /items/{id} matches "/items/id", but GET /{kind}/7 doesn't.- Moving to ServeMux from a router that takes the first match can show conflicts that were silent.
- The panic runs at startup, so a test that builds the router finds it.
- A literal beats a wildcard, so /items/new and /items/{id} can live together.
ServeMux checks routes when you register them. Two patterns with no winner panic at startup, so a conflict cannot reach production.
| library, latest release | verdict and reason |
|---|---|
| pgx v5.12.0, Oct 2026 | Use The Postgres driver: pool, COPY, batches, LISTEN, native types (G17). |
| sqlc v1.31.1, Apr 2026 | Use Generates typed Go from SQL, and checks queries against the schema before run time. |
| goose v3.29.0, Oct 2026 | Use Plain SQL files, embedded in the binary, with an advisory lock. |
| Atlas v1.3.0, Jul 2026 | For diffed schemas Plans a migration from a desired schema. The community edition lacks down migrations, views and triggers; lint needs a login. |
| connect-go v2 v2.0.2, Oct 2026 | Use for new code A schema, generated clients, and Connect, gRPC and gRPC-Web on one handler (G18). |
| connect-go v1 v1.21.1, Oct 2026 | Existing code Bug fixes and security patches only. New features go to v2. |
| Vanguard v0.5.0, Oct 2026 | When REST clients stay Serves one handler as REST too, from google.api.http rules. The version is below 1.0, so pin it. |
| chi v5.5.0, Oct 2026 | Prefer the stdlib ServeMux has methods and wildcards. chi stays worth it for deep route trees with many middleware groups. |
| x/sync v0.24.0, Sep 2026 | Use errgroup, semaphore and singleflight have no standard equivalent (G12). |
| x/time/rate v0.16.0, Aug 2026 | Use A token bucket with Wait and Allow. For a single process only (G12). |
| testcontainers-go v0.44.0, Aug 2026 | When CI has Docker A real Postgres per test run. Slower than a shared server, and it needs a container runtime. |
| OpenTelemetry v1.47.0, Oct 2026 | Use The vendor-neutral API for traces and metrics. Traces and metrics are stable; logs are a release candidate. |
| golang-jwt v5.3.1, Jan 2026 | Use, with pinned options Do not write JWT parsing yourself. Pin the method, issuer and audience (panel J). |
| testify v1.12.1, Aug 2026 | Prefer the stdlib Three small helpers cover most of it, with no dependency and a better failure line. |
All GitHub-hosted projects here were unarchived with commits in October 2026, checked on the same day. A red mark means prefer the standard library: the project itself is healthy.
I keep the list short. Every row has a reason, and the standard library wins wherever it now covers the need.
| need | ServeMux | chi |
|---|---|---|
| Method match | 1.22 | Yes |
| Wildcards | 1.22 | Yes |
| 405 with Allow | Yes | Yes |
| Matched route in logs | r.Pattern, 1.23 | Yes |
| Middleware stack | Chain, 3 lines | Yes |
| Route groups | A sub-mux | Yes |
| Regex in a path segment | No | Yes |
| A dependency | None | One small module |
Both use http.Handler, so middleware moves across unchanged.
I start on ServeMux. I move to chi when route groups with their own middleware fill the file, and that move is small.
// NewRouter covers the routes most APIs need with no dependency. Methods,
// wildcards and most-specific-wins matching are in net/http since Go 1.22.
func NewRouter(log *slog.Logger, key string) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}"1, show("home"))
mux.HandleFunc("GET /items/{id}", show("item"))
mux.HandleFunc("GET /items/new"2, show("new item form"))
mux.HandleFunc("POST /items", show("create item"))
mux.HandleFunc("GET /files/{path...}"3, show("file"))
mux.Handle("/admin/", http.StripPrefix("/admin", admin(key))4)
return Chain(mux, Logged(log))
}
func show(name string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, path := r.PathValue("id"), r.PathValue("path")
fmt.Fprintf(w, "%s id=%q path=%q", name, id, path)
}
}- 1The exact root. A bare "/" is a subtree that catches every path.
- 2A literal beats the wildcard route above, in any order.
- 3A final wildcard takes the rest of the path, with its slashes.
- 4A route group: the inner router sees /users/7.
Methods, wildcards and most-specific-wins are in net/http. r.PathValue reads a wildcard.
// Chain applies middleware so that the first one listed runs first. This is
// what chi's Use does, in 3 lines.
func Chain(h http.Handler, mw ...Middleware) http.Handler {
for _, m := range slices.Backward(mw)1 {
h = m(h)
}
return h
}
// Logged logs each request. r.Pattern2 is the route that matched, so the log
// groups requests by route and not by raw path.
func Logged(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Info("request", "pattern", r.Pattern,
"took", time.Since(start))
})
}
}- 1Go 1.23. The last middleware wraps first, so the first one listed runs first.
- 2Go 1.23. Logs and metrics group by route. A raw path has too many values.
Middleware is a function from Handler to Handler. Chain applies a list, and that is all of chi.Use I need here.
// RequireKey is a middleware for one group of routes.
func RequireKey(key string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Api-Key") != key {
http.Error(w, "no key", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
// admin is a route group: its own mux with its own middleware.
func admin(key string) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", show("admin user"))
return Chain(mux, RequireKey(key))1
}- 1This middleware covers the group only.
chi writes this as r.Route with r.Use. The mechanism is the same: one handler wraps another.
A group is a smaller ServeMux with its own middleware, mounted under a prefix.
GET /items/7 : 200
r.Pattern GET /items/{id}
body item id="7" path=""
The most specific route that matches wins.
405 comes free, and the most specific pattern wins. I log r.Pattern, so metrics stay grouped by route.
| testify | standard library |
|---|---|
| assert.Equal | if got != want, or equal[T] |
| assert.Equal on slices | slices.Equal, or deepEqual |
| assert.ElementsMatch | slices.Sort, then slices.Equal |
| require.NoError | t.Fatalf, or noError |
| assert.ErrorIs | errors.Is |
| assert.ErrorAs | errors.AsType[T] (1.26) |
| suite.Suite | t.Run, t.Cleanup |
| mock.Mock | A small fake that implements the interface |
Keep testify where a test suite already uses it. A rewrite gains little.
Three helpers replace most of testify in my tests. They add no dependency, and each failure points at the right line.
// equal fails the test with both values. t.Helper makes the failure point
// at the caller, which is the line the reader needs.
func equal[T comparable](t *testing.T, got, want T) {
t.Helper()1
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}
// deepEqual is for slices, maps and structs that hold them.
func deepEqual[T any](t *testing.T, got, want T) {
t.Helper()
if !reflect.DeepEqual(got, want)2 {
t.Errorf("got %+v, want %+v", got, want)
}
}
// noError stops the test, as require.NoError does, because the next lines
// use the result.
func noError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf3("unexpected error: %v", err)
}
}- 1The failure reports the caller's line, not this one.
- 2A nil slice and an empty slice differ here (see the drill).
- 3Stops this test. t.Errorf continues, so one run shows many failures.
func TestRouter(t *testing.T) {
log := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := httptest.NewServer(NewRouter(log, "k"))
defer srv.Close()
tests := []struct {
name, method, path string
wantStatus int
wantBody string
}{
{"wildcard", "GET", "/items/7", 200, `item id="7"`},
{"literal wins", "GET", "/items/new", 200, `new item form`},
{"rest of path", "GET", "/files/a/b.txt", 200, `file id=""`},
{"wrong method", "DELETE", "/items/7", 405, ""},
{"exact root only", "GET", "/nope", 404, ""},
{"group needs key", "GET", "/admin/users/7", 401, ""},
}
for _, tt := range tests {
t.Run(tt.name1, func(t *testing.T) {
req, err := http.NewRequestWithContext(t.Context(),
tt.method, srv.URL+tt.path, nil)
noError(t, err)
res, err := srv.Client().Do(req)
noError(t, err)
defer res.Body.Close()2
body, err := io.ReadAll(res.Body)
noError(t, err)
equal(t, res.StatusCode, tt.wantStatus)
equal(t, strings.HasPrefix(string(body), tt.wantBody), true)
})
}
}- 1Each row is a subtest, so go test -run can pick one.
- 2Closure scope: this runs when the subtest ends.
t.Helper makes the failure point at the caller. Fatal stops a test when the next line needs the value.
// Verify accepts a token only with the expected algorithm, issuer and
// audience, and only with an expiry. Each option closes a known forgery.
func Verify(secret []byte, token string) (*Claims, error) {
var c Claims
_, err := jwt.ParseWithClaims(token, &c,
func(*jwt.Token) (any, error) { return secret, nil },
jwt.WithValidMethods1([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithIssuer("orders-api"),
jwt.WithAudience("orders-web"),
jwt.WithExpirationRequired()2,
jwt.WithLeeway(30*time.Second)3,
)
if err != nil {
return nil, fmt.Errorf("verify: %w", err)
}
return &c, nil
}- 1Without this, the token picks its own algorithm. The drill shows the forgery.
- 2The exp claim is optional by default, so a token with none never expires.
- 3Allows clock skew between servers.
| token | Verify says |
|---|---|
| alg none | token signature is invalid: signing method none is invalid |
| HS512, right key | token signature is invalid: signing method HS512 is invalid |
| wrong key | token signature is invalid: signature is invalid |
| expired an hour ago | token has invalid claims: token is expired |
| no expiry | token has invalid claims: token is missing required claim: exp claim is required |
| wrong issuer | token has invalid claims: token has invalid issuer |
| wrong audience | token has invalid claims: token has invalid audience |
Each row is a real token. errors.Is with jwt.ErrTokenExpired finds the one case a client can fix with a refresh.
I pin the method, issuer and audience, and I require an expiry. The token's own header never picks the key.
| need | use | stdlib option |
|---|---|---|
| Wait for goroutines | sync.WaitGroup.Go | This one, 1.25 |
| First error, cancel the rest | errgroup | No |
| Limit, count 1 each | chan struct{} | This one |
| Limit with weights and ctx | semaphore | No |
| Share one call among callers | singleflight | No |
| Token bucket | rate.Limiter | No |
Code for each one is on G12.
WaitGroup.Go waits. errgroup also returns the first error and cancels the rest, so I use it when a goroutine can fail.
| question | choose |
|---|---|
| You write each migration by hand | goose |
| You want a plan from a target schema | Atlas |
| A mix of both | Atlas writes goose files through its goose format |
| CI has Docker, tests need isolation | testcontainers-go |
| Tests share a local server | One database per package |
| A mock of the database | It hides real behavior |
The tests behind G17 use one database per package on one server, so they need no container.
I use goose until I need a planner. For tests I use a real Postgres, in a container on CI or a shared server locally.
| layer | how | version |
|---|---|---|
| RPC server, client | otelconnect | v0.12.0 |
| Plain HTTP | otelhttp | Contrib module |
| pgx | A pgx.QueryTracer, as in the G17 count test | Your code, or a contrib tracer |
| Your logs | log/slog | Standard library |
The current otelconnect and Vanguard releases depend on connect-go v2. Signals are on O3.
I instrument at the edges: the HTTP or RPC layer and the database driver. A span per function adds cost and hides the signal.
| since | what changed | which library it replaces |
|---|---|---|
| 1.21 | log/slog, slices, maps, cmp. | Most logging wrappers, and x/exp slices. |
| 1.22 | ServeMux methods and wildcards. | Routers, for most APIs. |
| 1.23 | Request.Pattern. iter, and slices.Backward. | Router-specific route labels for metrics. |
| 1.24 | T.Context and B.Context. Server.Protocols. | h2c wrappers from x/net. |
| 1.25 | sync.WaitGroup.Go. testing/synctest. http.CrossOriginProtection. | errgroup with no errors. CSRF token middleware, for many apps. |
| 1.26 | errors.AsType. ServeMux slash redirects use 307. slog.NewMultiHandler. | Hand-written log fan-out. |
| 1.27 | The uuid package, with versions 4 and 7. encoding/json/v2. | google/uuid for new code. Third-party JSON for stricter decoding. |
| when | the moment | what to do or say |
|---|---|---|
| build | You need a router. | ServeMux. Type no go get in the first 45 minutes. |
| build | You need assertions. | The 3 helpers fit in a minute. A table test proves more than a library call. |
| talk | "What would you add for production?" | pgx with sqlc and goose, then OpenTelemetry at the edges. Give one reason for each. |
| talk | "Why not an ORM?" | sqlc keeps the SQL visible, and the compiler checks it. An ORM hides the N+1 and the lock. |
| talk | "How do you judge a dependency?" | What it replaces, its maintainers, its transitive modules, and how you leave it. |
| talk | "How do you handle JWTs?" | Pin the algorithm, issuer and audience, require an expiry, and keep the lifetime short. |
In the build I use the standard library only. In the talk I name the library and the reason for each step toward production.
0 of 10 known
Predict the output. GET and PUT routes exist for one path.
package main import ( "fmt" "net/http" "net/http/httptest" ) func ok(http.ResponseWriter, *http.Request) {} func probe(h http.Handler, method, path string) { rec := httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest(method, path, nil)) fmt.Printf("%s %s: %d %s\n", method, path, rec.Code, rec.Header().Get("Allow")+rec.Header().Get("Location")) } func main() { mux := http.NewServeMux() mux.HandleFunc("GET /items/{id}", ok) mux.HandleFunc("PUT /items/{id}", ok) probe(mux, "DELETE", "/items/7") probe(mux, "HEAD", "/items/7") probe(mux, "GET", "/items") }Predict the output.
package main import ( "fmt" "net/http" "net/http/httptest" ) func ok(http.ResponseWriter, *http.Request) {} func probe(h http.Handler, method, path string) { rec := httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest(method, path, nil)) fmt.Printf("%s %s: %d %s\n", method, path, rec.Code, rec.Header().Get("Allow")+rec.Header().Get("Location")) } func main() { mux := http.NewServeMux() mux.HandleFunc("GET /docs/", ok) mux.HandleFunc("GET /items/{$}", ok) probe(mux, "GET", "/docs") probe(mux, "GET", "/docs/a/b") probe(mux, "GET", "/items/") probe(mux, "GET", "/items/7") }Predict the output. The request goes through two routers.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { inner := http.NewServeMux() inner.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Println("path:", r.URL.Path, "id:", r.PathValue("id")) }) outer := http.NewServeMux() outer.Handle("/v1/", http.StripPrefix("/v1", inner)) r := httptest.NewRequest("GET", "/v1/users/7", nil) outer.ServeHTTP(httptest.NewRecorder(), r) fmt.Println("after:", r.URL.Path, "id:", r.PathValue("id")) }Predict the output. The path holds an escaped slash.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Printf("%q %q\n", r.PathValue("id"), r.PathValue("ID")) }) mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/a%2Fb", nil)) }Predict the output.
package main import ( "fmt" "reflect" "slices" ) func main() { var a []int b := []int{} fmt.Println(a == nil, b == nil) fmt.Println(reflect.DeepEqual(a, b)) fmt.Println(slices.Equal(a, b)) }Predict the output. Both values are the same instant.
package main import ( "fmt" "reflect" "time" ) func main() { a := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) b := a.In(time.FixedZone("IST", 19800)) fmt.Println(a == b) fmt.Println(reflect.DeepEqual(a, b)) fmt.Println(a.Equal(b)) }Predict the output.
package main import ( "errors" "fmt" "io/fs" ) func main() { err := fmt.Errorf("load config: %w", fs.ErrNotExist) fmt.Println(err == fs.ErrNotExist) fmt.Println(errors.Is(err, fs.ErrNotExist)) fmt.Println(err.Error() == fs.ErrNotExist.Error()) }Predict the output. The token has alg none and no signature.
package main import ( "fmt" "github.com/golang-jwt/jwt/v5" ) func main() { claims := jwt.MapClaims{"sub": "ada"} token := jwt.NewWithClaims(jwt.SigningMethodNone, claims) s, err := token.SignedString(jwt.UnsafeAllowNoneSignatureType) if err != nil { panic(err) } _, err = jwt.Parse(s, func(*jwt.Token) (any, error) { return []byte("secret"), nil }) fmt.Println(err) }Predict the output. The key function trusts the alg header.
package main import ( "crypto/ed25519" "crypto/rand" "fmt" "github.com/golang-jwt/jwt/v5" ) func main() { // The server signs with EdDSA. Its public key is public. public, _, err := ed25519.GenerateKey(rand.Reader) if err != nil { panic(err) } // The attacker signs with HS256, using the public key as the secret. forged := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": "attacker"}) s, err := forged.SignedString([]byte(public)) if err != nil { panic(err) } key := func(t *jwt.Token) (any, error) { if t.Method.Alg() == "HS256" { return []byte(public), nil } return public, nil } _, err = jwt.Parse(s, key) fmt.Println("no pinned method:", err) _, err = jwt.Parse(s, key, jwt.WithValidMethods([]string{"EdDSA"})) fmt.Println("pinned to EdDSA:", err) }Predict the output.
package main import ( "fmt" "time" "uuid" ) func main() { a := uuid.NewV7() time.Sleep(2 * time.Millisecond) b := uuid.NewV7() s := a.String() fmt.Println(len(s), string(s[14])) fmt.Println(a.Compare(b) < 0) _, err := uuid.Parse("not-a-uuid") fmt.Println(err != nil) }
- route lookup
- 145 ns with 101 routes.
- 2 wildcards
- 245 ns.
- 2 middleware
- 63.3 ns for the chain.
- direct call
- 1.4 ns.
Routing costs under 1 µs, and one query costs about 50 µs (G17). Router speed does not decide this choice. Go 1.27.3, GOMAXPROCS 16, median of 3 interleaved runs, on a busy machine.