fix: fix goroutine leak
Fix https://github.com/haunt98/go-test-color/issues/1 Replace goroutine use with more idiomatic usage https://pkg.go.dev/os/exec#Cmd.StdoutPipe https://pkg.go.dev/os/exec#Cmd.StderrPipemain
parent
53248bff4d
commit
bcc2054da6
42
main.go
42
main.go
|
@ -12,6 +12,8 @@ import (
|
||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const cmdName = "go-test-color"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
code := runGoTest()
|
code := runGoTest()
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
|
@ -24,33 +26,33 @@ func runGoTest() int {
|
||||||
args = append(args, os.Args[1:]...)
|
args = append(args, os.Args[1:]...)
|
||||||
cmd := exec.Command("go", args...)
|
cmd := exec.Command("go", args...)
|
||||||
|
|
||||||
// Output pipe
|
// Read stdout and stderr
|
||||||
outReader, outWriter := io.Pipe()
|
outReader, err := cmd.StdoutPipe()
|
||||||
defer outReader.Close()
|
if err != nil {
|
||||||
defer outWriter.Close()
|
log.Printf("%s failed to get stdout pipe: %s", cmdName, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
// Error pipe
|
errReader, err := cmd.StderrPipe()
|
||||||
errReader, errWriter := io.Pipe()
|
if err != nil {
|
||||||
defer errReader.Close()
|
log.Printf("%s failed to get stderr pipe: %s", cmdName, err)
|
||||||
defer errWriter.Close()
|
return 1
|
||||||
|
}
|
||||||
// Redirect cmd pipes to our pipes
|
|
||||||
cmd.Stdout = outWriter
|
|
||||||
cmd.Stderr = errWriter
|
|
||||||
|
|
||||||
// See https://stackoverflow.com/questions/8875038/redirect-stdout-pipe-of-child-process-in-go
|
// See https://stackoverflow.com/questions/8875038/redirect-stdout-pipe-of-child-process-in-go
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
log.Printf("Failed to start: %s", err)
|
log.Printf("%s failed to start: %s", cmdName, err)
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
defer func() {
|
|
||||||
if err := cmd.Wait(); err != nil {
|
|
||||||
log.Printf("Failed to wait: %s", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
go colorOutputReader(outReader)
|
// Add color to both stdout and stderr
|
||||||
go colorErrorReader(errReader)
|
colorOutputReader(outReader)
|
||||||
|
colorErrorReader(errReader)
|
||||||
|
|
||||||
|
if err := cmd.Wait(); err != nil {
|
||||||
|
log.Printf("%s failed to wait: %s", cmdName, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue