Created
May 8, 2022 00:57
-
-
Save umutbasal/42a3331280ae3e68ba99116c001bb69c to your computer and use it in GitHub Desktop.
prefix executed commands output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"context" | |
"fmt" | |
"io" | |
"os/exec" | |
) | |
func prefix(s string) string { | |
return "prefix: " + s | |
} | |
func main() { | |
reader, writer := io.Pipe() | |
ctx, cancel := context.WithCancel(context.Background()) | |
scannerStopped := make(chan struct{}) | |
go func() { | |
defer close(scannerStopped) | |
scanner := bufio.NewScanner(reader) | |
for scanner.Scan() { | |
fmt.Println(prefix(scanner.Text())) | |
} | |
}() | |
cmd := exec.Command("cat", "main.go") | |
cmd.Stdout = writer | |
_ = cmd.Start() | |
go func() { | |
_ = cmd.Wait() | |
cancel() | |
writer.Close() | |
}() | |
<-ctx.Done() | |
<-scannerStopped | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment