The middleware concept
- Go course
- Advanced
- Lesson 31/68
- 4 min
Learn the middleware concept and layered structure.
The middleware concept
Middleware is an intermediate layer that runs before and after an HTTP request reaches the real handler. It gathers work that repeats on every route — logging, authentication, compression, timing — in one place.
request → [log] → [auth] → handler
response ← [log] ← [auth] ← handlerIn Go, middleware is simply a function that takes an http.Handler and returns a new http.Handler.
Why middleware?
Copying the same log and permission code to the top of every handler means duplication and the risk of forgetting it. With middleware this code is written once and applied to the routes you choose. Handlers also focus only on their own job, which makes them easier to test.
Practice First middleware
Write func etiket(next http.Handler) http.Handler: it adds the header X-Ders: go to the response and calls next.ServeHTTP(w, r). Test it with httptest and print the header.
Starter code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func etiket(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Ders", "go")
next.ServeHTTP(w, r)
})
}
func main() {
h := etiket(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Header().Get("X-Ders"))
}Expected output
go
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the typical middleware signature in Go?
- func(http.ResponseWriter)
- func() error
- func(*http.Request) bool
- func(http.Handler) http.Handler Correct answer
Explanation: Middleware wraps a handler: it takes one and returns a new handler that adds work around it.
2 The wrapped type
func logla(next http.____) http.Handler {
func logla(next http.Handler) http.Handler {
Explanation: Middleware takes an http.Handler and returns an http.Handler.
3 Middleware uses
| Term | Meaning |
|---|---|
Log |
Records the request |
Auth |
Checks permission |
Recover |
Catches panics |
Gzip |
Compresses the response |