Columns › 2. Writing a service › Part 5
net/http and Middleware in Go
net/http 與中介層
Build the HTTP entry point of an order service with only the standard library: Go 1.22 method and wildcard routing, composable middleware (request IDs, slog logging, panic recovery, body limits) and sensible http.Server timeouts.
In this article
- What this article solves
- Step 1: Understand the Handler interface first
- Step 2: Go 1.22's routing rules
- Step 3: Middleware is just a function
- Step 4: Intercept the status code and write a logging middleware
- Step 5: Assemble a complete middleware chain
- Step 6: Configure http.Server timeouts
- Common pitfalls
- Key takeaways
- Next
In the previous article, “Go context: Cancellation, Timeouts and Request-Scoped Values”, we learned how to pass cancellation signals and timeouts all the way down the call chain. This article assembles the parts from the first four articles and writes the online shop's order service its first real entry point for HTTP requests, where context makes its first appearance as r.Context().
What this article solves
The first four articles laid the Go fundamentals: “Go Project Layout and Go Modules” settled the example.com/shop module and the cmd/ and internal/ directory plan, “Error Handling in Go: Wrapping, Sentinels and Custom Types” covered how errors are wrapped and inspected, “Goroutines, Channels and Concurrency Patterns in Go” covered concurrency, and the previous article covered context. From this article on we enter Part 2, "Writing a service", where we assemble these parts into a backend program that can really accept requests. The whole of Part 2 sticks with the same example: the online shop's order service (cmd/order/main.go), which can create and look up orders, and later gets a database and tests. An order's fields are ID, UserID, Items, Total (an integer in minor units) and Status (pending, paid, cancelled) throughout.
When many people first write an HTTP service in Go, their first reflex is to look for a framework. That used to make sense: before Go 1.22, the standard library's http.ServeMux could only match path prefixes, couldn't restrict HTTP methods and couldn't extract parameters from the path, so for the most common RESTful paths like /orders/42 you had to split strings yourself. But since Go 1.22, ServeMux supports patterns like GET /orders/{id}, with method matching, path wildcards and automatic 405 responses built in. For most services the standard library is now enough, and one dependency fewer is one fewer thing whose versions you have to track, whose source you have to read, and whose abandonment you have to worry about.
This article does the following, step by step:
- Write a minimal working order API with
net/http, and understand its three core roles:Handler,HandlerFuncandResponseWriter. - Understand Go 1.22's new routing rules: methods, wildcards,
{path...},{$}and precedence. - Understand that "middleware" is really just
func(http.Handler) http.Handler, and write request IDs, logging, panic recovery and body-size limits by hand. - Chain middleware together, and understand why the order matters.
- Configure the various
http.Servertimeouts so the service isn't dragged down by slow connections.
Step 1: Understand the Handler interface first
The core of the entire net/http design is a single interface:
http.Handler: it has just one method,ServeHTTP(w http.ResponseWriter, r *http.Request).
Any type that implements this method can handle HTTP requests. When the server receives a request, it starts a goroutine for each request and calls ServeHTTP on the Handler you gave it. This means two things: first, your handler is always called concurrently, so shared state must be protected with locks or other synchronisation; second, each request is independent of the others, so one stuck request doesn't directly block others, but it does tie up a goroutine and a connection.
So that you don't have to declare a new type every time, the standard library provides http.HandlerFunc. It is a function type that itself implements ServeHTTP, so any function with a matching signature becomes a Handler when converted to http.HandlerFunc. This little trick of "a function can implement an interface too" will come up again and again when we write middleware shortly.
http.ResponseWriter is where you write the response. It has three methods, and their order matters:
| Method | Purpose | Notes |
|---|---|---|
Header() | Gets the map of response headers | Must be set before WriteHeader or the first Write; changes after that aren't sent |
WriteHeader(code) | Sends the status code and headers | Only effective once; a second call shows a superfluous warning in the log |
Write(b) | Writes the body | If WriteHeader hasn't been called yet, it sends 200 first automatically |
The most common beginner mistake is to Write some content first and only then remember to set Content-Type or change the status code, so the client always receives 200. Get into the habit of "set headers first, then write the status code, then write the body", and most strange problems never happen.
Below is the first version of the order service, all in one file, cmd/order/main.go, with data kept in an in-memory map; the focus is on how routing and responses are written. The next article splits it into internal/order/.
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"sync"
)
type Item struct {
ProductID int64 `json:"product_id"`
Qty int `json:"qty"`
Price int64 `json:"price"` // in minor units, to avoid floating-point errors
}
type Order struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Items []Item `json:"items"`
Total int64 `json:"total"`
Status string `json:"status"` // pending / paid / cancelled
}
type store struct {
mu sync.Mutex
nextID int64
orders map[int64]Order
}
func (s *store) getOrder(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "id must be a number", http.StatusBadRequest)
return
}
s.mu.Lock()
o, ok := s.orders[id]
s.mu.Unlock()
if !ok {
http.Error(w, "order not found", http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, o)
}
func (s *store) createOrder(w http.ResponseWriter, r *http.Request) {
var in Order
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "malformed JSON", http.StatusBadRequest)
return
}
if in.UserID <= 0 || len(in.Items) == 0 {
http.Error(w, "user_id and items are required", http.StatusBadRequest)
return
}
in.Total = 0
for _, it := range in.Items {
in.Total += it.Price * int64(it.Qty)
}
in.Status = "pending"
s.mu.Lock()
s.nextID++
in.ID = s.nextID
s.orders[in.ID] = in
s.mu.Unlock()
w.Header().Set("Location", "/orders/"+strconv.FormatInt(in.ID, 10))
writeJSON(w, http.StatusCreated, in)
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("write response: %v", err)
}
}
func main() {
s := &store{orders: make(map[int64]Order)}
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", s.getOrder)
mux.HandleFunc("POST /orders", s.createOrder)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}A few details worth noting: Total is calculated by the server from the items rather than trusting the value the client sends, and it is stored as an integer number of minor units, avoiding floating-point errors like 0.1 + 0.2 when summing; new orders always start in the pending status; a successful creation returns 201 Created with a Location header pointing to the new resource's address, which is the semantically correct thing to do in HTTP; and writeJSON gathers "set Content-Type, write the status code, encode JSON" in one place, so they aren't repeated all over the handlers and the order is hard to get wrong.
You can try it with curl:
go run .
curl -i -X POST localhost:8080/orders \
-d '{"user_id":7,"items":[{"product_id":1,"qty":2,"price":600}]}'
curl -i localhost:8080/orders/1
curl -i -X DELETE localhost:8080/orders/1 # 405 Method Not Allowed, with Allow: GET, HEADTip:
http.ListenAndServeuses a server with no timeouts configured at all, which is only suitable for practice. In production, always create your ownhttp.Server; Step 6 explains why.
Step 2: Go 1.22's routing rules
The "GET /orders/{id}" in the previous step is the routing syntax added in Go 1.22. The full form of a pattern is [method] [host]/[path], and any of the three parts can be omitted as needed.
Figure: ServeMux matches the method and path together, and once a pattern matches, r.PathValue extracts the wildcard's value.
Method matching
Put a method at the front of a pattern and only requests with that method will match. There are two thoughtful defaults: when you write GET, HEAD requests also match the same handler automatically (the server discards the body and sends only the headers); and if a pattern matches the path but none of the methods match, ServeMux responds with 405 Method Not Allowed and automatically adds an Allow header listing the permitted methods. You used to have to write these checks yourself; now they're all built in.
Path wildcards
{id}: matches one whole segment of the path (the content between two slashes) and never crosses a slash./orders/{id}matches/orders/42but not/orders/42/items.{path...}: can only be the last segment, and consumes all the remaining path, slashes included. Good for file serving or proxies.{$}: means the path must end exactly here. The pattern/would normally match every path (because it ends in a slash, which means prefix matching); written as/{$}, it only matches the root path itself.
In the handler, get the value with r.PathValue("id"). It always returns a string, and conversion and validation are your responsibility. The value is URL-decoded first, so you don't have to deal with encodings like %20 yourself.
Precedence and conflicts
When several patterns match the same request, ServeMux picks the most specific one. Specific means that the set of requests it can match is a subset of the other's. For example, /orders/new is more specific than /orders/{id}, so /orders/new goes to the former; GET /orders/{id} is more specific than /orders/{id} because it also restricts the method.
If two patterns' matching sets overlap but neither is more specific than the other (for example /orders/{id} and /{kind}/42), registration panics outright. This is deliberate: a routing conflict that blows up at startup is better than some request mysteriously going to the wrong handler after going live.
| Pattern | /orders/42 | /orders/42/items | /orders/ | Explanation |
|---|---|---|---|---|
/orders/{id} | Matches | No match | No match | The wildcard takes only one segment, and it can't be empty |
/orders/{rest...} | Matches | Matches | Matches | Consumes everything left, which can be empty |
/orders/ | Matches | Matches | Matches | A trailing slash means prefix matching |
/orders/{$} | No match | No match | Matches | Only matches exactly /orders/ |
Tip: Since Go 1.23,
http.Requesthas aPatternfield recording the pattern string that actually matched (for exampleGET /orders/{id}). Grouping logs and metrics by it is much better than using the raw path, because/orders/1to/orders/99999fall into the same group, so the number of metric labels doesn't explode.
Step 3: Middleware is just a function
Once the service has routing, it immediately runs into a class of things that "every request needs": recording how long a request took and what status code it returned; giving each request an ID to make tracing easier; not dropping the whole connection when a handler panics; limiting the size of uploaded bodies; checking authentication tokens; adding CORS or security headers. If every handler does these itself, it's not only repetitive, but someone is bound to forget.
Middleware is the way to factor out these cross-cutting concerns. In Go there's nothing magic about it; it's just a function like this:
// Snippet
type Middleware func(http.Handler) http.HandlerIt takes the "next" handler and returns a new handler. When the new handler is called, it can do things before calling the next one (such as noting the start time), decide whether to call the next one at all (such as responding 401 straight away when authentication fails), and do things after the next one returns (such as calculating the duration and writing a log). Because input and output are both http.Handler, middleware can be stacked indefinitely, and ServeMux itself is just a Handler that can be wrapped at the very centre.
This layer-upon-layer structure is often compared to an onion: the request passes inwards through every layer from the outermost to reach the real handler, and the response passes back outwards through the layers from the inside.
Figure: each middleware layer wraps the inner layers; the request passes from outside in, and the response from inside out, through the same set of middleware.
Once you understand this structure, a few consequences follow naturally:
- Outer layers can see the results of inner layers; inner layers can't see what outer layers do afterwards. Put the logging middleware outside panic recovery and it records the 500 written after recovery; put it the other way round and the panic shoots straight through the logging layer, so the log misses it.
- Any layer can "short-circuit". When the authentication middleware finds an invalid token, it writes 401 and returns without calling
next, and the inner layers never run at all. - Passing data to inner layers relies on context. Middleware can create a new request with
r.WithContext(context.WithValue(...))and pass it down, and inner layers read the value fromr.Context(). This is the request-scoped data mentioned in “Go context: Cancellation, Timeouts and Request-Scoped Values”; keys should use an unexported type to avoid clashing with other packages.
Step 4: Intercept the status code and write a logging middleware
The logging middleware needs to record the status code, but http.ResponseWriter has no method for "reading back which status code was just written". The standard approach is to wrap it in your own ResponseWriter that intercepts WriteHeader and Write, remembers what was written, and passes them on to the real one.
// Snippet
type statusRecorder struct {
http.ResponseWriter
status int
bytes int
}
func (r *statusRecorder) WriteHeader(code int) {
if r.status == 0 {
r.status = code
}
r.ResponseWriter.WriteHeader(code)
}
func (r *statusRecorder) Write(b []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK // calling Write without WriteHeader is the same as 200
}
n, err := r.ResponseWriter.Write(b)
r.bytes += n
return n, err
}
// Unwrap lets http.ResponseController find the underlying Flusher and other features.
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }This uses struct embedding: statusRecorder embeds http.ResponseWriter, so Header() is forwarded to the underlying writer automatically, and we only override the two methods we need to intercept.
Why Unwrap is needed
Wrapping a ResponseWriter has a classic side effect: the underlying writer often implements other interfaces too, such as http.Flusher (to flush buffered output when streaming a response) or http.Hijacker (for WebSocket to take over the connection). Once it's wrapped, a type assertion w.(http.Flusher) from outside fails, because statusRecorder itself has no Flush method.
http.ResponseController, added in Go 1.20, solves this problem: it follows Unwrap() http.ResponseWriter methods inwards layer by layer until it finds a writer that supports the feature. So as long as your wrapper type provides Unwrap and handlers switch to http.NewResponseController(w).Flush(), middleware won't get in the way. It's a habit worth adopting whenever you write middleware.
Logging with slog
Since Go 1.21 the standard library has structured logging in log/slog. Rather than stitching everything into one line of text, structured logging outputs each field separately (as JSON, for example), so logging platforms can filter and aggregate directly by field. The core of the logging middleware is: note the start time, wrap w in a statusRecorder, call the next layer, and finally output the method, the matched pattern, the status code, the byte count and the duration. The complete version is in the program in the next step.
Tip:
logger.LogAttrswith typed attributes such asslog.Stringandslog.Intmakes fewer memory allocations than thelogger.Info("msg", "key", value)style of alternating keys and values, and fields can't get misaligned because you left out an argument. On hot paths, prefer the former for logging.
Step 5: Assemble a complete middleware chain
Now let's write out the commonly used middleware and chain them together with a small Chain function:
- RequestID: reuse the
X-Request-IDpassed from upstream (such as the gateway), or generate one if there isn't any, put it in the context and write it back in the response header. With every log carrying this ID, you can tie together the logs of the same request across different services. - Logging: the logging middleware from the previous step.
- Recover: catch handler panics, log the stack and respond 500, so a programming error in one request doesn't affect the connection.
- LimitBody: use
http.MaxBytesReaderto limit the request body size, stopping anyone from uploading huge content that eats all the memory.
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"os"
"runtime/debug"
"time"
)
// Middleware takes the next handler and returns a new, wrapped handler.
type Middleware func(http.Handler) http.Handler
// Chain applies middleware "from outside in": Chain(h, a, b) equals a(b(h)).
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
type ctxKey struct{}
func RequestIDFrom(ctx context.Context) string {
id, _ := ctx.Value(ctxKey{}).(string)
return id
}
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if id == "" || len(id) > 64 {
b := make([]byte, 8)
rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, id)))
})
}
type statusRecorder struct {
http.ResponseWriter
status int
bytes int
}
func (r *statusRecorder) WriteHeader(code int) {
if r.status == 0 {
r.status = code
}
r.ResponseWriter.WriteHeader(code)
}
func (r *statusRecorder) Write(b []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
n, err := r.ResponseWriter.Write(b)
r.bytes += n
return n, err
}
// Unwrap lets http.ResponseController find the underlying Flusher and other features.
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
func Logging(logger *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
logger.LogAttrs(r.Context(), slog.LevelInfo, "http request",
slog.String("request_id", RequestIDFrom(r.Context())),
slog.String("method", r.Method),
slog.String("pattern", r.Pattern),
slog.Int("status", rec.status),
slog.Int("bytes", rec.bytes),
slog.Duration("duration", time.Since(start)),
)
})
}
}
func Recover(logger *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler {
panic(v) // the signal for a deliberately aborted connection; hand it back to net/http
}
logger.Error("panic recovered",
slog.String("request_id", RequestIDFrom(r.Context())),
slog.Any("panic", v),
slog.String("stack", string(debug.Stack())),
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}()
next.ServeHTTP(w, r)
})
}
}
// LimitBody limits the request body size; reading past the limit makes Read return *http.MaxBytesError.
func LimitBody(n int64) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, n)
next.ServeHTTP(w, r)
})
}
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "order %s\n", r.PathValue("id"))
})
mux.HandleFunc("GET /boom", func(w http.ResponseWriter, r *http.Request) {
panic("demo panic")
})
handler := Chain(mux,
RequestID,
Logging(logger),
Recover(logger),
LimitBody(1<<20),
)
srv := &http.Server{
Addr: ":8080",
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
}
logger.Info("listening", slog.String("addr", srv.Addr))
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("server stopped", slog.Any("err", err))
os.Exit(1)
}
}How to order them
The order of Chain's arguments is the order from outside in, which reads the same as the order a request passes through. The ordering in this example has its reasons:
- RequestID outermost: so every later layer, including logging and panic recovery, can get the request ID.
- Logging outside Recover: only after the panic has been recovered into a 500 can the logging layer see that 500. The other way round, the panic passes through the logging layer first and the request disappears from the logs, when it is precisely the one that most needs to be seen.
- Recover as far out as possible: it can only rescue panics from "inner" layers, so the further out it is, the more it protects.
- LimitBody towards the inside: it only swaps out
r.Body, so it can go anywhere, as long as it comes before the handler that reads the body.
Middleware that "short-circuits", such as authentication and authorisation, usually goes inside logging and outside the handler: rejected requests should still be logged, but they don't need to enter the business logic. Routes can also have middleware applied by group: for example, if only routes under /admin/ need administrator authentication, you can create a separate ServeMux for the admin routes, wrap it, and mount it on the main mux, so you don't have to write the authentication logic into every handler.
Two details about panic recovery
First, net/http actually catches handler panics itself to stop the whole program from exiting, but it only prints the stack to the server's error log and closes the connection, so the client sees a connection reset rather than a proper 500. Writing your own recovery layer lets you output a structured log with the request ID and return a normal error response.
Second, http.ErrAbortHandler is the standard library's agreed signal for a "deliberate abort", used for example by the reverse proxy when it finds the upstream has disconnected. The recovery layer should re-panic with it unchanged so that net/http aborts the connection as expected, rather than logging it as a programming error.
Remember too: the recovery layer can only rescue panics in the same goroutine. If a handler starts its own goroutine, a panic in that goroutine is not caught by any middleware and ends the whole program directly. This is one of the reasons “Goroutines, Channels and Concurrency Patterns in Go” stresses managing the lifecycle of every goroutine.
Body size limits
Once http.MaxBytesReader wraps r.Body, reading past the limit returns *http.MaxBytesError, which the handler can detect with errors.As and respond with 413 Request Entity Too Large. It also tells the server to close the connection after the response, so it doesn't keep reading the rest of the huge content. The 1 MiB in the example is only illustrative; the real limit should be set by the API's needs, and endpoints such as file uploads can relax it in their own handlers.
Step 6: Configure http.Server timeouts
http.ListenAndServe uses a zero-value http.Server, where every timeout is "unlimited". That is very dangerous in production: a malicious client, or one on a very poor network, can send headers extremely slowly, one byte at a time, holding on to a connection and a goroutine; enough such connections can exhaust the server's resources. This kind of attack is usually called Slowloris.
Figure: the four timeouts each govern a different section of the connection's lifecycle, and WriteTimeout starts counting once the headers have been read.
| Field | Covers | Consequence of not setting it |
|---|---|---|
ReadHeaderTimeout | From accepting the connection (or the end of the previous request) to reading the request headers | Sending headers slowly can hold a connection |
ReadTimeout | Reading the whole request, headers and body | Uploading the body slowly holds a connection |
WriteTimeout | From finishing reading the headers to finishing writing the response | If the client doesn't read the response, the server waits forever |
IdleTimeout | How long a keep-alive connection waits for the next request | Idle connections pile up over time; if unset, ReadTimeout is used |
A few things to consider when configuring them:
ReadHeaderTimeoutshould almost always be set, and it can be short; a normal client needs very little time to send headers. Static analysis tools also commonly flag "this field isn't set" as a security issue.ReadTimeoutandWriteTimeoutare shared by the whole server and treat every route the same. If some endpoints need long-running streams (such as large downloads or Server-Sent Events), the globalWriteTimeoutcuts them off. In that case you can extend it individually in that handler withhttp.NewResponseController(w).SetWriteDeadline(...), which is another reason Step 4 required the wrapper type to provideUnwrap.- Timeouts only cut off reads and writes on the connection; they do not automatically stop your handler. When the handler should give up depends on
r.Context(): this context is cancelled when the client disconnects, and as long as the handler carries it into calls to the database or other services, the work can stop early. This is exactly where the previous article's context comes into play. - If you want to give the "business processing" an explicit time limit and return 503, you can wrap the handler with
http.TimeoutHandler. After the timeout it writes the 503 for you and cancels the request's context; but the handler itself still has to respect the context to actually stop.
The numbers of seconds in the example are only illustrative; the real values depend on the nature of the service: a pure JSON API usually responds quickly, so you can set them tighter, while a service with file uploads or report exports needs them relaxed, or the slow endpoints moved to a separately configured server. As for how to let in-flight requests finish before exiting when the server receives a shutdown signal, that is covered in detail in “Configuration and Graceful Shutdown in Go”.
Finally, the ErrorLog field makes net/http's internal error messages (such as TLS handshake failures and handler panics) go through the same slog logging too. slog.NewLogLogger turns a slog handler into an old-style *log.Logger, so all the logs have a consistent format.
Common pitfalls
- Setting headers after writing the body. The first
Writesends the status code and headers, so changingHeader()or callingWriteHeaderafterwards has no effect, and the log shows a superfluousWriteHeaderwarning. - Forgetting to
returnafterhttp.Error.http.Erroronly writes the response; it doesn't end the function, so the code after it still runs and may write the body again or carry on doing things it shouldn't. - Assuming the routes don't conflict. Code written for the old
ServeMuxchanges meaning when upgraded to Go 1.22; if some code depends on the old behaviour, you can temporarily restore it withGODEBUG=httpmuxgo121=1, but you should rewrite it as soon as possible. When two patterns overlap and neither is more specific, registration panics. - Putting middleware in the wrong order. With the logging layer inside the recovery layer, panicking requests aren't logged; with the authentication layer outside RequestID, rejected requests have no ID to look up.
- Wrapping ResponseWriter without providing Unwrap. Streaming, SSE and WebSocket suddenly stop working once middleware is added, because type assertions can't find
FlusherorHijacker. - Treating handlers as single-threaded. Every request runs in its own goroutine, so shared maps and counters must be protected;
go test -racecatches this easily. - Passing ordinary parameters through context. Context suits request-scoped data such as the request ID and the authenticated user; the dependencies a handler needs (database, services) should be passed in through struct fields, which the next article explains in detail.
- Going live with
http.ListenAndServedirectly. There are no timeouts at all, so it's easily dragged down by slow connections. - Trusting the request ID sent by the client. An
X-Request-IDfrom upstream must be limited in length and characters, or it can be used to flood the logs or for log injection.
Key takeaways
- The core of
net/httpis thehttp.Handlerinterface, andhttp.HandlerFunclets ordinary functions act as handlers; every request runs in its own goroutine. - The order for a response is: set
Header(), callWriteHeader, thenWritethe body; remember toreturnafterhttp.Error. - Since Go 1.22,
ServeMuxsupports patterns likeGET /orders/{id}that combine a method and wildcards; get values withr.PathValue,{path...}consumes the remaining path,{$}marks an exact end, and a matching path with the wrong method gets an automatic 405. - When several patterns match, the most specific wins; when that can't be decided, registration panics, so conflicts surface at startup.
- Middleware is just
func(http.Handler) http.Handler; it can do things before and after calling the next layer, and can short-circuit; passing data inwards relies on context. - Wrap
ResponseWriterto intercept the status code, and provideUnwrapsohttp.ResponseControllercan find the underlying features. - Order matters: the request ID outermost, logging wrapping panic recovery, and authentication inside logging.
- In production, always create your own
http.Serverand setReadHeaderTimeout,ReadTimeout,WriteTimeoutandIdleTimeout; when a handler stops depends onr.Context().
Next
Right now the order service's routing, validation, business rules and data access are all crammed into the same handlers, which makes them hard to test and the storage impossible to swap. “Layered Architecture and Dependency Injection in Go” splits it into three layers, handler, service and repository, and wires the dependencies together with nothing but constructors, without any framework.