Go Tip: Copy a Reader Into a Writer

Programming Jun 16, 2020

Something so simple, and yet, so easy to forget right when you need it. How does one exhaustively read from a Reader and write to a Writer at the same time? One way is to set up a []byte buffer, use to read a chunk from the Reader, write the chunk to the Writer and loop over, until there are no more bytes left to read:

buf = make([]byte, size)

for {
        nr, err := src.Read(buf)
        //break, if no more bytes left
        //...
        nw, err := dst.Write(buf[0:nr])
        //...
}

Or, you could simply use io.Copy from the Go Standard Library.

io.Copy to the rescue. I can best demonstrate it with a small HTTP server, where the contents of a JSON is being written directly into the HTTP response:

package main

import (
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	log.Panic(http.ListenAndServe(":8080", http.HandlerFunc(handle)))
}

func handle(w http.ResponseWriter, r *http.Request) {
	fp, err := os.Open("store.json")
	defer fp.Close()
	if err != nil {
		log.Printf("ERR: %s", err)
	}

	io.Copy(w, fp)
}

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.