Skip to content

Add main_stdout_ospipe example #930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/singleapp/main_stdout_ospipe/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
app
10 changes: 10 additions & 0 deletions examples/singleapp/main_stdout_ospipe/Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# https://taskfile.dev

version: '3'

tasks:
default:
cmds:
- go build -o app .
- ./app -v "hello" -v "world" -v "へろー" -v "ワールド"
- go test .
34 changes: 34 additions & 0 deletions examples/singleapp/main_stdout_ospipe/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"flag"
"fmt"
"strings"
)

type (
vars []string
)

func (me *vars) String() string {
return fmt.Sprint(*me)
}

func (me *vars) Set(v string) error {
*me = append(*me, v)
return nil
}

var (
_ flag.Value = (*vars)(nil)
)

func main() {
var (
vs vars
)
flag.Var(&vs, "v", "values")
flag.Parse()

fmt.Println(strings.Join(vs, ","))
}
42 changes: 42 additions & 0 deletions examples/singleapp/main_stdout_ospipe/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"bytes"
"io"
"os"
"sync"
"testing"
)

func TestMainOutput(t *testing.T) {
// 元の標準出力を退避させ、パイプのWriter側に差し替え
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
defer func() {
// 元に戻す。このプログラムはこのまま終了するので別にしなくて良いが習慣として。
os.Stdout = old
}()

// コマンドライン引数
os.Args = append(os.Args, "-v", "hello", "-v", "world", "-v", "へろー", "-v", "ワールド")

var wg sync.WaitGroup
wg.Add(1)

// パイプはノンバッファリングなので非同期処理が必須
go func() {
defer wg.Done()
defer w.Close()
main()
}()

wg.Wait()

// 出力内容を確認
want := []byte("hello,world,へろー,ワールド\n")
got, _ := io.ReadAll(r)
if !bytes.Equal(want, got) {
t.Errorf("want: %s\tgot: %s", want, got)
}
}
Loading