Shutdown server gracefully with Ctrl-C

This commit is contained in:
Iwasaki Yudai 2015-08-24 19:22:25 +09:00
parent 94a6230355
commit e613b29cc3
3 changed files with 45 additions and 2 deletions

25
main.go
View file

@ -7,6 +7,8 @@ import (
"github.com/codegangsta/cli"
"github.com/yudai/gotty/app"
"os/signal"
"syscall"
)
func main() {
@ -107,6 +109,8 @@ func main() {
os.Exit(2)
}
registerSignals(app)
err = app.Run()
if err != nil {
fmt.Println(err)
@ -118,3 +122,24 @@ func main() {
cmd.Run(os.Args)
}
func registerSignals(app *app.App) {
sigChan := make(chan os.Signal, 1)
signal.Notify(
sigChan,
syscall.SIGINT,
syscall.SIGTERM,
)
go func() {
for {
s := <-sigChan
switch s {
case syscall.SIGINT, syscall.SIGTERM:
if !app.Exit() {
os.Exit(4)
}
}
}
}()
}