SoFunction
Updated on 2025-03-04

Example of a method to download network pictures or files in Go language

I've been free recently, so I simply learned the basic usage of Go. Since practice is the fastest way to learn, here we start by downloading online pictures or files to learn Go language

When downloading files to the local area, the usual idea is to first obtain the input stream of network files and the output stream of local files, and then read the input stream into the output stream. Therefore, we naturally need to obtain the corresponding Reader and Writer.

The first thing is to use GoLang's() method (the principle of using client's do method is similar)

// Take the picture of Huapean.com as an example  imgUrl := "http://hbimg./32f065b3afb3fb36b75a5cbc90051b1050e1e6b6e199-Ml6q9F_fw320"

  res, err := (imgUrl)
  if err != nil {
    ("A error occurred!")
    return
  }
  // The defer is a delay operation, which is usually used to release related variables  defer ()

Then get the reader object of the get request response

// Get the reader object for the get request response  reader := (, 32 * 1024)

The reader object of the input stream is obtained above, and the writer object of the output stream of the local file is obtained below.

imgPath := "C:\\Users\\Asche\\go\\src\\GoSpiderTest\\"
  // Get the file name according to the image url  fileName := (imgUrl)


    file, err := (imgPath + fileName)
  if err != nil {
    panic(err)
  }
  // Obtain the file's writer object  writer := (file)

OK, both reader and writer objects are obtained and then read and write.

If you find it troublesome, you can copy it directly:

written, _ := (writer, reader)
  // Output file byte size  ("Total length: %d", written)

Or manually read and write

bytes := make([]byte, 32 * 1024)
  for {
    len, err := (bytes)

    if len < 0 || err != nil{
      return
    }
    // Note the [0:len] after the byte array here, otherwise it may cause unnecessary data to be written    _, _ = (bytes[0:len])
    ("%d ", len)
  }

OK, download is completed.

The complete code is posted below (the method used to read and write)

package main

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

func main() {
  imgPath := "C:\\Users\\Asche\\go\\src\\GoSpiderTest\\"
  imgUrl := "http://hbimg./32f065b3afb3fb36b75a5cbc90051b1050e1e6b6e199-Ml6q9F_fw320"

  fileName := (imgUrl)


  res, err := (imgUrl)
  if err != nil {
    ("A error occurred!")
    return
  }
  defer ()
  // Get the reader object for the get request response  reader := (, 32 * 1024)


  file, err := (imgPath + fileName)
  if err != nil {
    panic(err)
  }
  // Obtain the file's writer object  writer := (file)

  written, _ := (writer, reader)
  ("Total length: %d", written)
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.