Skip to content

Instantly share code, notes, and snippets.

@gdey
Created October 28, 2015 03:58
Show Gist options
  • Save gdey/f72b853a34e7b9f8e9b0 to your computer and use it in GitHub Desktop.
Save gdey/f72b853a34e7b9f8e9b0 to your computer and use it in GitHub Desktop.
Basic template for a correctly cancelable go application.
/* 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()
}
@gdey
Copy link
Author

gdey commented Oct 28, 2015

I have packaged this up here https://github.com/gdey/cmd

So the above becomes:

package main

import (
   "github.com/gdey/cmd"
)

func main(){
     defer cmd.New().Complete()
     // do main stuff here. Use cmd.IsCancelled() and cmd.Cancelled() as needed.
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment