Skip to content

Commit 4ba8a69

Browse files
committed
Add withcontext.go
1 parent 07d0624 commit 4ba8a69

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

internal/examples/basic/cmdexec/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@
77
|oneshot.go|cmdexec\_oneshot|コマンドを一発実行して結果を取得するサンプルです|
88
|oneshotwithstderr.go|cmdexec\_oneshot\_with\_stderr|コマンドを一発実行して結果を取得するサンプルです。(標準エラー出力も含む)|
99
|stdinouterr.go|cmdexec\_stdinouterr|標準入力・標準出力・標準エラー出力を指定してコマンドを実行するサンプルです|
10+
|withcontext.go|cmdexec\_withcontext|コマンドを context.Context 付きで実行するサンプルです|

internal/examples/basic/cmdexec/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ func (r *register) Regist(m mappings.ExampleMapping) {
1818
m["cmdexec_oneshot"] = OneShot
1919
m["cmdexec_oneshot_with_stderr"] = OneShotWithStderr
2020
m["cmdexec_stdinouterr"] = Stdinouterr
21+
m["cmdexec_withcontext"] = WithContext
2122
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package cmdexec
2+
3+
import (
4+
"context"
5+
"errors"
6+
"os/exec"
7+
"runtime"
8+
"time"
9+
10+
"github.com/devlights/gomy/output"
11+
)
12+
13+
// WithContext は、context.Context 付きでコマンドを実行するサンプルです。
14+
func WithContext() error {
15+
if runtime.GOOS == "windows" {
16+
return errors.New("this example cannot run on Windows, sorry")
17+
}
18+
19+
const (
20+
Shell = "/bin/bash"
21+
)
22+
23+
var (
24+
rootCtx = context.Background()
25+
mainCtx, mainCxl = context.WithCancel(rootCtx)
26+
procCtx, procCxl = context.WithTimeout(mainCtx, 500*time.Millisecond)
27+
)
28+
29+
defer mainCxl()
30+
defer procCxl()
31+
32+
var (
33+
cmd *exec.Cmd
34+
out []byte
35+
err error
36+
)
37+
38+
cmd = exec.CommandContext(procCtx, Shell, "-c", "sleep 1; echo ...done...")
39+
out, err = cmd.Output()
40+
if err != nil {
41+
var exitErr *exec.ExitError
42+
if errors.Is(procCtx.Err(), context.DeadlineExceeded) && errors.As(err, &exitErr) {
43+
output.Stdoutf("[timeout]", "%[1]v(%[1]T)\n", err)
44+
return nil
45+
} else {
46+
return err
47+
}
48+
}
49+
50+
output.Stdoutl("[output]", string(out))
51+
52+
return nil
53+
}

0 commit comments

Comments
 (0)