How to Download a File with HTTP in Go

Web
Download a file in Go using net/http.Get and io.Copy to save the response body to disk.

Use the net/http package's Get function to download a file and write the response body to a local file.

package main

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

func main() {
	resp, err := http.Get("https://example.com/file.txt")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	out, err := os.Create("file.txt")
	if err != nil {
		panic(err)
	}
	defer out.Close()

	io.Copy(out, resp.Body)
}