https://github.com/catvec/gointerrupt
Easily handle signals via context. Makes it easy to gracefully shutdown programs.
https://github.com/catvec/gointerrupt
Last synced: 7 months ago
JSON representation
Easily handle signals via context. Makes it easy to gracefully shutdown programs.
- Host: GitHub
- URL: https://github.com/catvec/gointerrupt
- Owner: catvec
- License: mit
- Created: 2020-01-07T06:40:18.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2024-06-20T02:01:21.000Z (almost 2 years ago)
- Last Synced: 2025-05-04T01:02:13.232Z (11 months ago)
- Language: Go
- Homepage:
- Size: 10.7 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://godoc.org/github.com/Noah-Huppert/gointerrupt)
# Go Interrupt
Easily handle interrupts via context.
# Table Of Contents
- [Overview](#overview)
- [Examples](#examples)
- [HTTP Server](#http-server-example)
- [Custom Signal](#custom-signal-example)
# Overview
Makes it easy to gracefully shutdown programs.
Provides a graceful shutdown `context.Context` which is canceled when the first
interrupt signal (`SIGINT`) is received. A harsh shutdown `context.Context` is
also provided and is canceled when the first termination signal (`SIGTERM`)
is received.
This allows processes to attempt to gracefully shutdown components by passing
a context. The harsh shutdown signal can be used to kill a graceful shutdown
processes as nicely as possible.
# Examples
## HTTP Server Example
This example shows how to use gointerrupt to gracefully shutdown
a `net/http.Server`.
```go
package main
import (
"context"
"net/http"
"sync"
"github.com/Noah-Huppert/gointerrupt"
)
func main() {
// Initialize a go interrupt context pair
ctxPair := gointerrupt.NewCtxPair(context.Background())
// Wait group is used to not exit the program until the HTTP server go
// routine has completed
var wg sync.WaitGroup
server := http.Server{
Addr: ":5000",
}
// Run HTTP server
wg.Add(1)
go func() {
if err := server.ListenAndServe(); err != nil &&
err != http.ErrServerClosed {
panic(err)
}
wg.Done()
}()
// Gracefully shutdown HTTP server when SIGINT received
go func() {
<-ctxPair.Graceful().Done()
if err := server.Shutdown(ctxPair.Harsh()); err != nil {
panic(err)
}
}()
wg.Wait()
}
```
## Custom Signal Example
This example shows how to cancel a context with custom signals.
```go
package main
import (
"context"
"net/http"
"syscall"
"github.com/Noah-Huppert/gointerrupt"
)
func main() {
// Setup a context to cancel when a kill signal is sent to the process
ctx := gointerrupt.NewSignalCtx(context.Background(), syscall.SIGKILL)
// Context will cancel when SIGKILL received
<-ctx.Ctx().Done()
}
```