version: 1.10

package io

import "io"

Overview

Package io provides basic interfaces to I/O primitives. Its primary job is to
wrap existing implementations of such primitives, such as those in package os,
into shared public interfaces that abstract the functionality, plus some other
related primitives.

Because these interfaces and primitives wrap lower-level operations with various
implementations, unless otherwise informed clients should not assume they are
safe for parallel execution.

Index

Examples

Package files

io.go multi.go pipe.go

Constants

  1. const (
  2. SeekStart = 0 // seek relative to the origin of the file
  3. SeekCurrent = 1 // seek relative to the current offset
  4. SeekEnd = 2 // seek relative to the end
  5. )

Seek whence values.

Variables

  1. var EOF = errors.New("EOF")

EOF is the error returned by Read when no more input is available. Functions
should return EOF only to signal a graceful end of input. If the EOF occurs
unexpectedly in a structured data stream, the appropriate error is either
ErrUnexpectedEOF or some other error giving more detail.

  1. var ErrClosedPipe = errors.New("io: read/write on closed pipe")

ErrClosedPipe is the error used for read or write operations on a closed pipe.

  1. var ErrNoProgress = errors.New("multiple Read calls return no data or error")

ErrNoProgress is returned by some clients of an io.Reader when many calls to
Read have failed to return any data or error, usually the sign of a broken
io.Reader implementation.

  1. var ErrShortBuffer = errors.New("short buffer")

ErrShortBuffer means that a read required a longer buffer than was provided.

  1. var ErrShortWrite = errors.New("short write")

ErrShortWrite means that a write accepted fewer bytes than requested but failed
to return an explicit error.

  1. var ErrUnexpectedEOF = errors.New("unexpected EOF")

ErrUnexpectedEOF means that EOF was encountered in the middle of reading a
fixed-size block or data structure.

func Copy

  1. func Copy(dst Writer, src Reader) (written int64, err error)

Copy copies from src to dst until either EOF is reached on src or an error
occurs. It returns the number of bytes copied and the first error encountered
while copying, if any.

A successful Copy returns err == nil, not err == EOF. Because Copy is defined to
read from src until EOF, it does not treat an EOF from Read as an error to be
reported.

If src implements the WriterTo interface, the copy is implemented by calling
src.WriteTo(dst). Otherwise, if dst implements the ReaderFrom interface, the
copy is implemented by calling dst.ReadFrom(src).


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. if _, err := io.Copy(os.Stdout, r); err != nil {
  3. log.Fatal(err)
  4. }
  5. // Output:
  6. // some io.Reader stream to be read

func CopyBuffer

  1. func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)

CopyBuffer is identical to Copy except that it stages through the provided
buffer (if one is required) rather than allocating a temporary one. If buf is
nil, one is allocated; otherwise if it has zero length, CopyBuffer panics.


Example:

  1. r1 := strings.NewReader("first reader\n")
  2. r2 := strings.NewReader("second reader\n")
  3. buf := make([]byte, 8)
  4. // buf is used here...
  5. if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
  6. log.Fatal(err)
  7. }
  8. // ... reused here also. No need to allocate an extra buffer.
  9. if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
  10. log.Fatal(err)
  11. }
  12. // Output:
  13. // first reader
  14. // second reader

func CopyN

  1. func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

CopyN copies n bytes (or until an error) from src to dst. It returns the number
of bytes copied and the earliest error encountered while copying. On return,
written == n if and only if err == nil.

If dst implements the ReaderFrom interface, the copy is implemented using it.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read")
  2. if _, err := io.CopyN(os.Stdout, r, 5); err != nil {
  3. log.Fatal(err)
  4. }
  5. // Output:
  6. // some

func ReadAtLeast

  1. func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)

