Skip to content

Instantly share code, notes, and snippets.

@rekby
Created September 3, 2021 05:53
Show Gist options
  • Save rekby/913c047c63a59713b8356f6112dacc16 to your computer and use it in GitHub Desktop.
Save rekby/913c047c63a59713b8356f6112dacc16 to your computer and use it in GitHub Desktop.
package ctxcancel
import "context"
// CtxCancel run f in background and return result
// onCancel called if ctx cancelled before f return result
// it called after f finish
// return f result of ctx.Err() (if ctx cancelled)
func CtxCancel(ctx context.Context, f func() error, onCancel func()) error {
fResult := make(chan error, 1)
go func() {
err := f()
fResult <- err
close(fResult)
}()
select {
case <-ctx.Done():
// pass
case err := <-fResult:
return err
}
if onCancel != nil {
go func() {
<-fResult
onCancel()
}()
}
return ctx.Err()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment