๐๐๐ถ๐น๐ฑ๐ถ๐ป๐ด ๐๐ผ ๐ ๐ถ๐ฑ๐ฑ๐น๐ฒ๐๐ฎ๐ฟ๐ฒ ๐๐ฟ๐ผ๐บ ๐ฆ๐ฐ๐ฟ๐ฎ๐๐ฐ๐ต
Every Go web framework uses middleware. Gin and Echo have it. Most tutorials teach you how to use it. Few teach you how it works.
Go HTTP logic relies on one interface: http.Handler.
A middleware is a function. It takes a handler and returns a handler. It wraps the next step in the process. It runs code before or after the main handler.
Manual wrapping is messy. You end up with nested functions. A Chain function fixes this. It takes a slice of middleware. It applies them in the right order.
You build production tools with this pattern:
- Logging: Track method, path, and duration.
- Recovery: Catch panics to stop server crashes.
- Auth: Validate tokens and pass user IDs.
- Timeout: Cancel requests taking too long.
This pattern is not magic. It is a series of nested function calls.
You do not always need a framework. The standard library handles most API needs.
Source: https://dev.to/shayan_holakouee/building-a-nethttp-middleware-chain-from-scratch-in-go-346b