V
V
vgrabkowot2021-04-17 14:01:24
go
vgrabkowot, 2021-04-17 14:01:24

How to work with Context correctly?

Good afternoon. I have a function:

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  p := getProviders(w, r)
  defer p.Close()

  ctx, cancel := context.WithTimeout(context.Background(), config.Read().HTTP.Timeout.Request*time.Second)
  defer cancel()
  h, isExist := nodePathGet(router.getBaseNode(r.Method), r.RequestURI)

  if !isExist {
    router.Errors.PageNotFound(ctx, p)
  } else {
    go func() {
      router.middlewareHandler(h)(ctx, p)
      cancel()
    }()
  }

  <-ctx.Done()
  if ctx.Err() == nil {
    if ctx.Err() == context.DeadlineExceeded {
      log.Println(r.Method, r.RequestURI, "error request timeout")
      router.Errors.RequestTimeout(ctx, p)
    }
  }
}

The problem is that when the function router.middlewareHandler(h)(ctx, p)runs longer than the set timeout, it triggers defer p.Close()which frees the memory, and then the routine tries to write something there and everything falls with a panic.

I want to implement a standard timeout. If the function does not complete longer than a certain time, then we "kill" it and display an error. How to implement it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2021-04-17
@vgrabkowot

Firstly, it is better to take the context not from Background, but from the http request. Thus, you will correctly handle the situation when the connection with the client is broken and you no longer need to process the request (the context will be canceled).

ctx, cancel := context.WithTimeout(r.Context(), config.Read().HTTP.Timeout.Request*time.Second)

Secondly, the context is usually not used to wait for internal goroutines, it is not intended for this. For this use sync.WaitGroup.
That's why you have a problem, because the context cancel event does not mean that the child functions have completed immediately. There is a situation where the reading of the channel <-ctx.Done()inside the function you provided occurs before the same reading of the channel inside the router.middlewareHandler(h) function. Therefore, you need to wait not for the cancellation of the context, but for the completion of the goroutine.
Thirdly, you don’t need a goroutine at all here, because you waited for its completion right after it. Instead, you can just write sequential code.
Fourth, you probably wanted to write . But you have == instead, which generally devalues ​​the code inside this ifa. if ctx.Err() != nil {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question