danielgatis / go-ctrlc

Gracefully quit when you press ctrl-c.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Go - Ctrlc

Go Report Card License MIT Go Doc

Gracefully quit when you press ctrl-c.

Install

go get -u github.com/danielgatis/go-ctrlc

And then import the package in your code:

import "github.com/danielgatis/go-ctrlc"

Example

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!

License

Copyright (c) 2021-present Daniel Gatis

Licensed under MIT License

Buy me a coffee

Liked some of my work? Buy me a coffee (or more likely a beer)

Buy Me A Coffee

About

Gracefully quit when you press ctrl-c.

License:MIT License


Languages

Language:Go 100.0%