A handy tool that will suit your purpose can be found in the standard library: bytes.Buffer
(see the package docs).
Say you have an object that implements io.Reader
(that is, it has a method with the signature Read([]byte) (int, os.Error)
).
A common example is an os.File
:
f, err := os.Open("/etc/passwd", os.O_RDONLY, 0644)
If you wanted to read the contents of that file into a string, simply create a bytes.Buffer
(its zero-value is a ready-to-use buffer, so you don't need to call a constructor):
var b bytes.Buffer
Use io.Copy
to copy the file's contents into the buffer:
n, err := io.Copy(b, f)
(An alternative to using io.Copy
would be b.ReadFrom(f)
- they're more or less the same.)
And call the buffer's String method to retrieve the buffer's contents as a string:
s := b.String()
The bytes.Buffer
will automatically grow to store the contents of the file, so you don't need to worry about allocating and growing byte
slices, etc.