英文:
Determining if TimeoutHandler has timed out
问题
我正在使用http.TimeoutHandler
来向客户端返回超时错误。这个功能正常工作,但问题是,如果超时被触发,我想调用一些代码。我查看了文档和源代码,但找不到一个好的方法来实现这个。响应只是返回给客户端,我找不到一种方法来检查上下文或ResponseWriter等。
调用代码无法访问上下文,所以我无法检查它。实际上,http.ResponseWriter
在http.TimeoutHandler
中写入的结构体确实包含了我需要的信息(它是http.timeoutWriter
),但我无法访问它,因为http.ResponseWriter
接口不支持访问这些变量。
我对Go并不是非常熟悉,但我觉得我可能需要重新实现自己的http.TimeoutHandler
,因为我找不到实现我所需功能的方法。
我有遗漏了什么吗?
英文:
I'm using http.TimeoutHandler
to return a timeout to the client. This works fine, the problem is that I'm trying to call some code if the timeout has been triggered. I've looked through the docs and the source code, and I can't find a good way of doing this. The response just goes back to the client and I can't find a way to do any introspection on the context or the ResponseWriter etc.
The calling code doesn't have access to the context, so I can't inspect it. The actual struct that the http.ResponseWriter
is writing to within http.TimeoutHandler
does put the information in that I need (it's the http.timeoutWriter
), but I can't access it because the http.ResponseWriter
interface doesn't support accessing those variables.
I'm not overly experience in Go, but I can't help but think that I'm just going to have to re-implement my own http.TimeoutHandler
because I can't see a way to do what I need to.
Have I missed something?
答案1
得分: 1
从TimeoutHandler
的源代码中可以看出,它将请求中的上下文设置为具有超时的上下文。这意味着,在您的处理程序中,您可以使用上下文来查看是否发生了超时:
func MyHandler(w http.ResponseWriter,r *http.Request) {
...
if r.Context().Err()==context.DeadlineExceeded {
// 发生了超时
}
}
英文:
As you can see from the source for TimeoutHandler
, it sets the context in the request to a context with timeout. That means, in your handler you can use the context to see if timeout happened:
func MyHandler(w http.ResponseWriter,r *http.Request) {
...
if r.Context().Err()==context.DeadlineExceeded {
// Timeout happened
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论