Go Reference ยท Errors, I/O and Files
Go io.Copy() function
Reference for Go io.Copy, CopyN and CopyBuffer: stream from a Reader to a Writer without loading it all in memory, return values, EOF handling and performance.
io.Copy(dst, src) copies everything from a reader to a writer until the reader reports io.EOF or an error occurs. It works in chunks, so it can move a multi-gigabyte file or an HTTP body while using only a small buffer.
It returns the number of bytes copied and the first error that happened. A normal end of input is not an error: io.Copy hides io.EOF and returns nil in that case.
n, err := io.Copy(dst, src)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Copy(dst Writer, src Reader) (written int64, err error) func CopyN(dst Writer, src Reader, n int64) (written int64, err error) func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
| Name | Description |
|---|---|
dst |
The writer that receives the data. |
src |
The reader to drain. |
n |
CopyN only: the exact number of bytes to copy. |
buf |
CopyBuffer only: a reusable buffer; it must not be empty (a panic otherwise). |
Returns: the number of bytes copied and the first error from reading or writing. A clean end of src gives a nil error. CopyN returns io.EOF if src had fewer than n bytes.
Usage notes
- Streaming, not buffering. Use
io.Copyinstead ofReadAllfollowed byWritefor anything of unknown or large size. - It uses shortcuts. If
srcimplementsio.WriterTo, ordstimplementsio.ReaderFrom(as*os.Fileand*bytes.Bufferdo),io.Copycalls that method, which can avoid copies or use system calls likesendfile. - Default buffer is 32 KB.
CopyBufferlets you reuse one buffer across many copies; the buffer is ignored when a shortcut applies. - Close what you open.
Copydoes not close either side. A common pattern isdefer src.Close()and checkingdst.Close()for write errors. - Copy does not rewind. A reader at EOF stays empty; seek back (
f.Seek(0, io.SeekStart)) if you need to copy again. - Limit untrusted input with
io.CopyNorio.LimitReaderso a hostile client cannot send unbounded data. - Short write errors: if the writer accepts fewer bytes than it was given without an error,
Copyreturnsio.ErrShortWrite.