Go's context.Background and TODO

·

1 min read

In Go's context package, from the source code, context.Background and context.TODO both return the global Empty context.

This means, in your application you don't need to call ctx.TODO in every function, b/c it returns the same global todo context anyway, you could call ctx.TODO once and save a global variable, then use that in your functions.

var (
    background = new(emptyCtx)
    todo       = new(emptyCtx)
)

func Background() Context {
    return background
}

func TODO() Context {
    return todo
}

Empty context's Done function return a nil channel, which means you shouldn't listen on it, b/c listen on a nil channel will block the program forever.

type emptyCtx int

func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
    return
}

func (*emptyCtx) Done() <-chan struct{} {
    return nil
}

func (*emptyCtx) Err() error {
    return nil
}

func (*emptyCtx) Value(key interface{}) interface{} {
    return nil
}

Example:

func myfunc(ctx context.Context) error {
    // ...
    done := ctx.Done()
    // here need to check if done is nil before select on it
    if done == nil {
        // do something
        return nil
    }

    select {
    case <- done:
        // do something
    case <- default:
         // do something
    }
}

Reference