Understanding Context in Golang

Iman Tung
1 min readAug 18, 2019

--

Sometimes functions/process requires some context.Context to run. What’s kind of context we need to give?

  • context.Background() if you only need it run as it is
  • context.WithValue(...) if you need to give some value to the process
  • context.WithCancel(...) if you want to able to cancel the process
  • context.WithDeadline(...) if you want the process done at some deadline time.
  • context.WithTimeout(...) if you want the process done after some duration(some with WithDeadline )

Give some value to the process

The process using contextValue(interface{}) interface{} to get the value.

func Process(ctx context.Context) {
value := ctx.Value("message")
fmt.Println(value)
}

Interruptible process

The process must be handled Done() <- chan struct{} as a signal from context to stop the work immediately. Read more about channel here.

func Process(ctx context.Context) {
finish := make(chan int)
go func() {
time.Sleep(3 * time.Second)
finish <- 1
}()
select {
case <-ctx.Done():
fmt.Println("cancelled")
case <-finish:
fmt.Println("finished")
}
}

Determine how the process is done

The caller used Err() error to determine how the process is done. If Err() return nil then because the process work is finished. Else, it is interrupted by context.

func main() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 10*time.Microsecond)
defer cancel()
process(ctx)
if ctx.Err() != nil {
fmt.Println(ctx.Err().Error())
}
}

Example

Check the my Github Repository for example in this writing. For further reading, the godoc provide a detailed explanation.

--

--

Iman Tung
Iman Tung

Written by Iman Tung

Technology to write, life to grateful. Overthinking is good, only if it has the output. Fundamental is the main concern.

No responses yet