summary refs log tree commit diff stats
path: root/background/download.go
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2020-03-24 18:35:27 +0530
committerAndinus <andinus@nand.sh>2020-03-24 18:35:27 +0530
commitbf040f6d1c8c7bc33d5268db42bc2ac9016e2198 (patch)
tree76006187821bd925a1509af614e4cecbef449133 /background/download.go
parent842bc9065905e8fcbd0e801526306407ac6793c4 (diff)
downloadcetus-bf040f6d1c8c7bc33d5268db42bc2ac9016e2198.tar.gz
Add background package
This rewrite has better comments and returns better error messages.
Diffstat (limited to 'background/download.go')
-rw-r--r--background/download.go48
1 files changed, 48 insertions, 0 deletions
diff --git a/background/download.go b/background/download.go
new file mode 100644
index 0000000..50f22c5
--- /dev/null
+++ b/background/download.go
@@ -0,0 +1,48 @@
+package background
+
+import (
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+)
+
+// Download takes path and url as input and downloads the data to a
+// file, returning an error if there is one.
+func Download(file string, url string) error {
+	o, err := os.Create(file)
+	if err != nil {
+		err = fmt.Errorf("%s%s\n%s",
+			"download.go: failed to create file: ", file,
+			err.Error())
+		return err
+	}
+	defer o.Close()
+
+	res, err := http.Get(url)
+	if err != nil {
+		err = fmt.Errorf("%s%s\n%s",
+			"download.go: failed to get response from ", url,
+			err.Error())
+		return err
+	}
+	defer res.Body.Close()
+
+	// Return an error on unexpected response code.
+	if res.StatusCode != http.StatusOK {
+		err = fmt.Errorf("Unexpected Response: %s",
+			res.Status)
+		return err
+	}
+
+	// This will not copy everything to memory but will save to
+	// disk as it progresses, ideal for big files or low memory
+	// environments.
+	_, err = io.Copy(o, res.Body)
+	if err != nil {
+		err = fmt.Errorf("%s\n%s",
+			"download.go: failed to copy body to file",
+			err.Error())
+	}
+	return err
+}