Skip to content

Instantly share code, notes, and snippets.

@jgfrancisco
Last active August 29, 2015 14:20
Show Gist options
  • Save jgfrancisco/6610078040b15b7e9611 to your computer and use it in GitHub Desktop.
Save jgfrancisco/6610078040b15b7e9611 to your computer and use it in GitHub Desktop.
Golang read from stdoutput
#!/bin/sh
for i in {1..20}
do
echo "This is message $i"
sleep $i
done
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
//"os"
"os/exec"
)
func readLine(reader *bufio.Reader) (strLine string, err error) {
buffer := new(bytes.Buffer)
for {
var line []byte
var isPrefix bool
log.Println("[INFO] Start reading line...")
line, isPrefix, err = reader.ReadLine()
log.Printf("[DEBUG] Read Len: %d, isPrefix: %t, Error: %v\n", len(line), isPrefix, err)
if err != nil && err != io.EOF {
return "", err
}
buffer.Write(line)
if !isPrefix {
log.Println("[INFO] EOL found")
break
}
}
log.Println("[DEBUG] End of line")
return buffer.String(), err
}
func main() {
//log.SetOutput(os.Stdout)
//cmd := exec.Command("./multiEcho.sh")
phantomjs := "/Users/zAthan/goLang/src/github.com/jgfrancisco/outPipeTest/phantomjs/bin/phantomjs"
cmd := exec.Command(phantomjs, "./hbsniffer.js", "http://topgear.com.ph")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
defer cmd.Wait()
go func() {
reader := bufio.NewReader(stdout)
for {
strline, err := readLine(reader)
if err != nil && err != io.EOF {
log.Fatal(err)
}
if len(strline) > 0 {
fmt.Printf("Read message: %s\n", strline)
}
if err == io.EOF {
fmt.Println("EOF. No more messages")
log.Println("[DEBUG] Exiting IO read")
break
}
fmt.Println("Waiting for the next message...")
}
log.Println("[DEBUG] Exiting go func()")
}()
fmt.Println("Waiting for output...")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment