HTTP Middleware Request Logging

Log HTTP requests with a middleware including method path status and duration.

GoCli Tooling

Code

gosnippet
15 lines
package main
import ("net/http";"time";"log")
type statusWriter struct {
    http.ResponseWriter
    status int
}
func (w *statusWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) }
func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        sw := &statusWriter{ResponseWriter: w, status: 200}
        next.ServeHTTP(sw, r)
        log.Printf("%s %s %d %v", r.Method, r.URL.Path, sw.status, time.Since(start))
    })
}

What the code does

HTTP Middleware Request Logging is built around the functions WriteHeader and LoggingMiddleware.

Applying it

Entry signature: func (w *statusWriter) WriteHeader(code int)

This is a method, not a free function — dispatch happens via a statusWriter value.

Statements that matter

func (w *statusWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(sw, r)
log.Printf("%s %s %d %v", r.Method, r.URL.Path, sw.status, time.Since(start))
})

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `WriteHeader`, `LoggingMiddleware` at load time.