/
View dependency graph
Depends on
- dh-golang (dh-golang)
- golang-defaults (golang-any)
- golang-golang-x-sync (golang-golang-x-sync-dev)
- debhelper-compat
README (full)
lifecycle
Overview
lifecycle helps manage goroutines at the application level. context.Context has been great for propagating cancellation signals, but not for getting any feedback about when goroutines actually finish.
This package works with context.Context to ensure that applications don't quit before their goroutines do.
The semantics work similarly to the go (lifecycle.Go) and defer (lifecycle.Defer) keywords as well as sync.WaitGroup.Wait (lifecycle.Wait). Additionally, there are lifecycle.GoErr and lifecycle.DeferErr which only differ in that they take funcs that return errors.
lifecycle.Wait will block until one of the following happens:
- all funcs registered with
Gocomplete successfully then all funcs registered withDefercomplete successfully - a func registered with
Goreturns an error, immediately cancelingctxand triggeringDeferfuncs to run. Once allGoandDeferfuncs complete,Waitwill return the error - a signal (by default
SIGINTandSIGTERM, but configurable withWithSignals) is received, immediately cancelingctxand triggeringDeferfuncs to run. Once allGoandDeferfuncs complete,Waitwill returnErrSignal - a func registered with
GoorDeferpanics. the panic will be propagated to the goroutine thatWaitruns in. there is no attempt, in case of a panic, to manage the state within thelifecyclepackage.
Example
Here is an example that shows how lifecycle could work with an http.Server:
// At the top of your application
ctx := lifecycle.New(
context.Background(),
lifecycle.WithTimeout(30*time.Second), // optional
)
helloHandler := func(w http.ResponseWriter, req *http.Request) {
_, _ = io.WriteString(w, "Hello, world!\n")
}
mux := http.NewServeMux()
mux.HandleFunc("/hello", helloHandler)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
}
lifecycle.GoErr(ctx, srv.ListenAndServe)
lifecycle.DeferErr(ctx, func() error {
// use a background context because we already have a timeout and when
// Defer funcs run, ctx is necessarily canceled.
return srv.Shutdown(context.Background())
})
// Any panics in Go or Defer funcs will be passed to the goroutine that Wait
// runs in, so it is possible to handle them like this
defer func() {
if r := recover(); r != nil {
panic(r) // example, you probably want to do something else
}
}()
// Then at the end of main(), or run() or however your application operates
//
// The returned err is the first non-nil error returned by any func
// registered with Go or Defer, otherwise nil.
if err := lifecycle.Wait(ctx); err != nil {
log.Fatal(err)
}
| dir | .circleci/ |
| dir | debian/ |
| file | .gitignore |
| file | LICENSE |
| file | README.md |
| file | example_test.go |
| file | go.mod |
| file | go.sum |
| file | lifecycle.go |
| file | lifecycle_test.go |
| file | options.go |