Gracefully quit when you press ctrl-c.
go get -u github.com/danielgatis/go-ctrlc
And then import the package in your code:
import "github.com/danielgatis/go-ctrlc"
An example described below is one of the use cases.
package main
import (
"fmt"
"os"
"time"
"github.com/danielgatis/go-ctrlc"
)
func main() {
tick := time.NewTicker(time.Second)
exit := make(chan struct{})
ctrlc.Watch(func() {
exit <- struct{}{}
})
for {
select {
case <-exit:
fmt.Println("bye!")
os.Exit(0)
case <-tick.C:
fmt.Println(time.Now())
}
}
}
❯ go run main.go
2022-01-06 12:08:46.015813 -0300 -03 m=+1.000276951
2022-01-06 12:08:47.016224 -0300 -03 m=+2.000688652
^Cbye!
Copyright (c) 2021-present Daniel Gatis
Licensed under MIT License
Liked some of my work? Buy me a coffee (or more likely a beer)