Pass a context.Context to your goroutine and check ctx.Err() or use ctx.Done() to stop execution when the parent context is canceled.
ctx, cancel := context.WithCancel(context.Background())
// Start the goroutine with the context
go func(ctx context.Context) {
select {
case <-ctx.Done():
// Context canceled, exit immediately
return
case <-time.After(5 * time.Second):
// Do work
}
}(ctx)
// Cancel later to stop the goroutine
cancel()