# Go's context.Background and TODO

In Go's context package, from the [source code](https://golang.org/src/context/context.go?s=7426:7451#L198), `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.

```go
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.

```go
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:
```go
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
* https://golang.org/pkg/context/#pkg-overview
* [Using context cancellation in Go](https://www.sohamkamani.com/golang/2018-06-17-golang-using-context-cancellation/)
* [上下文Context](https://draveness.me/golang/docs/part3-runtime/ch06-concurrency/golang-context/#61-%e4%b8%8a%e4%b8%8b%e6%96%87-context)
