package downloader import ( "errors" "fmt" "io" "os" "strings" req "github.com/levigross/grequests" "github.com/schollz/progressbar/v3" ) func handleError(err error) { fmt.Println(err.Error()) os.Exit(0) } func DownloadFile(path, url string) { resp, err := req.Head(url, nil) if err != nil { if strings.Contains(err.Error(), "no such host") { handleError(errors.New("invalid url")) } else if strings.Contains(err.Error(), "certificate signed by unknown authority") { handleError(errors.New("certificate from unknown authority")) } handleError(err) } defer resp.Close() if resp.StatusCode == 404 { handleError(errors.New("invalid url")) } else if resp.StatusCode == 401 { handleError(errors.New("restricted access (credentials required)")) } else if resp.StatusCode != 200 { handleError(errors.New(resp.RawResponse.Status)) } resp.Close() resp, err = req.Get(url, nil) if err != nil { handleError(err) } var filesize int64 if resp.RawResponse.ContentLength > -1 { filesize = resp.RawResponse.ContentLength } destFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { handleError(err) } defer destFile.Close() bar := progressbar.DefaultBytes( filesize, "downloading", ) _, err = io.Copy(io.MultiWriter(destFile, bar), resp.RawResponse.Body) if err != nil { handleError(err) } fmt.Println("Saved file to", path) } func FileExists(path string) bool { _, err := os.Stat(path) return !errors.Is(err, os.ErrNotExist) }