Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
137: Middleware Patterns in net/http
You've already built basic handlers in net/http, but as your app grows, you'll find yourself repeating the same logic—like logging requests, checking authentication, or recovering from panics—across every single endpoint. Copy-pasting that code is a nightmare to maintain. This is where middleware comes in.
Think of middleware as a wrapper. You're taking an existing http.Handler and wrapping it in another function that can execute code both before and after the actual handler runs. In Go, the idiomatic pattern for this is a function that takes an http.Handler and returns a new http.Handler.
Defining the core logic
Let's build a small API that serves a "Secret Dashboard." First, I'll start with the actual destination—the handler that does the real work. I'm keeping this simple so we can focus on the wrapping logic.
package main
import (
"fmt"
"log"
"net/http"
)
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome to the secret dashboard!")
}
Adding a logging wrapper
I want to know every time someone hits my server, regardless of which endpoint they use. Instead of adding a log.Printf inside every handler, I'll create a middleware function. Notice the signature: it returns a http.HandlerFunc, which satisfies the http.Handler interface.
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request received: %s %s", r.Method, r.URL.Path)
// Now we pass the request along to the next handler in the chain
next.ServeHTTP(w, r)
})
}
By calling next.ServeHTTP(w, r), we're effectively saying, "I'm done with my pre-processing; now let the next person in line have a turn."
Creating a security gate (and a common slip-up)
Now, I want to protect the dashboard. Only requests with a specific API key in the header should get through. I'll write a authMiddleware to handle this.
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
apiKey := r.Header.Get("X-API-KEY")
if apiKey != "super-secret-token" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
// I'm making a mistake here on purpose.
// I forgot to return after the error!
}
next.ServeHTTP(w, r)
})
}
If I ran this as-is, I'd run into a bug. http.Error sends a response to the client, but it doesn't stop the execution of the function. Without a return statement, the code will continue and call next.ServeHTTP(w, r) anyway. The client would get an "Unauthorized" message, but the dashboard handler would still execute on the server, and you'd likely see a "superfluous response.WriteHeader call" warning in your logs. I'll fix that by adding return immediately after the error call.
if apiKey != "super-secret-token" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return // Stop the chain here!
}
Wiring the chain together
Finally, I need to apply these wrappers to my handler. You can nest these calls, though it gets ugly quickly if you have ten of them. For this example, I'll wrap the dashboard handler in auth, and then wrap that whole bundle in the logger.
func main() {
mux := http.NewServeMux()
// Wrap the handler: logger -> auth -> dashboard
finalHandler := loggingMiddleware(authMiddleware(http.HandlerFunc(dashboardHandler)))
mux.Handle("/dashboard", finalHandler)
log.Println("Server starting on :8080...")
log.Fatal(http.ListenAndServe(":8080", mux))
}
Now, every request to /dashboard is first logged, then checked for a key, and only then does it reach the dashboard logic. If the auth check fails, the logger still records the attempt, but the dashboard logic is never touched. This "onion" structure is exactly how most production Go web frameworks handle requests.
📋 Practical Task
Implement a Request Timing Middleware
Modify the server built in this lesson to include a third middleware called timingMiddleware. This middleware should measure how long it takes for the rest of the chain to execute and log the duration.
- The middleware should capture the start time using
time.Now(). - It should call
next.ServeHTTP(w, r). - After the call returns, it should calculate the elapsed time using
time.Since()and log it (e.g., "Request took 15ms"). - Integrate it into the
mainfunction so that it is the outermost layer (it should be the first to start and the last to finish).
There are no comments for now.