add dl.go

Commit 56105a991f79 · konakona · 2026-10-21 23:50 +0700

Changeset
56105a991f7994542b7bdf9946419313c610be39

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/dl.go b/dl.go
new file mode 100644
--- /dev/null
+++ b/dl.go
@@ -0,0 +1,22 @@
+package main
+
+import (
+	"fmt"
+	"os"
+)
+
+func main() {
+	if len(os.Args) < 2 {
+		fmt.Println("Use the correct syntax: dl <URL>")
+		fmt.Println("Example: dl https://example.com/file.tar.xz")
+		os.Exit(1)
+	}
+
+	targetURL := os.Args[1]
+
+	err := DownloadFile(targetURL)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
+		os.Exit(1)
+	}
+}
diff --git a/download.go b/download.go
new file mode 100644
--- /dev/null
+++ b/download.go
@@ -0,0 +1,44 @@
+package main
+
+import (
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+)
+
+func DownloadFile(rawURL string) error {
+	fmt.Printf("Connecting to: %s\n", rawURL)
+
+	resp, err := http.Get(rawURL)
+	if err != nil {
+		return fmt.Errorf("can't connect to URL: %v", err)
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode != http.StatusOK {
+		return fmt.Errorf("server returned an HTTP error status: %s", resp.Status)
+	}
+
+	filename := ExtractFilename(rawURL)
+	fmt.Printf("Saving as: %s\n", filename)
+
+	out, err := os.Create(filename)
+	if err != nil {
+		return fmt.Errorf("Can't create file: %v", err)
+	}
+	defer out.Close()
+
+	counter := &ProgressWriter{
+		Writer: out,
+		Total: resp.ContentLength,
+	}
+
+	_, err = io.Copy(counter, resp.Body)
+	if err != nil {
+		return fmt.Errorf("Error while download file: %v", err)
+	}
+
+	fmt.Println("\n[Success] File downloaded")
+	return nil
+}
diff --git a/go.mod b/go.mod
new file mode 100644
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module dl
+
+go 1.27.2
diff --git a/utils.go b/utils.go
new file mode 100644
--- /dev/null
+++ b/utils.go
@@ -0,0 +1,42 @@
+package main
+
+import (
+	"fmt"
+	"io"
+	"net/url"
+	"path"
+)
+
+type ProgressWriter struct {
+	io.Writer
+	Total int64
+	Written int64
+}
+
+func (pw *ProgressWriter) Write(p []byte) (int, error) {
+	n, err := pw.Writer.Write(p)
+	pw.Written += int64(n)
+
+	if pw.Total > 0 {
+		percentage := float64(pw.Written)
+		fmt.Printf("\r[Downloading] %d / %d bytes (%.2f%%)", pw.Written, pw.Total, percentage)
+	} else {
+		fmt.Printf("\r[Downloading] %d bytes downloaded", pw.Written)
+	}
+
+return n, err
+}
+
+func ExtractFilename(rawURL string) string {
+	parsed, err := url.Parse(rawURL)
+	if err != nil {
+		return "downloaded_file"
+	}
+
+	filename := path.Base(parsed.Path)
+	if filename == "" || filename == "." || filename == "/" {
+		return "downloaded_file"
+	}
+
+return filename
+}