All PatternsBehavioral
Chain of Responsibility
Passes requests along a chain of handlers.
Middleware chainsEvent handlingApproval workflows
Understanding Chain of Responsibility
The Chain of Responsibility pattern links a chain of handler objects, where each handler either processes a request or passes it to the next handler in the chain. This decouples the sender of a request from its receivers, allowing multiple objects a chance to handle it. In Go, each handler implements a common interface and holds a reference to the next handler. This pattern is the foundation of HTTP middleware pipelines in frameworks like Chi and Echo, where each middleware can process a request, modify it, or pass it along.
Key Concepts
- •Handler interface — each handler implements the same interface with a method to process or delegate requests
- •Next reference — each handler holds a pointer to the next handler, forming a linked chain
- •Short-circuiting — a handler can choose to handle the request and stop the chain, or pass to the next handler
- •Dynamic assembly — the chain can be configured at runtime by linking handlers in different orders
When to Use
✅ Use when
- • Multiple objects may handle a request and the handler isn\'t known in advance
- • You want to assemble processing pipelines dynamically
- • You\'re building middleware chains (HTTP, logging, validation)
- • Processing should continue until one handler can deal with the request
⚠️ Avoid when
- • Every request must be handled — an unhandled request falling off the chain is a bug
- • The chain is always the same and a simple function call sequence would be clearer
- • Performance is critical and the chain traversal adds measurable overhead
Structure
Client
↓ sends request
Handler A → Handler B → Handler C
↓ each may handle or pass
Process or Forward
How It Works
Request
Handler1
handles < 10
Handler2
handles < 20
Handler3
handles all
Request enters chain
1
Request Arrives
A request enters the chain.
1 / 4
Basic Implementation
Request handlers based on value size:
main.go
Loading editor...
Real-World Example: Logging System
Multi-level logging with console, file, and alerts:
main.go
Loading editor...