diff options
-rwxr-xr-x | README.md | 15 | ||||
-rw-r--r-- | example/http_server.go | 2 | ||||
-rw-r--r-- | go.mod | 6 | ||||
-rw-r--r-- | go.sum | 4 | ||||
-rwxr-xr-x | rutina.go | 17 | ||||
-rwxr-xr-x | rutina_test.go | 3 |
6 files changed, 33 insertions, 14 deletions
@@ -15,7 +15,7 @@ HTTP server with graceful shutdown (`example/http_server.go`): ``` // New instance with builtin context. Alternative: r, ctx := rutina.WithContext(ctx) -r := rutina.New() +r, _ := rutina.New() srv := &http.Server{Addr: ":8080"} http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { @@ -38,17 +38,8 @@ r.Go(func(ctx context.Context) error { return srv.Shutdown(ctx) }) -// OS signals subscriber -r.Go(func(ctx context.Context) error { - sig := make(chan os.Signal, 1) - signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT) - select { - case <-sig: - log.Println("TERM or INT signal received") - case <-ctx.Done(): - } - return nil -}) +// OS signals listener +r.ListenTermSignals() if err := r.Wait(); err != nil { log.Fatal(err) diff --git a/example/http_server.go b/example/http_server.go index b1d0181..a8072bb 100644 --- a/example/http_server.go +++ b/example/http_server.go @@ -1,3 +1,5 @@ +// +build ignore + package main import ( @@ -0,0 +1,6 @@ +module github.com/NeonXP/rutina + +require ( + github.com/neonxp/rutina v0.0.0-20181204214833-c582001e89c0 + github.com/pkg/errors v0.8.1 +) @@ -0,0 +1,4 @@ +github.com/neonxp/rutina v0.0.0-20181204214833-c582001e89c0 h1:AyPAQ9ebiG/k20WXojUg0rIqodaaw1KFYk4QJpHYIm4= +github.com/neonxp/rutina v0.0.0-20181204214833-c582001e89c0/go.mod h1:QJOHIcMI4Lh4Nyyi0v119KZllW1S5KxJyy/zg5KQXno= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -2,7 +2,10 @@ package rutina import ( "context" + "os" + "os/signal" "sync" + "syscall" ) //Rutina is routine manager @@ -44,6 +47,20 @@ func (r *Rutina) Go(doer func(ctx context.Context) error) { }() } +// OS signals handler +func (r *Rutina) ListenTermSignals() { + r.Go(func(ctx context.Context) error { + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT) + select { + case <-sig: + r.cancel() + case <-ctx.Done(): + } + return nil + }) +} + // Wait all routines and returns first error or nil if all routines completes without errors func (r *Rutina) Wait() error { r.wg.Wait() diff --git a/rutina_test.go b/rutina_test.go index cff73c4..361d5eb 100755 --- a/rutina_test.go +++ b/rutina_test.go @@ -2,10 +2,9 @@ package rutina import ( "context" + "errors" "testing" "time" - - "github.com/pkg/errors" ) func TestSuccess(t *testing.T) { |