Golang io.Pipe 与 node.js 管道

标签 go pipe

我是 golang 的新手,我在理解 go 的 io.Pipe 时遇到了问题。这类似于 node.js 的 .pipe 吗?我应该如何使用它?是否可以将它与 1 个读取文件和一个写入文件一起使用?

提前谢谢大家。

最佳答案

不,它们并不完全相似。 io.Copy(dat io.Writer, src io.Reader) 足以读写文件,如下所示:

input := bufio.NewReader(os.Stdin)
output := bufio.NewWriter(os.Stdout) // buffer output like C stdlib
io.Copy(output, input)               // copy entire file
output.Flush()

io.Pipe() (*PipeReader, *PipeWriter) 将在您拥有 时为您生成管道 ReaderWriter不是他们而是代码期望他们,像这样:

type id struct{
  name string
  age int
}

payload := id{"John", 25}     
requestBody, jsonPayload := io.Pipe()
request := http.NewRequest("POST". "http://www.example.com", requestBody) // NewRequest expect io.Reader
encoder := json.NewEncoder(jsonPayload) // NewEncoder expect io.Writer
err := encoder.Encode(payload)
response, err := client.Do(request)

关于Golang io.Pipe 与 node.js 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27994368/

相关文章:

json - 在 Go 中表示此 JSON 的最佳方式?

go - 将工作外包出去,但限制 worker 数量

c - 如何使用popen?

bash 权限被拒绝 : Can't echo to the stdin of a running process?

Go no install location for directory outside GOPATH 运行时出错 "go get"

go - 如何在 Go 中 gc 互斥映射?

go - 使用 'go build' 获取依赖项,即使它们位于 vendor/中

python - 子进程通信 : order matters?

c - 如果从管道读取时 tail 失败怎么办

Python 子进程 : how to use pipes thrice?