确定 TimeoutHandler 是否已超时

huangapple go评论83阅读模式
英文:

Determining if TimeoutHandler has timed out

问题

我正在使用http.TimeoutHandler来向客户端返回超时错误。这个功能正常工作,但问题是,如果超时被触发,我想调用一些代码。我查看了文档和源代码,但找不到一个好的方法来实现这个。响应只是返回给客户端,我找不到一种方法来检查上下文或ResponseWriter等。

调用代码无法访问上下文,所以我无法检查它。实际上,http.ResponseWriterhttp.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
  }
}

huangapple
  • 本文由 发表于 2021年8月7日 22:39:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/68693351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定