英文:
golang api when to use the cancel method on context
问题
我有一个标准的golang API,它的流程如下:
handler.go -> service.go -> repository.go -> elasticRepository。
在所有这些情况下,我都从handler传递context
对象一直传递到repository.go
文件。我的问题是关于在context
对象上使用cancel
方法。如果用户在中途取消请求,我在handler.go
上监听context
对象上的完成信号,但是一旦我收到信号,接下来该怎么做?我应该调用cancel吗?我的service.go
和repository.go
文件目前除了传递参数之外没有做太多事情,但是repository.go
文件有一个对弹性客户端的引用,该客户端也使用相同的context
对象。我的假设是,如果用户取消请求,弹性客户端将自动收到此通知并取消,我不需要做任何操作,这样对吗?
英文:
I have a standard golang api which takes the following flow
handler.go->service.go->repository.go->elasticRepository.
In all these cases from the handler I am passing down the context
object all the way down to the repository.go
file. My question is around the use of the cancel
method on the context
object. Mid-way if the user cancels the request I am listning to the done signal on the context object on the handler.go
but once I get the signal what should I do next ? should I call cancel?. My service.go
and repository.go
files don't do much other than just passing down the paramters for the moment, however the repository.go
file has a reference to the elastic client which is also using this same context
object. My assumption is that if the user cancels the request, the elastic client will automatically get this notification and cancel and I don't have to do anything, is this correct ?
答案1
得分: 2
我查看了ElasticSearch的Golang客户端代码,并发现:
每个ES请求都使用传输客户端:
go-elasticsearch <- elastictransport <- net/http.DefaultTransport
所以调用过程如下:
您的程序 -> go-elasticsearch API -> transport.Perform() -> elastictransport.Perform() -> net/http.Transport.RoundTrip()
让我们来看一下net/http.Transport.roundTrip的代码片段这里:
select {
case <-ctx.Done():
req.closeBody()
return nil, ctx.Err()
default:
}
ctx被一直传递到这个函数!
回到您的问题:
如果用户取消请求,elastic客户端会自动收到通知并取消,我不需要做任何操作,这样对吗?
答案是:
是的,当上下文被取消后,ES客户端会立即返回。
英文:
I went through the code of ElasticSearch golang client, and found out:
Every ES request uses the transport client:
> go-elasticsearch <- elastictransport <- net/http.DefaultTransport
So the call process would be:
> Your program -> go-elasticsearch API -> transport.Perform() -> elastictransport.Perform() -> net/http.Transport.RoundTrip()
>
Let's look at the code snippet of net/http.Transport.roundTrip here:
select {
case <-ctx.Done():
req.closeBody()
return nil, ctx.Err()
default:
}
the ctx is passed all the way to this function!
Back to your question:
> if the user cancels the request, the elastic client will automatically get this notification and cancel and I don't have to do anything, is this correct ?
The answer is:
> Yes, the ES client will return, right after the context is canceled
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论