Middleware in Go
Start with Middleware in Go
In this lesson, explore middleware in go through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of middleware in go.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Middleware wraps an http.Handler to apply reusable behavior such as logging, authentication, rate limits or request IDs. It runs before and sometimes after calling the next handler.
Order matters: authentication should protect the handler that accesses private data, and response-writing middleware must coordinate when headers are sent.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func withHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Lesson", "Go")
next.ServeHTTP(w, r)
})
}
func main() {
base := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") })
rec := httptest.NewRecorder()
withHeader(base).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Header().Get("X-Lesson"), rec.Body.String())
}
Output
Go okTrace what the program does
withHeader changes the response header before delegating to the wrapped handler, which writes ok.
Avoid common mistakes
- Middleware cannot safely change headers after the downstream handler commits the response.
- Avoid logging secrets from credentials or request bodies.
Try it yourself
Add a middleware that rejects requests without a chosen header before reaching the base handler.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Middleware in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.