~/Golang Middleware Overview

Mar 14, 2023


Golang middleware is a function or set of functions that wrap around the main http handler to process requests before or after the main logic. In net/http, middleware is commonly used for logging, authentication, or CORS handling.

To make middleware, define a function that takes and returns an http.Handler. Here is a simple logging middleware example:

1
2
3
4
5
6
func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("Request: %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

To use this, wrap your handler:

1
http.Handle("/example", LoggingMiddleware(http.HandlerFunc(ExampleHandler)))

See Go Blog Middleware for more details.

There are middleware frameworks like alice to chain middlewares:

1
2
chain := alice.New(LoggingMiddleware, AuthMiddleware)
http.Handle("/protected", chain.ThenFunc(ProtectedHandler))

Middleware adds reusable logic to multiple endpoints and improves code clarity. For best practices, check the Go standard library docs.

Tags: [golang] [middleware]