Menu Close

WithCancelCause in context package in Go

Here, we will are going to learn about WithCancelCause function in context package in Go with example in details.

The WithCancelCause function in context package in Go is a custom function that can be built on top of the standard ‘WithCancel‘ function. The ‘WithCancelCause‘ function returns a derived context and a cancellation function which is similar to ‘WithCancel‘. However, it also allows you to attach an error value to the cancellation which can be useful for providing additional information about the cause of the cancellation.


func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)


Let’s create a simple example to demonstrate the use of the ‘WithCancelCause’ function. We will create a small Go application that simulates a long-running process and shows how to use the ‘WithCancelCause’ function to cancel the process with an attached cause.

package main

import (







type cancelCauseKey struct{}

func WithCancelCause(parent context.Context) (context.Context, context.CancelFunc, func(error)) {

	ctx, cancel := context.WithCancel(parent)

	setCause := func(err error) {

		if err != nil {

			ctx = context.WithValue(ctx, cancelCauseKey{}, err)




	return ctx, cancel, setCause


func longRunningProcess(ctx context.Context, wg *sync.WaitGroup) {

	defer wg.Done()

	for {

		select {

		case <-ctx.Done():

			cause := ctx.Value(cancelCauseKey{})

			if cause != nil {

				fmt.Printf("Process cancelled: %v\n", cause)

			} else {

				fmt.Println("Process cancelled")




			fmt.Println("Process running...")

			time.Sleep(1 * time.Second)




func main() {

	parentCtx := context.Background()

	ctx, _, setCause := WithCancelCause(parentCtx)

	var wg sync.WaitGroup


	go longRunningProcess(ctx, &wg)

	time.Sleep(5 * time.Second)

	setCause(errors.New("User requested cancellation"))


	fmt.Println("Main function completed")


In this example, the ‘WithCancelCause’ function takes a parent context as an argument and returns a derived context, a cancellation function, and a setCause function. The setCause function takes an error value as an argument, sets it as a value in the context using a custom key, and then calls the cancellation function.

In this example, the longRunningProcess function simulates a long-running process by repeatedly printing “Process running…” every second. It uses the context’s Done channel to listen for a cancellation signal. If a cancellation signal is received, it checks if there’s a cause value attached to the context, and if so, prints the cause along with the “Process cancelled” message.


Process running...
Process running...
Process running...
Process running...
Process cancelled
Main function completed

To learn more about golang, Please refer given below link.


Posted in context, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *