-
Notifications
You must be signed in to change notification settings - Fork 27
/
main.go
51 lines (44 loc) · 1.04 KB
/
main.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
47
48
49
50
51
package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
)
func createContextWithTimeout(d time.Duration) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithTimeout(context.Background(), d)
return ctx, cancel
}
func setupSignalHandler(w io.Writer, cancelFunc context.CancelFunc) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go func() {
s := <-c
fmt.Fprintf(w, "Got signal: %v\n", s)
cancelFunc()
}()
}
func executeCommand(ctx context.Context, command string, arg string) error {
return exec.CommandContext(ctx, command, arg).Run()
}
func main() {
if len(os.Args) != 3 {
fmt.Fprintf(os.Stdout, "Usage: %s <command> <argument>\n", os.Args[0])
os.Exit(1)
}
command := os.Args[1]
arg := os.Args[2]
cmdTimeout := 30 * time.Second
ctx, cancel := createContextWithTimeout(cmdTimeout)
defer cancel()
setupSignalHandler(os.Stdout, cancel)
err := executeCommand(ctx, command, arg)
if err != nil {
fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
}