io.Copy
- Go course
- Intermediate
- Lesson 39/80
- 4 min
Learn to transfer data with io.Copy.
io.Copy
io.Copy(dst, src) streams data from a Reader to a Writer: it works in 32 KB chunks without loading everything into memory. Even gigabyte files are copied with constant memory.
src, _ := os.Open("buyuk.iso")
defer src.Close()
dst, _ := os.Create("kopya.iso")
defer dst.Close()
n, err := io.Copy(dst, src)
fmt.Println(n, "bayt kopyalandı")Stream chains
Combining Readers and Writers performs complex work in a single pass. For example, compressing a file while computing its hash at the same time:
h := sha256.New()
gz := gzip.NewWriter(io.MultiWriter(cikis, h))
io.Copy(gz, giris)
gz.Close()
fmt.Printf("%x\n", h.Sum(nil))io.TeeReader(r, w) writes what it reads to a Writer at the same time.
Practice Copy and hash
Copy the contents of strings.NewReader("gopher") into a bytes.Buffer with io.Copy while also writing to a sha256.New() hash through io.TeeReader. Print the number of bytes copied and the first 4 bytes of the hash with %x.
Starter code
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"strings"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"strings"
)
func main() {
h := sha256.New()
var buf bytes.Buffer
n, err := io.Copy(&buf, io.TeeReader(strings.NewReader("gopher"), h))
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%d %x\n", n, h.Sum(nil)[:4])
}Expected output
6 9cc1ee45
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which uses the least memory to send a large file in an HTTP response?
- os.ReadFile then Write
- Converting the file to a string
- io.Copy(w, f) Correct answer
- b, _ := io.ReadAll(f); w.Write(b)
Explanation: io.Copy streams piece by piece; ReadAll and ReadFile load the whole file into memory.
2 Copy by streaming
n, err := io.____(os.Stdout, strings.NewReader("merhaba"))
n, err := io.Copy(os.Stdout, strings.NewReader("merhaba"))
Explanation: io.Copy moves data from a Reader to a Writer in pieces and returns the number of bytes copied.
3 Helper and role
| Term | Meaning |
|---|---|
io.Copy |
Streaming copy |
io.TeeReader |
Duplicate while reading |
io.MultiWriter |
Duplicate while writing |
io.LimitReader |
Byte limit |