Go Package io
External
Internal
Overview
The io package consists of a few functions, but mostly interfaces used by other packages.
io.EOF
The error returned by I/O operations that encounter the end of file. It can be tested with:
_, err := ...
if errors.Is(err, io.EOF) {
// is EOF
...
}
io.Reader
An interface that exposes Read()
.
Reader
s can be used to unmarshall JSON into structs as shown here:
Files opened with os.Create()
implement io.Reader
.
Wrapping a []byte into a Reader
A []byte
can be wrapped into a Reader
with:
import "bytes"
bs := []byte("something")
r := bytes.NewReader(bs)
Getting a Reader from a string
s := "some string"
reader := strings.NewReader(s)
io.Writer
io.Writer
is the interface that wraps the basic Write method:
Write(p []byte) (n int, err error)
Write()
writes the given bytes to the underlying data stream.
Files opened with os.Create()
implement io.Writer
.
Capturing the Content Written into a Writer and Converting to String
bytes.Buffer
implements io.Writer
so a bytes.Buffer
instance can be used to be written into and get the string representation. The following example dumps the content of a net/http.Request
into a string, identically with how it will be sent over the wire:
var r = &http.Request{...}
b := &bytes.Buffer{}
if err := r.Write(b); err != nil { ... }
s := b.String()
Closer
Files opened with os.Create()
implement io.Closer
.
ReadCloser
An interface that exposes basic Read()
and Close()
methods. The http.Request
body is a ReadCloser
. See Reader
.