Chain of Responsibility em Go


O Chain of Responsibility (CoR) é um padrão comportamental que permite passar uma solicitação ao longo de uma cadeia de handlers. Cada handler decide se processa a mensagem ou se delega ao próximo, evitando condicionais gigantes, promovendo desacoplamento e facilitando a extensão do fluxo.
SetNext e Handle.package main import ( "fmt" "strings" ) type Request struct { User string Authenticated bool Payload string } type Handler interface { SetNext(Handler) Handler Handle(*Request) error } type BaseHandler struct { next Handler } func (b *BaseHandler) SetNext(next Handler) Handler { b.next = next return next } func (b *BaseHandler) callNext(req *Request) error { if b.next == nil { return nil } return b.next.Handle(req) } type AuthHandler struct { BaseHandler } func (h *AuthHandler) Handle(req *Request) error { if !req.Authenticated { return fmt.Errorf("usuário %s não autenticado", req.User) } fmt.Println("✅ Autenticação ok para", req.User) return h.callNext(req) } type PayloadHandler struct { BaseHandler } func (h *PayloadHandler) Handle(req *Request) error { if strings.TrimSpace(req.Payload) == "" { return fmt.Errorf("payload vazio") } fmt.Println("✅ Payload válido:", req.Payload) return h.callNext(req) } type BusinessHandler struct { BaseHandler } func (h *BusinessHandler) Handle(req *Request) error { fmt.Println("🚀 Executando lógica de negócio para", req.User) return h.callNext(req) } func main() { auth := &AuthHandler{} payload := &PayloadHandler{} business := &BusinessHandler{} auth.SetNext(payload).SetNext(business) req1 := &Request{User: "Alice", Authenticated: true, Payload: "dados"} if err := auth.Handle(req1); err != nil { fmt.Println("Erro:", err) } fmt.Println("---") req2 := &Request{User: "Bob", Authenticated: false, Payload: "teste"} if err := auth.Handle(req2); err != nil { fmt.Println("Erro:", err) } }
✅ Autenticação ok para Alice
✅ Payload válido: dados
🚀 Executando lógica de negócio para Alice
---
Erro: usuário Bob não autenticado
O Chain of Responsibility oferece um caminho limpo para construir pipelines flexíveis: defina o contrato, implemente handlers específicos e encadeie. Em Go, o padrão se traduz em código simples, expressivo e alinhado à filosofia da linguagem para middlewares, validações, transformações e fluxos condicionais.
The Chain of Responsibility (CoR) is a behavioral pattern that allows passing a request along a chain of handlers. Each handler decides whether to process the message or delegate it to the next one, avoiding giant conditionals, promoting decoupling, and facilitating flow extension.
SetNext and Handle.package main import ( "fmt" "strings" ) type Request struct { User string Authenticated bool Payload string } type Handler interface { SetNext(Handler) Handler Handle(*Request) error } type BaseHandler struct { next Handler } func (b *BaseHandler) SetNext(next Handler) Handler { b.next = next return next } func (b *BaseHandler) callNext(req *Request) error { if b.next == nil { return nil } return b.next.Handle(req) } type AuthHandler struct { BaseHandler } func (h *AuthHandler) Handle(req *Request) error { if !req.Authenticated { return fmt.Errorf("user %s not authenticated", req.User) } fmt.Println("✅ Authentication ok for", req.User) return h.callNext(req) } type PayloadHandler struct { BaseHandler } func (h *PayloadHandler) Handle(req *Request) error { if strings.TrimSpace(req.Payload) == "" { return fmt.Errorf("empty payload") } fmt.Println("✅ Valid payload:", req.Payload) return h.callNext(req) } type BusinessHandler struct { BaseHandler } func (h *BusinessHandler) Handle(req *Request) error { fmt.Println("🚀 Executing business logic for", req.User) return h.callNext(req) } func main() { auth := &AuthHandler{} payload := &PayloadHandler{} business := &BusinessHandler{} auth.SetNext(payload).SetNext(business) req1 := &Request{User: "Alice", Authenticated: true, Payload: "data"} if err := auth.Handle(req1); err != nil { fmt.Println("Error:", err) } fmt.Println("---") req2 := &Request{User: "Bob", Authenticated: false, Payload: "test"} if err := auth.Handle(req2); err != nil { fmt.Println("Error:", err) } }
✅ Authentication ok for Alice
✅ Valid payload: data
🚀 Executing business logic for Alice
---
Error: user Bob not authenticated
The Chain of Responsibility offers a clean path to build flexible pipelines: define the contract, implement specific handlers, and chain them. In Go, the pattern translates into simple, expressive code aligned with the language's philosophy for middlewares, validations, transformations, and conditional flows.