https://github.com/lesiw/defers
Global defers for Go.
https://github.com/lesiw/defers
go go-package golang
Last synced: 10 months ago
JSON representation
Global defers for Go.
- Host: GitHub
- URL: https://github.com/lesiw/defers
- Owner: lesiw
- License: mit
- Created: 2024-06-16T19:41:22.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-12-23T23:15:42.000Z (over 1 year ago)
- Last Synced: 2024-12-23T23:27:41.968Z (over 1 year ago)
- Topics: go, go-package, golang
- Language: Go
- Homepage: https://lesiw.io/defers
- Size: 26.4 KB
- Stars: 17
- Watchers: 1
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# lesiw.io/defers
[](https://pkg.go.dev/lesiw.io/defers)
Package defers handles program-wide defers.
Defers are executed when defers.Exit() is called or when an interrupt signal is
caught, whichever happens first.
If an interrupt signal is caught, the program will exit with a status of 128
plus the signal number. In the event the signal number cannot be determined, the
program will exit with exit status 1.
## Example
```go
package main
import (
"fmt"
"os"
"lesiw.io/defers"
)
// Set stop to true to halt the program.
// This forces the Go Playground to send an os.Interrupt.
// Global defers will still run before the program ends.
var stop = false
var success bool
func main() {
defer defers.Run()
defers.Add(func() {
if success {
fmt.Fprintln(os.Stderr, "The program executed successfully.")
} else {
fmt.Fprintln(os.Stderr, "The program was interrupted.")
}
})
fmt.Println("Preparing to send a greeting...")
if stop {
select {}
}
fmt.Println("Hello world!")
success = true
}
```
[▶️ Run this example on the Go Playground](https://go.dev/play/p/Ser5Yr68rko)