Copying from one stream to another

There are three main functions in the io package that make it possible to transfer data from a writer to a reader. This is a very common scenario; you could be writing the contents from a file opened for reading to another file opened for writing, for instance, or draining a buffer and writing its content as standard output.

We already saw how to use the io.Copy function on a file to simulate the behavior of the cp command in Chapter 4, Working with the Filesystem. This behavior can be extended to any sort of reader and writer implementation, from buffers to network connections.

If the writer is also an io.WriterTo interface, the copy calls the WriteTo method. If not, it executes a series of writes using a buffer of fixed size (32 KB). If the operation ends with the io.EOF value, no error is returned. A common case scenario is the bytes.Buffer struct, which is capable of writing its content to another writer and will behave accordingly. Alternatively, if the destination is an io.ReaderFrom interface, the ReadFrom method is executed.

If the interface is a simple io.Writer interface, this method uses a temporary buffer that will be cleaned afterwards. To avoid wasting computing power on garbage collection, and maybe reuse the same buffers, there's another function—the io.CopyBuffer function. This has an additional argument, and a new buffer gets allocated only if this extra argument is nil.

The last function is io.CopyN, which works exactly like io.Copy but makes it possible to specify a limit to the number of bytes to be written to the extra argument. If the reader is also io.Seeker, it can be useful to write partial content—the seeker first moves the cursor to the correct offset, then a certain number of bytes is written.

Let's make an example of copying n bytes at once:

func CopyNOffset(dst io.Writer, src io.ReadSeeker, offset, length int64) (int64, error) {
if _, err := src.Seek(offset, io.SeekStart); err != nil {
return 0, err
}
return io.CopyN(dst, src, length)
}

The full example is available at https://play.golang.org/p/8wCqGXp5mSZ.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.46.58