Building a File Downloader in Go

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Step 1: Import Required Packages
  5. Step 2: Get User Input for Download URL and Destination Path
  6. Step 3: Download the File
  7. Step 4: Handle Errors
  8. Step 5: Build and Run the Program
  9. Recap

Introduction

In this tutorial, we will learn how to build a file downloader in Go. We will use the Go programming language to write a script that allows users to input a URL to download a file and specify a destination path. The script will then download the file from the given URL and save it to the specified path on the local machine.

By the end of this tutorial, you will have a working file downloader written in Go that you can use to download files from any given URL.

Prerequisites

To follow along with this tutorial, you will need:

  • Basic knowledge of the Go programming language
  • Go installed on your machine

Setup

Before we begin, make sure you have Go installed on your machine. You can download and install Go from the official website (https://golang.org/dl/).

Step 1: Import Required Packages

First, let’s import the necessary packages for our file downloader. We will need the net/http package to perform HTTP requests and the io package to handle file operations.

package main

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

Step 2: Get User Input for Download URL and Destination Path

Next, let’s prompt the user to enter the URL of the file they want to download and the destination path where they want to save the file.

func getUserInput() (string, string) {
    var url, path string
    fmt.Print("Enter the URL of the file: ")
    fmt.Scanln(&url)
    fmt.Print("Enter the destination path: ")
    fmt.Scanln(&path)
    return url, path
}

In this function, we use the fmt.Scanln function to read user input from the console. The URL and destination path are then returned as strings.

Step 3: Download the File

Now, let’s implement the downloading logic. We will define a function named downloadFile that takes the URL and destination path as input and performs the file download.

func downloadFile(url, path string) error {
    // Create the file
    file, err := os.Create(path)
    if err != nil {
        return err
    }
    defer file.Close()

    // Download the file
    response, err := http.Get(url)
    if err != nil {
        return err
    }
    defer response.Body.Close()

    // Write the file
    _, err = io.Copy(file, response.Body)
    if err != nil {
        return err
    }

    fmt.Println("File downloaded successfully.")
    return nil
}

In this function, we first create a file at the specified destination path using os.Create. We then send an HTTP GET request to the given URL and retrieve the response. Finally, we write the response body to the file using io.Copy.

Step 4: Handle Errors

To handle any errors that may occur during the file download process, let’s define a function named handleError that takes an error as input and displays an appropriate error message.

func handleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(1)
}

In this function, we simply print the error message and exit the program with a non-zero status code using os.Exit(1).

Step 5: Build and Run the Program

Now that we have implemented all the necessary functions, let’s build and run the program.

func main() {
    url, path := getUserInput()
    err := downloadFile(url, path)
    if err != nil {
        handleError(err)
    }
}

In the main function, we call the getUserInput function to get the URL and destination path from the user. We then pass this information to the downloadFile function. If any error occurs during the download, we call the handleError function to display the error message.

To build and run the program, open a terminal and navigate to the directory where your Go file is saved. Then, run the following command:

go run main.go

You will be prompted to enter the URL of the file to download and the destination path. After providing the necessary information, the file will be downloaded.

Recap

Congratulations! You have successfully built a file downloader in Go. In this tutorial, we learned how to use the net/http package to perform HTTP requests and the io package to handle file operations. We also covered how to prompt the user for input, handle errors, and build and run the program.

Feel free to modify the script as per your requirements and explore additional features such as progress tracking or handling authentication.

Happy coding!