TIL: Go's context.AfterFunc
Go 1.21 added context.AfterFunc which registers a function to run (in its own goroutine) after a context is done.
1stop := context.AfterFunc(ctx, func() {
2 // cleanup logic here
3 conn.Close()
4})
5
6// Call stop() if you want to prevent the function from running
7defer stop()This is cleaner than spinning up a goroutine with select on ctx.Done() – the stdlib handles the lifecycle for you.
Key things to note:
- The function runs in its own goroutine
stop()returnstrueif it successfully prevented the call- Multiple
AfterFunccalls on the same context are independent