How to Chain Multiple Middleware in Go

Web
Chain Go middleware by wrapping handlers sequentially using a helper function that iterates through the middleware list in reverse order.

Chain multiple middleware in Go by wrapping handlers sequentially, where each middleware calls the next in the chain before or after its logic.

func chainMiddleware(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        for i := len(middlewares) - 1; i >= 0; i-- {
            next = middlewares[i](next)
        }
        return next
    }
}

// Usage:
// handler := chainMiddleware(mw1, mw2, mw3)(http.HandlerFunc(myHandler))