Go Tip: Copy a Reader Into a Writer


1 min read

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)
}

Related Articles

This Week in Elixir and Erlang #5
4 min read
This Week in Elixir and Erlang #4
3 min read
This Week in Elixir and Erlang #3
3 min read
This Week in Elixir and Erlang #2
4 min read
This Week in Elixir and Erlang
2 min read
Elixir Tip: Case vs. With
3 min read

GO TOP