ReadAtLeast reads from r into buf until it has read at least min bytes. It
returns the number of bytes copied and an error if fewer bytes were read. The
error is EOF only if no bytes were read. If an EOF happens after reading fewer
than min bytes, ReadAtLeast returns ErrUnexpectedEOF. If min is greater than the
length of buf, ReadAtLeast returns ErrShortBuffer. On return, n >= min if and
only if err == nil.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. buf := make([]byte, 33)
  3. if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
  4. log.Fatal(err)
  5. }
  6. fmt.Printf("%s\n", buf)
  7. // buffer smaller than minimal read size.
  8. shortBuf := make([]byte, 3)
  9. if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
  10. fmt.Println("error:", err)
  11. }
  12. // minimal read size bigger than io.Reader stream
  13. longBuf := make([]byte, 64)
  14. if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
  15. fmt.Println("error:", err)
  16. }
  17. // Output:
  18. // some io.Reader stream to be read
  19. //
  20. // error: short buffer
  21. // error: EOF

func ReadFull

  1. func ReadFull(r Reader, buf []byte) (n int, err error)

ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of
bytes copied and an error if fewer bytes were read. The error is EOF only if no
bytes were read. If an EOF happens after reading some but not all the bytes,
ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err
== nil.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. buf := make([]byte, 4)
  3. if _, err := io.ReadFull(r, buf); err != nil {
  4. log.Fatal(err)
  5. }
  6. fmt.Printf("%s\n", buf)
  7. // minimal read size bigger than io.Reader stream
  8. longBuf := make([]byte, 64)
  9. if _, err := io.ReadFull(r, longBuf); err != nil {
  10. fmt.Println("error:", err)
  11. }
  12. // Output:
  13. // some
  14. // error: unexpected EOF

func WriteString

  1. func WriteString(w Writer, s string) (n int, err error)

WriteString writes the contents of the string s to w, which accepts a slice of
bytes. If w implements a WriteString method, it is invoked directly. Otherwise,
w.Write is called exactly once.


Example:

  1. io.WriteString(os.Stdout, "Hello World")
  2. // Output: Hello World

type ByteReader

  1. type ByteReader interface {
  2. ReadByte() (byte, error)
  3. }

ByteReader is the interface that wraps the ReadByte method.

ReadByte reads and returns the next byte from the input or any error
encountered. If ReadByte returns an error, no input byte was consumed, and the
returned byte value is undefined.

type ByteScanner

  1. type ByteScanner interface {
  2. ByteReader
  3. UnreadByte() error
  4. }

ByteScanner is the interface that adds the UnreadByte method to the basic
ReadByte method.

UnreadByte causes the next call to ReadByte to return the same byte as the
previous call to ReadByte. It may be an error to call UnreadByte twice without
an intervening call to ReadByte.

type ByteWriter

  1. type ByteWriter interface {
  2. WriteByte(c byte) error
  3. }

ByteWriter is the interface that wraps the WriteByte method.

type Closer

  1. type Closer interface {
  2. Close() error
  3. }

Closer is the interface that wraps the basic Close method.

The behavior of Close after the first call is undefined. Specific
implementations may document their own behavior.

type LimitedReader

  1. type LimitedReader struct {
  2. R Reader // underlying reader
  3. N int64 // max bytes remaining
  4. }

A LimitedReader reads from R but limits the amount of data returned to just N
bytes. Each call to Read updates N to reflect the new amount remaining. Read
returns EOF when N <= 0 or when the underlying R returns EOF.

func (*LimitedReader) Read

  1. func (l *LimitedReader) Read(p []byte) (n int, err error)

type PipeReader

  1. type PipeReader struct {
  2. // contains filtered or unexported fields
  3. }

A PipeReader is the read half of a pipe.

func Pipe

  1. func Pipe() (*PipeReader, *PipeWriter)

Pipe creates a synchronous in-memory pipe. It can be used to connect code
expecting an io.Reader with code expecting an io.Writer.

Reads and Writes on the pipe are matched one to one except when multiple Reads
are needed to consume a single Write. That is, each Write to the PipeWriter
blocks until it has satisfied one or more Reads from the PipeReader that fully
consume the written data. The data is copied directly from the Write to the
corresponding Read (or Reads); there is no internal buffering.

It is safe to call Read and Write in parallel with each other or with Close.
Parallel calls to Read and parallel calls to Write are also safe: the individual
calls will be gated sequentially.


