简体   繁体   中英

Golang how would you pipe the stdout of a function to another function that executes fzf

Say we have a the following function:

func example() {
   fmt.Println("January")
   fmt.Println("February")
   fmt.Println("March")
}

Now we need another function which takes the output of the above function to bash command fzf, how would you achieve this?

I know i have to redirect stdout to stdin, and there is a whole concept of os.Pipe

So i tried to capture the stdout first:

func capture(f func()) string {
  out := os.Stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  w.Close()
  os.Stdout = out

  var buf bytes.Buffer
  io.Copy(&buf, r)
  return buf.String()
}

Didn't work out and i haven't figured the part of sending stdout to the function that executes fzf

PlayGround

I edited your code and it seems working now check it out.

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func example() {
    fmt.Println("January")
    fmt.Println("February")
    fmt.Println("March")
}

func main() {
    str := capture(example)
    println("start", str, "end")

}

func capture(f func()) string {

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

    f()

    ChnOut := make(chan string)

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

    w.Close()
    os.Stdout = stdout
    str := <-ChnOut

    return str
}

if I miss something please let me know. I would like to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM