Golang的io.Pipe与node.js的Pipe比较

huangapple go评论85阅读模式
英文:

Golang io.Pipe vs node.js Pipe

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对Go语言还不熟悉,我在理解Go的io.Pipe时遇到了问题。这个和Node.js的.pipe类似吗?我应该如何使用它?能否将其用于一个读取文件和一个写入文件的操作?

提前感谢大家。

英文:

I'm new to golang and I'm having problem understanding go's io.Pipe. Is this similar to node.js' .pipe? And how should I use it? Is it possible to use it with 1 read file and a write file?

Thank in advance guys.

答案1

得分: 5

不,它们并不完全相似。io.Copy(dat io.Writer, src io.Reader)足以用于读取和写入文件,就像这样:

input := bufio.NewReader(os.Stdin)
output := bufio.NewWriter(os.Stdout) // 像C标准库一样缓冲输出
io.Copy(output, input)               // 复制整个文件
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期望io.Reader
encoder := json.NewEncoder(jsonPayload) // NewEncoder期望io.Writer
err := encoder.Encode(payload)
response, err := client.Do(request)
英文:

No, they are not precisely similar. io.Copy(dat io.Writer, src io.Reader) is quite enough to read and write files, like this:

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) will produce piped Reader and Writer for you when you have not them but code expect them, like this:

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)

huangapple
  • 本文由 发表于 2015年1月17日 07:23:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/27994368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定