X-Git-Url: https://git.korewanetadesu.com/?p=go-signalcontext.git;a=blobdiff_plain;f=README.md;fp=README.md;h=d537761a0604406867b76450a3a868db22e1322e;hp=0000000000000000000000000000000000000000;hb=ee7aee79cc9e3e3ccf2929c4eb50ac485ad3c915;hpb=6d43b73af18d23a4cab88dccf8d93a8eb423d2ed diff --git a/README.md b/README.md new file mode 100644 index 0000000..d537761 --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +# `signalcontext` + +A `signalcontext.Context` provides a `context.Context` which cancels +when an operating system signal (e.g. [os.Interrupt][]) is received. +This can be useful to bound some long or infinite operation running near +the top-level of a program so the rest of the program can +proceed with a clean shutdown. + +[os.Interrupt]: https://golang.org/pkg/os/#Signal + + +## Usage + +Using this module correctly requires some knowledge of the standard +[context package][]. In its simplest form it can be used exactly like +any other context, e.g. to read from a [sarama ConsumerGroup][] until an +interrupt is received: + +```go +parent := context.Background() // for example +ctx := signalcontext.UntilSignal(parent, os.Interrupt) +var err error +for err == nil { + select { + case <-ctx.Done(): + err = ctx.Err() + default: + err = consumer.Consume(ctx, topics, hander) + } +} +ctx.Cancel() +return err +``` + +A more advanced use would be to push decisions about acceptable cleanup +times out of the process, into an orchestration layer that communicates +by sending signals: + +```go +parent := context.Background() // for example +srv := &http.Server{…} + +// Run an HTTP server until a SIGTERM is received… +srvctx := signalcontext.UntilSignal(parent, syscall.SIGTERM) +go func() { + handleError(srv.ListenAndServe()) + srvctx.Cancel() +}() +<-srvctx.Done() +// no need to cancel, srvctx must be done by now. + +// Then try a clean shutdown, giving up if a second SIGTERM is received. +shutdownctx := signalcontext.UntilSignal(parent, syscall.SIGTERM) +defer shutdownctx.Cancel() +return srv.Shutdown(srvctx) +``` + +[context package]: https://golang.org/pkg/context/ +[sarama ConsumerGroup]: https://godoc.org/github.com/Shopify/sarama#ConsumerGroup + + +## Licensing + +Copyright 2020 Joe Wreschnig + +This program is free software: you can redistribute it and/or modify it +under the terms of the [GNU General Public License](COPYING) as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version.