Created
September 3, 2021 05:53
-
-
Save rekby/913c047c63a59713b8356f6112dacc16 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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