Go语言通过高阶函数和闭包实现装饰器模式,可在不修改原函数的前提下为其添加日志、权限校验、超时控制等功能。1. 使用func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc为HTTP处理函数添加日志;2. 通过链式调用组合多个装饰器,如loggingMiddleware(authMiddleware(timeoutMiddleware(handler))));3. 可扩展至普通函数,如timeIt统计执行时间。关键在于函数作为一等公民传递,结合闭包封装逻辑,注意上下文传递与错误处理。

在Go语言中,虽然没有像Python那样的装饰器语法糖,但可以通过函数式编程和高阶函数的方式实现装饰器模式。装饰器模式的核心是在不修改原始函数逻辑的前提下,为其增加额外功能,比如日志记录、权限校验、耗时统计等。
Go中的函数是一等公民,可以作为参数传递或返回值。利用这一点,我们可以定义一个返回函数的函数,即“装饰器”。
例如,为一个HTTP处理函数添加日志功能:
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("Received request: %s %s", r.Method, r.URL.Path)
next(w, r)
log.Printf("Completed request: %s %s", r.Method, r.URL.Path)
}
}使用方式:
立即学习“go语言免费学习笔记(深入)”;
http.HandleFunc("/hello", loggingMiddleware(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}))多个装饰器可以层层嵌套,形成调用链。例如,添加超时控制和身份验证:
本文档主要讲述的是在Android-Studio中导入Vitamio框架;介绍了如何将Vitamio框架以Module的形式添加到自己的项目中使用,这个方法也适合导入其他模块实现步骤。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
0
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next(w, r)
}
}
<p>func timeoutMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r <em>http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5</em>time.Second)
defer cancel()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;"> done := make(chan bool, 1)
go func() {
next(w, r.WithContext(ctx))
done <- true
}()
select {
case <-done:
case <-ctx.Done():
http.Error(w, "Request timeout", http.StatusGatewayTimeout)
}
}}
组合使用:
handler := loggingMiddleware(authMiddleware(timeoutMiddleware(helloHandler)))
http.HandleFunc("/hello", handler)不仅限于HTTP处理函数,也可以为普通函数写装饰器。比如统计函数执行时间:
func timeIt(fn func(int) int) func(int) int {
return func(n int) int {
start := time.Now()
result := fn(n)
log.Printf("Function took %v\n", time.Since(start))
return result
}
}使用示例:
slowFunc := timeIt(func(n int) int {
time.Sleep(2 * time.Second)
return n * 2
})
<p>slowFunc(5) // 输出耗时信息基本上就这些。Go通过高阶函数和闭包天然支持装饰器模式,关键是理解函数类型匹配和中间逻辑的封装方式。不复杂但容易忽略细节,比如上下文传递和错误处理。
以上就是如何在Golang中实现装饰器模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号