Added OS signals handler

Added go.mod
This commit is contained in:
Alexander Kiryukhin 2019-01-11 17:22:06 +03:00
parent c582001e89
commit a4e62510cf
6 changed files with 33 additions and 14 deletions

View file

@ -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)

View file

@ -1,3 +1,5 @@
// +build ignore
package main
import (

6
go.mod Normal file
View file

@ -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
)

4
go.sum Normal file
View file

@ -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=

View file

@ -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()

View file

@ -2,10 +2,9 @@ package rutina
import (
"context"
"errors"
"testing"
"time"
"github.com/pkg/errors"
)
func TestSuccess(t *testing.T) {