Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Home/Go/Design patterns/Chain of Responsibility
Go

Go

Simple, fast to compile, built for concurrent network services.

Paradigm
Procedural, composition over inheritance
Typing
Static, strong, structural interfaces
Memory
Concurrent low-latency GC
Runs
Single static native binary
Concurrency
Goroutines and channels
Behavioral pattern

Chain of Responsibility

Intent

Passes a request along a chain of handlers; each decides to process it or pass it on.

Problem

Request checks (auth, validation, rate limits, caching) pile up in one huge method.

Solution

Turn each check into a handler linked to the next one; HTTP middleware is the everyday example.

Real-world analogy

Think of it like this

Calling tech support: the voice menu, then an operator, then an engineer. Each one solves the problem or escalates it.

Structure

association / extends implements / depends on
Client 4 «interface» Handler + setNext(h: Handler)+ handle(request) 1 BaseHandler - next: Handler+ handle(request) 2 ConcreteHandlers + handle(request) 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Handler — Handler declares the interface common to all handlers.
  2. 2BaseHandler — Base Handler (optional) stores the next handler and forwards by default.
  3. 3ConcreteHandlers — Concrete Handlers decide whether to process a request and whether to pass it on.
  4. 4Client — Client composes the chain once or dynamically, and sends requests to any handler.

Code example

A Go code sample for Chain of Responsibility is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Chain of Responsibility when different requests need different processing in unknown order.

Use Chain of Responsibility when handlers must run in a particular order.

Use Chain of Responsibility when the set of handlers changes at runtime.

Pros and cons

Pros

  • Control order of handling
  • Single Responsibility and Open–Closed

Cons

  • Some requests may end unhandled

Relations with other patterns

Check yourself

Check yourself

An HTTP request must pass authentication, rate limiting and validation, and each step can stop it.

Saved in this browser only. Part of Behavioral patterns (0/11).