-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommand.go
46 lines (39 loc) · 953 Bytes
/
command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package consistenthashing
import (
"context"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
func RunCommand(cmd func(cmd *cobra.Command, args []string) error) {
signals := make(chan os.Signal, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
select {
case sig := <-signals:
log.WithField("signal", sig).Info("got signal, clean up and exit")
cancel()
case <-ctx.Done():
}
}()
rootCmd := &cobra.Command{
PreRun: func(cmd *cobra.Command, args []string) {
rand.Seed(time.Now().UTC().UnixNano())
viper.AutomaticEnv()
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
},
RunE: cmd,
PostRun: func(cmd *cobra.Command, args []string) {
signal.Stop(signals)
},
}
if err := rootCmd.ExecuteContext(ctx); err != nil {
log.WithError(err).Fatal("failed to execute command")
}
}