Home > Software engineering >  Read from os.stdout
Read from os.stdout

Time:10-13

I would like to send log information to a socket, to achieve that, I need to first capture the os.stdout. I know i could redirect the os.stdout with os.pipe. But is there a way i directly read from os.stdout use bufio.NewReader or bufio.NewScanner?

func Start() {
   //dataChan := make(chan string)

   outC := make(chan string, 3)
   defer close(outC)
   conn, err := net.Dial("tcp", "localhost:9090")

   if err != nil {
       log.Fatal(err)
   }

   fmt.Println("first line!")
   fmt.Println("second line!")
   fmt.Println("third line!")
   // write to channel
   go func() {
       scanner := bufio.NewScanner(os.Stdout)
       for scanner.Scan() {
           outC <- scanner.Text()   "\n"
           err = scanner.Err()

           if err != nil {
               log.Fatal(err)
           }
       }
   }()

   // read from channel and print to connection
   go func() {
       out := <-outC

       for {
           conn.Write([]byte(out   "\n"))
       }

   }()

}

CodePudding user response:

You could read stdout through os.Pipe

    old := os.Stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    fmt.Println("first line!")
    fmt.Println("second line!")
    fmt.Println("third line!")

    w.Close()
    os.Stdout = old // restore stdout

    for {
        select {
        case out := <-outC:
            conn.Write([]byte("read "   out   "\n"))
        }
    }
  • Related