Chain Of Responsibility Pattern You Should Know in Golang(Design Patterns 06)

Unlock the Power of Responsibility: Discover how Go’s Chain of Responsibility pattern can simplify complex request handling scenarios.

golang golang-chain-of-responsibility-pattern(from github.com/MariaLetta/free-gophers-pack)|300

Hello, here is Wesley, Today’s article is about chain of responsibility pattern in Go. Without further ado, let’s get started.💪

Chain of Responsibility Pattern

The Chain of Responsibility pattern is a behavioral design pattern that allows requests to be passed along a chain of handlers, where each handler can process the request or pass it on to the next one.

Background

In real-world development, we often encounter scenarios where requests need to be processed at different levels. For example, a logging system may need to dispatch logs based on log levels, or an access control system may need to verify permissions level by level.

By using the Chain of Responsibility pattern, we can avoid hardcoding multiple if-else or switch logic and separate responsibilities into different handlers, enhancing code readability and extensibility.

Go is a language that emphasizes simplicity and efficiency. Its interfaces, composition, and functional programming features make it well-suited for implementing the Chain of Responsibility pattern. Unlike Java-like languages with complex inheritance mechanisms, Go tends to use interface composition and function chaining to implement flexible responsibility chains.

Design Idea

We will design a dynamic chain of responsibility that allows each handler to:

  1. Process requests.
  2. Decide whether to pass the request on to the next handler.

In Go’s implementation, we will use two methods:

  1. Interface Implementation: Define a handler interface to build the chain of responsibility.
  2. Functional Implementation: Use Go’s function types and closures to implement chained calls.

Example: Implementing a Simple Log Processing System

Requirements: Handle logs based on their level (Info, Warning, Error) using different handlers.

Run Results:

1
2
3
[INFO] This is an info log.
[WARNING] This is a warning log.
[ERROR] This is an error log.

Functional Implementation

Which implementation is more characteristic of Go?

  • Interface Implementation: More suitable for handling complex responsibility chain scenarios, allowing for easier extension and implementation of more behaviors.
  • Functional Implementation: More concise, using Go’s functional programming features to quickly implement lightweight responsibility chains.

Applicable Scenarios

We can see from the concept that the Chain of Responsibility pattern has the following obvious advantages:

  • Decoupling by role: Unlocks
  • Object chain: Logic is clear

Applicable scenarios:

  • *Multiple objects can handle a request: When it’s unclear which object will handle the request, you can use the Chain of Responsibility pattern.
  • Dynamically specify a group of objects to handle requests: You can add or modify handlers in the chain as needed
  • Decouple request senders from receivers: The sender doesn’t need to know which specific object will handle the request, reducing system coupling.

Some concrete scenarios include:

  1. Log processing: Handle logs based on their level (Info, Warning, Error).
  2. Permission verification: Verify user operation permissions level by level based on roles and permissions.
  3. Request filtering: Filter requests in a web framework, intercepting and handling them at different levels.

Standard Library Implementation

In Go’s net/http standard library, you can implement the Chain of Responsibility pattern when handling HTTP requests by using multiple middleware layers.

Each middleware (such as LoggingMiddleware and AuthMiddleware) acts as a “handling node”, allowing it to choose whether to process the request or pass it on to the next middleware.

Summary

The Chain of Responsibility pattern can be implemented in Go by fully leveraging its concise interfaces and functional features, making code more clear and efficient. It is particularly effective in scenarios where you need to dynamically specify a group of objects to handle requests, such as in middleware, event handling, and request dispatching applications.

More

Recent Articles:

Random Article:


More Series Articles about You Should Know In Golang:

https://wesley-wei.medium.com/list/you-should-know-in-golang-e9491363cd9a

And I’m Wesley, delighted to share knowledge from the world of programming. 

Don’t forget to follow me for more informative content, or feel free to share this with others who may also find it beneficial. it would be a great help to me.

Give me some free applauds, highlights, or replies, and I’ll pay attention to those reactions, which will determine whether or not I continue to post this type of article.

See you in the next article. 👋

中文文章: https://programmerscareer.com/zh-cn/golang-chain-of-responsibility-pattern/
Author: Medium,LinkedIn,Twitter
Note: Originally written at https://programmerscareer.com/golang-chain-of-responsibility-pattern/ at 2024-12-10 00:50.
Copyright: BY-NC-ND 3.0

Reference

An Easy Guide to Learn Chain of Responsibility in Golang | by Leonard Yeo | Level Up Coding
Golang Pattern: Chain of Responsibility | by Achmad Rizki Nur Fauzie | Medium

Goroutine Collaboration You Should Know In Golang Object Pool Pattern You Should Know in Golang(Design Patterns 05)

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×