Skip to Content
Course content

137: Middleware Patterns in net/http

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 main function so that it is the outermost layer (it should be the first to start and the last to finish).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.