Example:

  1. r, w := io.Pipe()
  2. go func() {
  3. fmt.Fprint(w, "some text to be read\n")
  4. w.Close()
  5. }()
  6. buf := new(bytes.Buffer)
  7. buf.ReadFrom(r)
  8. fmt.Print(buf.String())
  9. // Output:
  10. // some text to be read

func (*PipeReader) Close

  1. func (r *PipeReader) Close() error

Close closes the reader; subsequent writes to the write half of the pipe will
return the error ErrClosedPipe.

func (*PipeReader) CloseWithError

  1. func (r *PipeReader) CloseWithError(err error) error

CloseWithError closes the reader; subsequent writes to the write half of the
pipe will return the error err.

func (*PipeReader) Read

  1. func (r *PipeReader) Read(data []byte) (n int, err error)

Read implements the standard Read interface: it reads data from the pipe,
blocking until a writer arrives or the write end is closed. If the write end is
closed with an error, that error is returned as err; otherwise err is EOF.

type PipeWriter

  1. type PipeWriter struct {
  2. // contains filtered or unexported fields
  3. }

A PipeWriter is the write half of a pipe.

func (*PipeWriter) Close

  1. func (w *PipeWriter) Close() error

Close closes the writer; subsequent reads from the read half of the pipe will
return no bytes and EOF.

func (*PipeWriter) CloseWithError

  1. func (w *PipeWriter) CloseWithError(err error) error

CloseWithError closes the writer; subsequent reads from the read half of the
pipe will return no bytes and the error err, or EOF if err is nil.

CloseWithError always returns nil.

func (*PipeWriter) Write

  1. func (w *PipeWriter) Write(data []byte) (n int, err error)

Write implements the standard Write interface: it writes data to the pipe,
blocking until one or more readers have consumed all the data or the read end is
closed. If the read end is closed with an error, that err is returned as err;
otherwise err is ErrClosedPipe.

type ReadCloser

  1. type ReadCloser interface {
  2. Reader
  3. Closer
  4. }

ReadCloser is the interface that groups the basic Read and Close methods.

type ReadSeeker

  1. type ReadSeeker interface {
  2. Reader
  3. Seeker
  4. }

ReadSeeker is the interface that groups the basic Read and Seek methods.

type ReadWriteCloser

  1. type ReadWriteCloser interface {
  2. Reader
  3. Writer
  4. Closer
  5. }

ReadWriteCloser is the interface that groups the basic Read, Write and Close
methods.

type ReadWriteSeeker

  1. type ReadWriteSeeker interface {
  2. Reader
  3. Writer
  4. Seeker
  5. }

ReadWriteSeeker is the interface that groups the basic Read, Write and Seek
methods.

type ReadWriter

  1. type ReadWriter interface {
  2. Reader
  3. Writer
  4. }

ReadWriter is the interface that groups the basic Read and Write methods.

type Reader

  1. type Reader interface {
  2. Read(p []byte) (n int, err error)
  3. }

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <=
n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may
use all of p as scratch space during the call. If some data is available but not
len(p) bytes, Read conventionally returns what is available instead of waiting
for more.

When Read encounters an error or end-of-file condition after successfully
reading n > 0 bytes, it returns the number of bytes read. It may return the
(non-nil) error from the same call or return the error (and n == 0) from a
subsequent call. An instance of this general case is that a Reader returning a
non-zero number of bytes at the end of the input stream may return either err ==
EOF or err == nil. The next Read should return 0, EOF.

Callers should always process the n > 0 bytes returned before considering the
error err. Doing so correctly handles I/O errors that happen after reading some
bytes and also both of the allowed EOF behaviors.

Implementations of Read are discouraged from returning a zero byte count with a
nil error, except when len(p) == 0. Callers should treat a return of 0 and nil
as indicating that nothing happened; in particular it does not indicate EOF.

Implementations must not retain p.

func LimitReader

  1. func LimitReader(r Reader, n int64) Reader

LimitReader returns a Reader that reads from r but stops with EOF after n bytes.
The underlying implementation is a *LimitedReader.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. lr := io.LimitReader(r, 4)
  3. if _, err := io.Copy(os.Stdout, lr); err != nil {
  4. log.Fatal(err)
  5. }
  6. // Output:
  7. // some

