Skip to content

Instantly share code, notes, and snippets.

@jlainezs
Created November 11, 2022 22:58
Show Gist options
  • Save jlainezs/e98d1a5d27592121ec5b3c1db40f01c3 to your computer and use it in GitHub Desktop.
Save jlainezs/e98d1a5d27592121ec5b3c1db40f01c3 to your computer and use it in GitHub Desktop.
Download a file using net/http
# https://golangdocs.com/golang-download-files
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
)
var (
fileName string
fullURLFile string
)
func main() {
fullURLFile = "put_your_url_here"
// Build fileName from fullPath
fileURL, err := url.Parse(fullURLFile)
if err != nil {
log.Fatal(err)
}
path := fileURL.Path
segments := strings.Split(path, "/")
fileName = segments[len(segments)-1]
// Create blank file
file, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
// Put content on file
resp, err := client.Get(fullURLFile)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
size, err := io.Copy(file, resp.Body)
defer file.Close()
fmt.Printf("Downloaded a file %s with size %d", fileName, size)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment