How to Implement the Middleware Pattern in Go

Implement Go middleware by defining a function that wraps http.Handler to execute logic before and after the core request handler.

Implement the middleware pattern in Go by defining a function type that wraps http.Handler and chaining functions that modify the request or response before passing control to the next handler.

package main

import (
	"log"
	"net/http"
)

// Middleware is a function that wraps an http.Handler
func Middleware(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Pre-processing logic
		log.Println("Before request")
		
		// Call the next handler in the chain
		handler.ServeHTTP(w, r)
		
		// Post-processing logic
		log.Println("After request")
	})
}

func main() {
	// Define your base handler
	baseHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World!"))
	})

	// Wrap the handler with middleware
	finalHandler := Middleware(baseHandler)

	// Start the server
	log.Fatal(http.ListenAndServe(":8080", finalHandler))
}