The most common is to write the response directly to a file using the io.writefile () function in the IO /ioutil package

But we need to use ioutil.readall (resp.body) to ReadAll the responses into memory first. If the file is too large, it consumes a lot of memory.

The IO package provides the io.copy () method, which implements copying between two files.


func main(a) {
	// Initiate an HTTP request
	res,err := http.Get("http://xxxxx.com")
	iferr! =nil{
		log.Panicln(err)
		return
	}
	// Close release
	defer res.Body.Close()
	data,dataErr:=ioutil.ReadAll(res.Body)
	ifdataErr ! =nil{
		log.Println(dataErr)
		return
	}
	// Store the requested data and receive it with a map
	result := make(map[string]interface{})
	iferr :=json.Unmarshal(data,&result); err! =nil{
		log.Println(err)
		return
	}
	Type assertion based on structured data format
	list := result["data"([]].interface{})
	for _,v := range list{
		// Type assertion
		item :=  v.(map[string]interface{})
		//// Open Goroutine to download images
		go Download(item["coverImage"]. (string))}}// Download the network image and save it to the specified local path
func Download(url string){
	// Initiate a network request
	res,err:=http.Get(url)
	iferr! =nil{
		log.Println(err)
		return
	}
	// defer releases the resource
	defer res.Body.Close()
	// Define the file name
	path := strings.Split(url,"/")
	name := path[len(path)- 1]
	// Create a file
	out,err:= os.Create("./static/img/"+name)
	iferr! =nil{
		log.Println(err)
		return
	}
	// defer the call to close the file and release the resource
	defer out.Close()
	Bufio uses buffering to improve efficiency.
	wt:=bufio.NewWriter(out)
	_,_=io.Copy(wt,res.Body)
	// Write cached data to a file
	_=wt.Flush()
}

Copy the code