Add project documentation and licensing
[go-signalcontext.git] / README.md
1 # `signalcontext`
2
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.
8
9 [os.Interrupt]: https://golang.org/pkg/os/#Signal
10
11
12 ## Usage
13
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:
18
19 ```go
20 parent := context.Background() // for example
21 ctx := signalcontext.UntilSignal(parent, os.Interrupt)
22 var err error
23 for err == nil {
24 select {
25 case <-ctx.Done():
26 err = ctx.Err()
27 default:
28 err = consumer.Consume(ctx, topics, hander)
29 }
30 }
31 ctx.Cancel()
32 return err
33 ```
34
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
37 by sending signals:
38
39 ```go
40 parent := context.Background() // for example
41 srv := &http.Server{…}
42
43 // Run an HTTP server until a SIGTERM is received…
44 srvctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
45 go func() {
46 handleError(srv.ListenAndServe())
47 srvctx.Cancel()
48 }()
49 <-srvctx.Done()
50 // no need to cancel, srvctx must be done by now.
51
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)
56 ```
57
58 [context package]: https://golang.org/pkg/context/
59 [sarama ConsumerGroup]: https://godoc.org/github.com/Shopify/sarama#ConsumerGroup
60
61
62 ## Licensing
63
64 Copyright 2020 Joe Wreschnig
65
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.