func MultiReader

  1. func MultiReader(readers ...Reader) Reader

MultiReader returns a Reader that’s the logical concatenation of the provided
input readers. They’re read sequentially. Once all inputs have returned EOF,
Read will return EOF. If any of the readers return a non-nil, non-EOF error,
Read will return that error.


Example:

  1. r1 := strings.NewReader("first reader ")
  2. r2 := strings.NewReader("second reader ")
  3. r3 := strings.NewReader("third reader\n")
  4. r := io.MultiReader(r1, r2, r3)
  5. if _, err := io.Copy(os.Stdout, r); err != nil {
  6. log.Fatal(err)
  7. }
  8. // Output:
  9. // first reader second reader third reader

func TeeReader

  1. func TeeReader(r Reader, w Writer) Reader

TeeReader returns a Reader that writes to w what it reads from r. All reads from
r performed through it are matched with corresponding writes to w. There is no
internal buffering - the write must complete before the read completes. Any
error encountered while writing is reported as a read error.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. var buf bytes.Buffer
  3. tee := io.TeeReader(r, &buf)
  4. printall := func(r io.Reader) {
  5. b, err := ioutil.ReadAll(r)
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9. fmt.Printf("%s", b)
  10. }
  11. printall(tee)
  12. printall(&buf)
  13. // Output:
  14. // some io.Reader stream to be read
  15. // some io.Reader stream to be read

type ReaderAt

  1. type ReaderAt interface {
  2. ReadAt(p []byte, off int64) (n int, err error)
  3. }

ReaderAt is the interface that wraps the basic ReadAt method.

ReadAt reads len(p) bytes into p starting at offset off in the underlying input
source. It returns the number of bytes read (0 <= n <= len(p)) and any error
encountered.

When ReadAt returns n < len(p), it returns a non-nil error explaining why more
bytes were not returned. In this respect, ReadAt is stricter than Read.

Even if ReadAt returns n < len(p), it may use all of p as scratch space during
the call. If some data is available but not len(p) bytes, ReadAt blocks until
either all the data is available or an error occurs. In this respect ReadAt is
different from Read.

If the n = len(p) bytes returned by ReadAt are at the end of the input source,
ReadAt may return either err == EOF or err == nil.

If ReadAt is reading from an input source with a seek offset, ReadAt should not
affect nor be affected by the underlying seek offset.

Clients of ReadAt can execute parallel ReadAt calls on the same input source.

Implementations must not retain p.

type ReaderFrom

  1. type ReaderFrom interface {
  2. ReadFrom(r Reader) (n int64, err error)
  3. }

ReaderFrom is the interface that wraps the ReadFrom method.

ReadFrom reads data from r until EOF or error. The return value n is the number
of bytes read. Any error except io.EOF encountered during the read is also
returned.

The Copy function uses ReaderFrom if available.

type RuneReader

  1. type RuneReader interface {
  2. ReadRune() (r rune, size int, err error)
  3. }

RuneReader is the interface that wraps the ReadRune method.

ReadRune reads a single UTF-8 encoded Unicode character and returns the rune and
its size in bytes. If no character is available, err will be set.

type RuneScanner

  1. type RuneScanner interface {
  2. RuneReader
  3. UnreadRune() error
  4. }

RuneScanner is the interface that adds the UnreadRune method to the basic
ReadRune method.

UnreadRune causes the next call to ReadRune to return the same rune as the
previous call to ReadRune. It may be an error to call UnreadRune twice without
an intervening call to ReadRune.

type SectionReader

  1. type SectionReader struct {
  2. // contains filtered or unexported fields
  3. }

SectionReader implements Read, Seek, and ReadAt on a section of an underlying
ReaderAt.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. s := io.NewSectionReader(r, 5, 17)
  3. if _, err := io.Copy(os.Stdout, s); err != nil {
  4. log.Fatal(err)
  5. }
  6. // Output:
  7. // io.Reader stream

func NewSectionReader

  1. func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader

NewSectionReader returns a SectionReader that reads from r starting at offset
off and stops with EOF after n bytes.

func (*SectionReader) Read

  1. func (s *SectionReader) Read(p []byte) (n int, err error)

