3 A `signalcontext.Context` provides a `context.Context` which cancels
4 when an operating system signal (e.g. [os.Interrupt][]) is received.
5 This can be useful to bound some long or infinite operation running near
6 the top-level of a program so the rest of the program can
7 proceed with a clean shutdown.
9 [os.Interrupt]: https://golang.org/pkg/os/#Signal
14 Using this module correctly requires some knowledge of the standard
15 [context package][]. In its simplest form it can be used exactly like
16 any other context, e.g. to read from a [sarama ConsumerGroup][] until an
17 interrupt is received:
20 parent := context.Background() // for example
21 ctx := signalcontext.UntilSignal(parent, os.Interrupt)
28 err = consumer.Consume(ctx, topics, hander)
35 A more advanced use would be to push decisions about acceptable cleanup
36 times out of the process, into an orchestration layer that communicates
40 parent := context.Background() // for example
41 srv := &http.Server{…}
43 // Run an HTTP server until a SIGTERM is received…
44 srvctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
46 handleError(srv.ListenAndServe())
50 // no need to cancel, srvctx must be done by now.
52 // Then try a clean shutdown, giving up if a second SIGTERM is received.
53 shutdownctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
54 defer shutdownctx.Cancel()
55 return srv.Shutdown(srvctx)
58 [context package]: https://golang.org/pkg/context/
59 [sarama ConsumerGroup]: https://godoc.org/github.com/Shopify/sarama#ConsumerGroup
64 Copyright 2020 Joe Wreschnig
66 This program is free software: you can redistribute it and/or modify it
67 under the terms of the [GNU General Public License](COPYING) as
68 published by the Free Software Foundation, either version 3 of the
69 License, or (at your option) any later version.