Created
October 28, 2015 03:58
-
-
Save gdey/f72b853a34e7b9f8e9b0 to your computer and use it in GitHub Desktop.
Basic template for a correctly cancelable go application.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Here is a basic template for a cancellable go app using ctr-c. | |
*/ | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"os/signal" | |
"sync" | |
"syscall" | |
"golang.org/x/net/context" | |
) | |
func main_run(ctx context.Context) { | |
/* Do main work here; ctx.Done() will return somtheing when ctr-c has been pressed. */ | |
} | |
func main() { | |
flag.Parse() | |
ctx, cancel := context.WithCancel(context.Background()) | |
c := make(chan os.Signal) | |
signal.Notify(c, os.Interrupt) | |
signal.Notify(c, syscall.SIGTERM) | |
var cancelwg sync.WaitGroup | |
cancelwg.Add(1) | |
go func() { | |
select { | |
case <-c: | |
cancel() | |
case <-ctx.Done(): | |
} | |
cancelwg.Done() | |
}() | |
main_run(ctx) | |
// Make sure cancel go routine exits. | |
cancel() | |
// Wait for the cancel go routine to exit. | |
cancelwg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have packaged this up here https://github.com/gdey/cmd
So the above becomes: