Padrão Pipeline em Go


Combinar o padrão Pipeline com o Chain of Responsibility deixa o fluxo de dados intuitivo: cada etapa (stage) processa a entrada, decide se continua e delega para a próxima. Esse formato é perfeito para pipelines de validação, processamento de pedidos, middlewares e qualquer fluxo onde cada passo tem responsabilidade clara.
Pipeline de processamento de pedidos com três etapas:
Cada etapa é um stage encadeado. Se alguma falhar, o fluxo é interrompido.
package main import ( "context" "errors" "fmt" "time" ) type Order struct { ID int Product string Quantity int } type Invoice struct { OrderID int Total float64 } // Stage define o contrato de cada etapa da pipeline. // SetNext encadeia o próximo stage; Execute processa o pedido. type Stage interface { SetNext(Stage) Stage Execute(context.Context, Order) (Order, error) } // BaseStage concentra a lógica comum de encadeamento. type BaseStage struct { next Stage } func (b *BaseStage) SetNext(next Stage) Stage { b.next = next return next } func (b *BaseStage) callNext(ctx context.Context, order Order) (Order, error) { if b.next == nil { return order, nil } return b.next.Execute(ctx, order) } // Stage 1: valida campos obrigatórios. type ValidationStage struct { BaseStage } func (s *ValidationStage) Execute(ctx context.Context, order Order) (Order, error) { if order.Product == "" || order.Quantity <= 0 { return order, fmt.Errorf("pedido #%d inválido", order.ID) } fmt.Printf("🔍 Pedido #%d validado\n", order.ID) return s.callNext(ctx, order) } // Stage 2: reserva estoque (simulado em memória). type StockStage struct { BaseStage stock map[string]int } func (s *StockStage) Execute(ctx context.Context, order Order) (Order, error) { available := s.stock[order.Product] if available < order.Quantity { return order, fmt.Errorf("estoque insuficiente para %s (pedido #%d)", order.Product, order.ID) } s.stock[order.Product] -= order.Quantity fmt.Printf("📦 Estoque reservado para pedido #%d\n", order.ID) return s.callNext(ctx, order) } // Stage 3: emite nota fiscal fictícia e envia via canal. type InvoiceStage struct { BaseStage invoices chan Invoice } func (s *InvoiceStage) Execute(ctx context.Context, order Order) (Order, error) { total := float64(order.Quantity) * 99.90 invoice := Invoice{OrderID: order.ID, Total: total} select { case <-ctx.Done(): return order, ctx.Err() case s.invoices <- invoice: fmt.Printf("🧾 Nota emitida para pedido #%d (R$ %.2f)\n", order.ID, total) } return s.callNext(ctx, order) } func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() invoices := make(chan Invoice, 10) go func() { for inv := range invoices { fmt.Printf("✅ Pedido #%d finalizado (Total R$ %.2f)\n", inv.OrderID, inv.Total) } }() // Montagem do pipeline: Validação -> Estoque -> Nota. validation := &ValidationStage{} stock := &StockStage{stock: map[string]int{"Notebook": 5, "Mouse": 1}} invoice := &InvoiceStage{invoices: invoices} validation.SetNext(stock).SetNext(invoice) orders := []Order{ {ID: 1, Product: "Notebook", Quantity: 2}, {ID: 2, Product: "Mouse", Quantity: 2}, // estoque insuficiente {ID: 3, Product: "Teclado", Quantity: 1}, // produto desconhecido } for _, order := range orders { if _, err := validation.Execute(ctx, order); err != nil && !errors.Is(err, context.Canceled) { fmt.Println("Erro:", err) } } close(invoices) }
🔍 Pedido #1 validado
📦 Estoque reservado para pedido #1
🧾 Nota emitida para pedido #1 (R$ 199.80)
✅ Pedido #1 finalizado (Total R$ 199.80)
🔍 Pedido #2 validado
Erro: estoque insuficiente para Mouse (pedido #2)
Erro: pedido #3 inválido
Tratar a pipeline como uma cadeia de handlers deixa o fluxo transparente e flexível. Cada stage decide se continua ou interrompe, e trocar a ordem é questão de reencadeamento. Em Go, essa abordagem encaixa perfeitamente com a linguagem e ajuda a manter o código limpo, modular e intuitivo.
Combining the Pipeline pattern with Chain of Responsibility makes the data flow intuitive: each stage processes the input, decides whether to continue, and delegates to the next stage. This setup is perfect for validation pipelines, order processing, middlewares, or any flow where each step has a clear responsibility.
We’ll process orders through three stages:
Each stage is chained. If one fails, the flow stops.
package main import ( "context" "errors" "fmt" "time" ) type Order struct { ID int Product string Quantity int } type Invoice struct { OrderID int Total float64 } // Stage defines the contract for each pipeline step. // SetNext chains the next stage; Execute processes the order. type Stage interface { SetNext(Stage) Stage Execute(context.Context, Order) (Order, error) } // BaseStage centralizes the chaining logic. type BaseStage struct { next Stage } func (b *BaseStage) SetNext(next Stage) Stage { b.next = next return next } func (b *BaseStage) callNext(ctx context.Context, order Order) (Order, error) { if b.next == nil { return order, nil } return b.next.Execute(ctx, order) } // Stage 1: validate required fields. type ValidationStage struct { BaseStage } func (s *ValidationStage) Execute(ctx context.Context, order Order) (Order, error) { if order.Product == "" || order.Quantity <= 0 { return order, fmt.Errorf("order #%d is invalid", order.ID) } fmt.Printf("🔍 Order #%d validated\n", order.ID) return s.callNext(ctx, order) } // Stage 2: simulate stock reservation (in-memory). type StockStage struct { BaseStage stock map[string]int } func (s *StockStage) Execute(ctx context.Context, order Order) (Order, error) { available := s.stock[order.Product] if available < order.Quantity { return order, fmt.Errorf("insufficient stock for %s (order #%d)", order.Product, order.ID) } s.stock[order.Product] -= order.Quantity fmt.Printf("📦 Stock reserved for order #%d\n", order.ID) return s.callNext(ctx, order) } // Stage 3: emit a mock invoice and send it through a channel. type InvoiceStage struct { BaseStage invoices chan Invoice } func (s *InvoiceStage) Execute(ctx context.Context, order Order) (Order, error) { total := float64(order.Quantity) * 99.90 invoice := Invoice{OrderID: order.ID, Total: total} select { case <-ctx.Done(): return order, ctx.Err() case s.invoices <- invoice: fmt.Printf("🧾 Invoice issued for order #%d ($ %.2f)\n", order.ID, total) } return s.callNext(ctx, order) } func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() invoices := make(chan Invoice, 10) go func() { for inv := range invoices { fmt.Printf("✅ Order #%d completed (Total $ %.2f)\n", inv.OrderID, inv.Total) } }() // Assemble the pipeline: Validation -> Stock -> Invoice. validation := &ValidationStage{} stock := &StockStage{stock: map[string]int{"Laptop": 5, "Mouse": 1}} invoice := &InvoiceStage{invoices: invoices} validation.SetNext(stock).SetNext(invoice) orders := []Order{ {ID: 1, Product: "Laptop", Quantity: 2}, {ID: 2, Product: "Mouse", Quantity: 2}, // insufficient stock {ID: 3, Product: "Keyboard", Quantity: 1}, // product not configured } for _, order := range orders { if _, err := validation.Execute(ctx, order); err != nil && !errors.Is(err, context.Canceled) { fmt.Println("Error:", err) } } close(invoices) }
🔍 Order #1 validated
📦 Stock reserved for order #1
🧾 Invoice issued for order #1 ($ 199.80)
✅ Order #1 completed (Total $ 199.80)
🔍 Order #2 validated
Error: insufficient stock for Mouse (order #2)
Error: order #3 is invalid
Treating the pipeline as a chain of handlers keeps the flow transparent and flexible. Each stage decides to continue or halt, and rearranging the order is just a matter of re-chaining. In Go, this approach aligns perfectly with the language’s simplicity and helps maintain clean, modular, and intuitive code.