https://github.com/xgfone/go-atexit
Manage the exit functions of the program.
https://github.com/xgfone/go-atexit
atexit exit go golang init
Last synced: 9 months ago
JSON representation
Manage the exit functions of the program.
- Host: GitHub
- URL: https://github.com/xgfone/go-atexit
- Owner: xgfone
- License: apache-2.0
- Created: 2021-05-29T00:50:54.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2024-05-13T06:36:27.000Z (about 2 years ago)
- Last Synced: 2024-12-11T21:42:01.570Z (over 1 year ago)
- Topics: atexit, exit, go, golang, init
- Language: Go
- Homepage:
- Size: 59.6 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Go AtExit [](https://github.com/xgfone/go-atexit/actions/workflows/go.yml) [](https://pkg.go.dev/github.com/xgfone/go-atexit) [](https://raw.githubusercontent.com/xgfone/go-atexit/master/LICENSE)
The package `atexit` is used to manage the exit functions of the program. Support `Go1.8+`.
## Install
```shell
$ go get -u github.com/xgfone/go-atexit
```
## Example
```go
package main
import (
"flag"
"log"
"os"
"github.com/xgfone/go-atexit"
)
var logfile = flag.String("logfile", "", "the log file path")
func init() {
// Register the exit functions
atexit.OnExitWithPriority(1, func() { log.Println("the program exits") })
atexit.OnExit(func() { log.Println("do something to clean") })
// Register the init functions.
atexit.OnInit(flag.Parse)
atexit.OnInit(func() {
if *logfile != "" {
file, err := os.OpenFile(*logfile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Println(err)
atexit.Exit(1)
} else {
log.SetOutput(file)
}
// Close the file before the program exits.
atexit.OnExitWithPriority(0, func() {
log.Println("close the log file")
file.Close()
})
}
})
}
func main() {
atexit.Init()
log.Println("do jobs ...")
atexit.Exit(0)
// $ go run main.go
// 2021/05/29 08:29:14 do jobs ...
// 2021/05/29 08:29:14 do something to clean
// 2021/05/29 08:29:14 the program exits
//
// $ go run main.go -logfile test.log
// $ cat test.log
// 2021/05/29 08:29:19 do jobs ...
// 2021/05/29 08:29:19 do something to clean
// 2021/05/29 08:29:19 the program exits
// 2021/05/29 08:29:19 close the log file
}
```