Golang io.Copy() Function

Golang io.Copy() function is “used to copy data from a source (reader) to a destination (writer) until either an error occurs or the end of the source is reached (EOF)”.

Syntax

func Copy(dst Writer, src Reader) (written int64, err error)

Parameters

  1. dst: The destination io.Writer where the data will be written.
  2. src: The source io.Reader from which the data will be read.
  3. written: The number of bytes copied from the source to the destination.
  4. err: An error if one occurred during the copy process; otherwise, it will be nil.

Example 1: How to Use io.Copy() function

package main

import (
  "fmt"
  "io"
  "os"
)

func main() {
  err := CopyFile("data.txt", "my_text_file.txt")
  if err != nil {
    fmt.Println("Error copying file:", err)
    return
  }
  fmt.Println("File copied successfully")
}

 func CopyFile(dstPath, srcPath string) error {
  // Open the source file for reading
  srcFile, err := os.Open(srcPath)
  if err != nil {
    return err
  }
  defer srcFile.Close()

  // Create the destination file for writing
  dstFile, err := os.Create(dstPath)
  if err != nil {
    return err
  }
  defer dstFile.Close()

  // Copy the data from the source file to the destination file
  _, err = io.Copy(dstFile, srcFile)
  if err != nil {
    return err
  }

  return nil
}

Output

File copied successfully

Example 2: Using the io.Copy() in a different context

Imagine you have a web server, and you want to send an image to the client when they hit a certain endpoint. We can use io.Copy() to stream the image file from the disk to the client’s browser without reading the entire image into memory first.

Here’s a simple web server using the net/http package that serves an image using io.Copy():

package main

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

func serveImage(w http.ResponseWriter, r *http.Request) {
  // Open the image file
  imageFile, err := os.Open("example.jpg")
  if err != nil {
    http.Error(w, "Could not open image", http.StatusInternalServerError)
    return
  }
  defer imageFile.Close()

  w.Header().Set("Content-Type", "image/jpeg")

  _, err = io.Copy(w, imageFile)
  if err != nil {
    http.Error(w, "Failed to send image", http.StatusInternalServerError)
    return
  }
}

func main() {
  http.HandleFunc("/image", serveImage) 

  port := 8080
  fmt.Printf("Starting server on :%d...\n", port)
  err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
  if err != nil {
    fmt.Println("Error:", err)
  }
}

When you run this program and navigate to http://localhost:8080/image in your web browser, it will serve the example.jpg image from the current directory.

The io.Copy() function is used to stream the image file from the disk to the browser, which is especially useful for large files to prevent high memory usage.

That’s it!