Stage 3 · Build
HTTP & REST APIs
Middleware
Request IDs, access logs, panic recovery, CORS, compression, and authentication wrappers.
The Middleware Pattern
Middleware is a function that wraps an http.Handler, adds behavior before or after, and returns a new http.Handler. This is Go's most powerful HTTP abstraction. Logging, auth, rate limiting, and panic recovery all use this pattern.
Request ID
Every request needs a unique identifier for tracing across logs and services. The standard approach is to read an incoming X-Request-ID header or generate a UUID, then store it in the request context.
Access Logging
Access logs record every request with method, path, status code, duration, and client IP. This data is essential for debugging, monitoring, and capacity planning. Structured JSON logs are preferred in production.
Panic Recovery
A panic in a handler kills the goroutine and returns a raw 500 response. Recovery middleware catches panics, logs the stack trace, and returns a clean error response. This is essential for production stability.
Place Recovery as the outermost middleware so it catches panics from all other middleware and handlers. If it is innermost, panics from logging or auth middleware will not be caught.
CORS
Cross-Origin Resource Sharing controls which domains can access your API from a browser. For APIs serving web frontends, you need CORS headers. For server-to-server APIs, you usually skip it.
Authentication Wrapper
Auth middleware validates credentials and stores user identity in the context. Handlers read the user from context without repeating auth logic. This separates authentication from business logic.
Good middleware does one thing well. It reads from the request, writes to the response or context, and calls next. This makes middleware testable with httptest and reusable across different route groups.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.