what’s context.Background()

tags: learning go programming

content

  • Background is the root of all contexts
  • context.Background() returns an empty context

WithCancel and WithTimeout

  • these two functions copies parent context (input arg)
  • returns a new context and a cancel function
    • WithTimeout takes one more arg (timeout duration)
    • when timeout duration is reached, context is auto canceled
ctx, cancelFunc = context.WithCancel(ctx)
ctx, cancelFunc = context.WithTimeout(ctx, 10 * time.Seconds)
  • a context has a Done channel
    • canceling the context is to close the Done channel
    • calling cancelFunc closes the Done channel

up

down

reference