Home > other >  golang api when to use the cancel method on context
golang api when to use the cancel method on context

Time:01-22

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 ?

CodePudding user response:

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

  •  Tags:  
  • Related