责任链模式通过将处理器串联成链使请求依次传递,每个处理器可选择处理或转发请求。Go语言利用函数类型和闭包可轻松实现过滤器链,如HTTP中间件中的日志、认证等逻辑组合;也可通过接口和结构体实现更复杂的自定义责任链,适用于需动态调整处理流程的场景。

在Go语言开发中,责任链模式是一种非常实用的设计模式,特别适合用于构建过滤器链或请求处理流水线。它将请求的发送者和接收者解耦,让多个对象都有机会处理请求,从而实现灵活、可扩展的处理流程。
责任链模式通过将多个处理器串联成一条链,使请求沿着链传递,直到某个处理器处理该请求为止。每个处理器都持有对下一个处理器的引用,可以决定是否处理当前请求,以及是否继续向下传递。
这种结构非常适合以下场景:
在Go中,我们可以利用函数类型和闭包轻松实现一个高性能的过滤器链。常见的做法是定义一个Handler类型,并通过链式调用组织中间件。
立即学习“go语言免费学习笔记(深入)”;
type Handler func(http.Handler) http.Handler
<p>func CreateFilterChain(filters ...Handler) Handler {
return func(https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd http.Handler) http.Handler {
for i := len(filters) - 1; i >= 0; i-- {
https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd = filters<a href="https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd">i</a>
}
return https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd
}
}</p>上面的代码从后往前包装处理器,确保执行顺序符合预期。比如你有日志、认证两个中间件:
logger := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
h.ServeHTTP(w, r)
})
}
<p>auth := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
}</p>然后这样组合使用:
chain := CreateFilterChain(logger, auth)
finalHandler := chain(http.HandlerFunc(yourEndpoint))
http.Handle("/api/", finalHandler)
对于非HTTP场景或者需要更精细控制的情况,可以用结构体方式实现责任链。
type Request struct {
Path string
Header map[string]string
}
<p>type Response struct {
StatusCode int
Body string
}</p><p>type Processor interface {
Sethttps://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd(https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd Processor)
Handle(req <em>Request) </em>Response
}</p><p>type BaseProcessor struct {
https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd Processor
}</p><p>func (b *BaseProcessor) Sethttps://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd(https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd Processor) {
b.https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd = https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd
}</p><p>func (b <em>BaseProcessor) Forward(req </em>Request) *Response {
if b.https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd != nil {
return b.https://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd.Handle(req)
}
return &Response{StatusCode: 200, Body: "OK"}
}</p>具体处理器实现:
type LoggingProcessor struct {
BaseProcessor
}
<p>func (l <em>LoggingProcessor) Handle(req </em>Request) *Response {
log.Printf("Processing request: %s", req.Path)
return l.Forward(req)
}</p><p>type ValidationProcessor struct {
BaseProcessor
}</p><p>func (v <em>ValidationProcessor) Handle(req </em>Request) *Response {
if req.Header["token"] == "" {
return &Response{StatusCode: 401, Body: "Missing token"}
}
return v.Forward(req)
}</p>使用时组装链条:
logging := &LoggingProcessor{}
validation := &ValidationProcessor{}
handler := &BusinessHandler{}
<p>logging.Sethttps://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd(validation)
validation.Sethttps://www.php.cn/link/53e5fee4b79f57668bd8e85742d9f9cd(handler)</p><p>req := &Request{Path: "/data", Header: map[string]string{"token": "abc"}}
resp := logging.Handle(req)</p>在真实项目中使用责任链时,有几个关键点需要注意:
基本上就这些。Go的简洁语法和强大标准库让责任链模式变得非常自然,尤其在Web服务中间件中几乎成了标配。只要设计得当,既能保证灵活性,又不会牺牲可维护性。不复杂但容易忽略的是链的初始化顺序和异常传播方式,建议统一规范团队内的实现风格。
以上就是Golang责任链模式过滤器链与请求处理实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号