Logging middleware wrapping an http.Handler in Go
WHAT IT TESTS: the http.Handler middleware pattern. OUTLINE: middleware has signature func(http.Handler) http.Handler, records start time, calls next.ServeHTTP, then logs method, URL, and elapsed duration; chaining works because the wrapper is itself a…
WHAT IT TESTS: understanding Go's decorator-style middleware. ANSWER OUTLINE: define func Logging(next http.Handler) http.Handler returning http.HandlerFunc. Inside, capture start := time.Now(), call next.ServeHTTP(w, r) to run the wrapped handler, then log r.Method, r.URL, and time.Since(start). Because the returned value satisfies http.Handler, middlewares compose: Logging(Auth(mux)). RED FLAG: a signature that does not take and return http.Handler, which prevents chaining.
Read the original → interview
- #go
- #middleware
- #http
- #logging
- #handlers
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.