https://github.com/dataphos/lib-shutdown
A lightweight Go library which offers utility functions that deal with graceful termination on selected OS signals.
https://github.com/dataphos/lib-shutdown
go library
Last synced: 24 days ago
JSON representation
A lightweight Go library which offers utility functions that deal with graceful termination on selected OS signals.
- Host: GitHub
- URL: https://github.com/dataphos/lib-shutdown
- Owner: dataphos
- License: apache-2.0
- Created: 2024-10-02T09:19:27.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-10-11T09:19:38.000Z (over 1 year ago)
- Last Synced: 2025-12-26T06:47:49.296Z (6 months ago)
- Topics: go, library
- Language: Go
- Homepage:
- Size: 55.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
# lib-shutdown
lib-shutdown is a lightweight Go library that offers utility functions that deal with graceful termination on selected
OS signals.
## Installation
`go get github.com/dataphos/lib-shutdown`
## Getting Started
### Cancelling Context On OS Signals
The code snippet below shows the basic principle of the `graceful` package:
```go
secondsRemaining := 10
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(secondsRemaining)*time.Second)
defer cancel()
ctx = graceful.WithSignalShutdown(ctx)
for {
select {
case <-ctx.Done():
fmt.Println("context cancelled, leaving")
return
case <-time.After(1 * time.Second):
secondsRemaining -= 1
fmt.Println(secondsRemaining, "seconds remaining")
}
}
```
`graceful.WithSignalShutdown` returns a new ctx derived from the one given, which will be cancelled when this process
receives a SIGTERM or SIGQUIT signal, cancelling the returned context before the parent context times out.
### Graceful Shutdown of HTTP Servers
`graceful.ListenAndServe` and `graceful.ListenAndServeTLS` functions wrap the equivalent
method of the given `http.Server` instance, signaling to the server that a SIGTERM or SIGQUIT signal
was received, allowing some additional time for the server to cleanup and complete the active requests.