func (*SectionReader) ReadAt

  1. func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. s := io.NewSectionReader(r, 5, 16)
  3. buf := make([]byte, 6)
  4. if _, err := s.ReadAt(buf, 10); err != nil {
  5. log.Fatal(err)
  6. }
  7. fmt.Printf("%s\n", buf)
  8. // Output:
  9. // stream

func (*SectionReader) Seek

  1. func (s *SectionReader) Seek(offset int64, whence int) (int64, error)


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. s := io.NewSectionReader(r, 5, 16)
  3. if _, err := s.Seek(10, io.SeekStart); err != nil {
  4. log.Fatal(err)
  5. }
  6. buf := make([]byte, 6)
  7. if _, err := s.Read(buf); err != nil {
  8. log.Fatal(err)
  9. }
  10. fmt.Printf("%s\n", buf)
  11. // Output:
  12. // stream

func (*SectionReader) Size

  1. func (s *SectionReader) Size() int64

Size returns the size of the section in bytes.

type Seeker

  1. type Seeker interface {
  2. Seek(offset int64, whence int) (int64, error)
  3. }

Seeker is the interface that wraps the basic Seek method.

Seek sets the offset for the next Read or Write to offset, interpreted according
to whence: SeekStart means relative to the start of the file, SeekCurrent means
relative to the current offset, and SeekEnd means relative to the end. Seek
returns the new offset relative to the start of the file and an error, if any.

Seeking to an offset before the start of the file is an error. Seeking to any
positive offset is legal, but the behavior of subsequent I/O operations on the
underlying object is implementation-dependent.

type WriteCloser

  1. type WriteCloser interface {
  2. Writer
  3. Closer
  4. }

WriteCloser is the interface that groups the basic Write and Close methods.

type WriteSeeker

  1. type WriteSeeker interface {
  2. Writer
  3. Seeker
  4. }

WriteSeeker is the interface that groups the basic Write and Seek methods.

type Writer

  1. type Writer interface {
  2. Write(p []byte) (n int, err error)
  3. }

Writer is the interface that wraps the basic Write method.

Write writes len(p) bytes from p to the underlying data stream. It returns the
number of bytes written from p (0 <= n <= len(p)) and any error encountered that
caused the write to stop early. Write must return a non-nil error if it returns
n < len(p). Write must not modify the slice data, even temporarily.

Implementations must not retain p.

func MultiWriter

  1. func MultiWriter(writers ...Writer) Writer

MultiWriter creates a writer that duplicates its writes to all the provided
writers, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time. If a listed writer
returns an error, that overall write operation stops and returns the error; it
does not continue down the list.


Example:

  1. r := strings.NewReader("some io.Reader stream to be read\n")
  2. var buf1, buf2 bytes.Buffer
  3. w := io.MultiWriter(&buf1, &buf2)
  4. if _, err := io.Copy(w, r); err != nil {
  5. log.Fatal(err)
  6. }
  7. fmt.Print(buf1.String())
  8. fmt.Print(buf2.String())
  9. // Output:
  10. // some io.Reader stream to be read
  11. // some io.Reader stream to be read

type WriterAt

  1. type WriterAt interface {
  2. WriteAt(p []byte, off int64) (n int, err error)
  3. }

WriterAt is the interface that wraps the basic WriteAt method.

WriteAt writes len(p) bytes from p to the underlying data stream at offset off.
It returns the number of bytes written from p (0 <= n <= len(p)) and any error
encountered that caused the write to stop early. WriteAt must return a non-nil
error if it returns n < len(p).

If WriteAt is writing to a destination with a seek offset, WriteAt should not
affect nor be affected by the underlying seek offset.

Clients of WriteAt can execute parallel WriteAt calls on the same destination if
the ranges do not overlap.

Implementations must not retain p.

type WriterTo

  1. type WriterTo interface {
  2. WriteTo(w Writer) (n int64, err error)
  3. }

WriterTo is the interface that wraps the WriteTo method.

WriteTo writes data to w until there’s no more data to write or when an error
occurs. The return value n is the number of bytes written. Any error encountered
during the write is also returned.

The Copy function uses WriterTo if available.

Subdirectories