在中间件中无法追踪 HTTP 响应代码
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《在中间件中无法追踪 HTTP 响应代码》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
我正在使用 go-openapi 从 swagger 配置生成一个 http 服务器并处理所有处理程序。
我的中间件的架构是 request -> override func -> do http stuff -> 日志响应代码 -> response。
这是我的中间件:
func (pm *prometheusmetrics) httpmiddleware(h http.handler) http.handler {
return http.handlerfunc(func(w http.responsewriter, r *http.request) {
start := time.now()
statusrecoder := &utils.statusrecorder{responsewriter: w, statuscode: 200}
logrus.infof("--> %v %v", r.method, r.url.path)
// statusrecoder := negroni.newresponsewriter(w) <-- tried this solution, didn't worked
h.servehttp(statusrecoder, r)
logrus.infof("<-- %v", statusrecoder.status()) // should display status code
duration := time.since(start)
statuscode := strconv.itoa(statusrecoder.status())
pm.pushhttpmetrics(r.url.path, statuscode, duration.seconds())
})
}
这是我传递中间件的方式:
func setupglobalmiddleware(handler http.handler, prommetrics *apihandlers.prometheusmetrics) http.handler {
middle := interpose.new()
middle.usehandler(handler)
recoverymiddleware := recovr.new()
middle.use(recoverymiddleware)
logrusmiddleware := interposemiddleware.negronilogrus()
middle.use(logrusmiddleware)
middle.use(func(h http.handler) http.handler {
return prommetrics.httpmiddleware(h)
})
corsmiddleware := cors.new(cors.options{
allowedheaders: []string{"*"},
allowedorigins: []string{"*"},
allowedmethods: []string{"get", "post", "put", "patch", "delete", "options"},
maxage: 1000,
optionspassthrough: false,
})
if log.getlevel() >= log.debuglevel {
corsmiddleware.log = log.standardlogger()
}
return corsmiddleware.handler(middle)
}
最后,我调用 setupglobalmiddleware 函数:
func configureapi(api *operations.kubeesapi) http.handler { // operations is package generated by go-openapi
// some setup...
return setupglobalmiddleware(api.serve(setupmiddlewares), prommetrics)
}
statusrecoder 的重写:
type StatusRecorder struct {
http.ResponseWriter
StatusCode int
}
// WriteHeader is the fake function to record status code
func (rec *StatusRecorder) WriteHeader(statusCode int) {
logrus.Infof("hello there: %v", statusCode)
rec.StatusCode = statusCode
rec.ResponseWriter.WriteHeader(statusCode)
}
如您所见,我重写了 http.handler 中的 writeheader 函数,以仅存储状态代码并在外部访问它,然后调用原始 writeheader 函数。这里的问题是我的函数 writeheader 从未被调用。并且无法弄清楚为什么不是。
解决方案
如果您没有完整的软件包列表,那么答案会更难理解。
问题在于 go-openapi 和 go-swagger 在代码中实现中间件并处理它们的方式。许多其他已安装的软件包也存在此问题。
为了确保正确检索状态代码,我将中间件放在中间件声明的右底部。
代码:
func setupglobalmiddleware(handler http.handler, prommetrics *apihandlers.prometheusmetrics) http.handler {
middle := interpose.new()
middle.usehandler(handler)
recoverymiddleware := recovr.new()
middle.use(recoverymiddleware)
logrusmiddleware := interposemiddleware.negronilogrus()
middle.use(logrusmiddleware)
// the old declaration was here
corsmiddleware := cors.new(cors.options{
allowedheaders: []string{"*"},
allowedorigins: []string{"*"},
allowedmethods: []string{"get", "post", "put", "patch", "delete", "options"},
maxage: 1000,
optionspassthrough: false,
})
if log.getlevel() >= log.debuglevel {
corsmiddleware.log = log.standardlogger()
}
// notice the changement where the prommetrics.httpmiddleware is now in the bottom
return corsmiddleware.handler(prommetrics.httpmiddleware(middle))
// return corsmiddleware.handler(middle) <-- old line
}
因为go使用组合,而不是继承。 writeheader 最常在第一次调用 write() 时自动调用。来自http.ResponseWriter documentation:
但由于您尚未定义自己的 write 方法,因此将调用嵌入式方法(由 http.responsewriter 的嵌入式实例提供)。当调用 write() 方法,然后调用 writeheader 时,它会调用原始 writeheader 方法,而不是您的版本。
解决方案是还提供您自己的 write 方法,该方法包装原始方法,并在需要时调用您的 writeheader 版本。
type StatusRecorder struct {
http.ResponseWriter
StatusCode int
written bool
}
// WriteHeader is the fake function to record status code
func (rec *StatusRecorder) WriteHeader(statusCode int) {
rec.written = true
logrus.Infof("hello there: %v", statusCode)
rec.StatusCode = statusCode
rec.ResponseWriter.WriteHeader(statusCode)
}
func (rec *StatusRecorder) Write(p []byte) (int, error) {method
if !rec.written {
rec.WriteHeader(http.StatusOK)
}
return rec.Write(p)
}
以上就是《在中间件中无法追踪 HTTP 响应代码》的详细内容,更多关于的资料请关注golang学习网公众号!
golang中的嵌套结构不会被编码为http响应
- 上一篇
- golang中的嵌套结构不会被编码为http响应
- 下一篇
- 在Go中使用递归和迭代处理结构体数组
-
- Golang · Go问答 | 7分钟前 |
- Go tar 解包后文件权限异常怎样还原
- 200浏览 收藏
-
- Golang · Go问答 | 9分钟前 | 错误处理 · go · Go gzip Writer.Close gzip 尾部 Go 压缩文件 Flush Close 区别
- Go gzip Writer Close 为什么必须调用
- 374浏览 收藏
-
- Golang · Go问答 | 12分钟前 |
- Go template 执行成功但页面内容为空怎么办
- 197浏览 收藏
-
- Golang · Go问答 | 12分钟前 |
- Go bufio.Writer 写入成功但文件没有内容怎么办
- 430浏览 收藏
-
- Golang · Go问答 | 17分钟前 |
- Go 自定义 MarshalJSON 为什么递归调用自己
- 169浏览 收藏
-
- Golang · Go问答 | 20分钟前 |
- Go reflect.Value IsNil 为什么会 panic
- 216浏览 收藏
-
- Golang · Go问答 | 22分钟前 |
- Go interface 比较为什么触发不可比较类型 panic
- 136浏览 收藏
-
- Golang · Go问答 | 45分钟前 |
- Go map 清空后内存为什么没有立即下降
- 343浏览 收藏
-
- Golang · Go问答 | 45分钟前 |
- Go slice 截取后大数组为什么仍被保留
- 424浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 465次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 528次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 545次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 495次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 316次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go crypto/rand.Text 的长度为什么不是固定字符数
- 2026-10-04 501浏览
-
- Go strings.ToValidUTF8 清洗日志内容的边界
- 2026-10-03 501浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览

