Add middleware in Go web servers

Add middleware in Go by wrapping your http.Handler with a function that executes logic before passing the request to the next handler.

Add middleware to a Go web server by wrapping your handler with a function that executes before or after the request reaches your main logic.

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, World"))
    })
    http.ListenAndServe(":8080", loggingMiddleware(mux))
}