Reputation: 1973
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.
Upvotes: 1
Views: 1428
Reputation: 8490
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)
Upvotes: 5