Skip to content
GDP for Noobs
☰ All patterns
BehavioralAdvanced

Chain of Responsibility

Pass a request along a chain until someone handles or rejects it.

01

Explain it like I'm new

Real-life analogy

Airport security

Ticket check → passport control → bag scan → gate. Each checkpoint can stop you or wave you on to the next one.

😩 The problem

Each request needs auth, rate limiting and validation. One giant function doing all three is hard to reorder, reuse or test.

💡 The pattern

Each check is a handler with a link to the next one. A handler either stops with an error or passes the request on.

02

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import (
4 "errors"
5 "fmt"
6)
7
8type Request struct {
9 User string
10 Token string
11 Body string
12}
13
14// Handler is one link in the chain.
15type Handler interface {
16 SetNext(h Handler) Handler
17 Handle(r Request) error
18}
19
20// BaseHandler holds the "next" link. Others embed it to get SetNext for free.
21type BaseHandler struct{ next Handler }
22
23func (b *BaseHandler) SetNext(h Handler) Handler { b.next = h; return h }
24func (b *BaseHandler) passOn(r Request) error {
25 if b.next == nil {
26 return nil
27 }
28 return b.next.Handle(r)
29}
30
31type AuthCheck struct{ BaseHandler }
32
33func (a *AuthCheck) Handle(r Request) error {
34 if r.Token != "secret" {
35 return errors.New("auth: invalid token") // stop the chain here
36 }
37 fmt.Println(" auth ok")
38 return a.passOn(r) // let the next handler have a go
39}
40
41type RateLimit struct {
42 BaseHandler
43 seen map[string]int
44 max int
45}
46
47func (rl *RateLimit) Handle(r Request) error {
48 rl.seen[r.User]++
49 if rl.seen[r.User] > rl.max {
50 return fmt.Errorf("rate limit: %s made too many requests", r.User)
51 }
52 fmt.Println(" rate limit ok")
53 return rl.passOn(r)
54}
55
56type Validate struct{ BaseHandler }
57
58func (v *Validate) Handle(r Request) error {
59 if r.Body == "" {
60 return errors.New("validate: empty body")
61 }
62 fmt.Println(" body ok")
63 return v.passOn(r)
64}
65
66func main() {
67 chain := &AuthCheck{}
68 chain.SetNext(&RateLimit{seen: map[string]int{}, max: 2}).SetNext(&Validate{})
69
70 requests := []Request{
71 {"ana", "secret", "hi"},
72 {"bob", "wrong", "hi"},
73 {"ana", "secret", ""},
74 {"ana", "secret", "again"},
75 }
76 for i, r := range requests {
77 fmt.Printf("request %d from %s:\n", i+1, r.User)
78 if err := chain.Handle(r); err != nil {
79 fmt.Println(" REJECTED ->", err)
80 } else {
81 fmt.Println(" ACCEPTED")
82 }
83 }
84}
terminal
Press ▶ Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

03

When should I use it?

✅ Reach for it when…

  • •Middleware, validation pipelines, approval workflows, event handling with fallbacks.

🚫 Skip it when…

  • •The order of checks never changes and there are only one or two. Inline them.

🐹 Go tip

Struct embedding (struct{ BaseHandler }) is Go's way of sharing code. It's composition, not inheritance.

🌍 You've already seen it in

HTTP middleware stacks in chi, echo and gin, and gRPC interceptor chains.

04

Quick check

One question. No pressure.

Request 2 has a wrong token. Which handlers run?

Related: Decorator, Pipeline