How to Use Middleware in Go HTTP Servers

Web
Implement Go HTTP middleware by wrapping http.Handler functions to execute logic before or after the main request handler.

Go does not have built-in middleware; you implement it by wrapping http.Handler functions in a chain. Create a function that takes a handler, returns a new handler, and executes logic before or after calling the original handler.

func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello"))
    })
    handler := LoggingMiddleware(mux)
    http.ListenAndServe(":8080", handler)
}