Writing a Go-Based CLI Tool for Backup Management

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the CLI Tool
  5. Backing up Files
  6. Restoring Files
  7. Conclusion

Introduction

In this tutorial, we will learn how to write a CLI (Command Line Interface) tool in Go for backup management. The tool will allow users to back up and restore files easily from the command line. By the end of this tutorial, you will be able to create a powerful backup management tool using Go.

Prerequisites

Before starting this tutorial, you should have some basic knowledge of Go programming language, including variables, functions, and command line interactions. You should also have Go installed on your system.

Setup

To set up your development environment, follow these steps:

  1. Install Go by downloading it from the official website: https://golang.org/dl/

  2. Verify the installation by opening a terminal or command prompt and running the command go version. You should see the installed Go version.

Creating the CLI Tool

  1. Open your preferred IDE or text editor.
  2. Create a new directory for your project. For example, backup-tool.

  3. Within the backup-tool directory, create a new file named main.go.

     package main
        
     import (
     	"fmt"
     	"os"
     )
        
     func main() {
     	fmt.Println("Welcome to Backup Tool!")
     }
    
  4. Save the file and open a terminal or command prompt.
  5. Navigate to the backup-tool directory using the cd command.

  6. Build and run the tool using the command go run main.go. You should see the message “Welcome to Backup Tool!” displayed in the terminal.

Backing up Files

Next, we will implement the functionality to back up files using our CLI tool.

  1. Add the following imports to the main.go file:

     import (
     	"flag"
     	"fmt"
     	"io"
     	"os"
     	"path/filepath"
     )
    
  2. Below the existing imports, add the following function to display the help message when no command is provided:

     func displayHelp() {
     	fmt.Println("Usage: backup-tool [command]")
     	fmt.Println("Commands:")
     	fmt.Println("  backup <source> <destination> - Back up files from the source directory to the destination directory.")
     	fmt.Println("  restore <source> <destination> - Restore files from the source directory to the destination directory.")
     }
    
  3. Modify the main function to parse the provided command and arguments:

     func main() {
     	if len(os.Args) < 2 {
     		displayHelp()
     		return
     	}
        
     	command := os.Args[1]
     	args := os.Args[2:]
        
     	switch command {
     	case "backup":
     		backup(args)
     	case "restore":
     		restore(args)
     	default:
     		displayHelp()
     	}
     }
    
  4. Implement the backup function to handle the backup command:

     func backup(args []string) {
     	if len(args) != 2 {
     		fmt.Println("Invalid number of arguments. Usage: backup-tool backup <source> <destination>")
     		return
     	}
        
     	source := args[0]
     	destination := args[1]
        
     	filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
     		if err != nil {
     			return err
     		}
        
     		if !info.IsDir() {
     			relativePath, err := filepath.Rel(source, path)
     			if err != nil {
     				return err
     			}
        
     			destPath := filepath.Join(destination, relativePath)
     			err = os.MkdirAll(filepath.Dir(destPath), os.ModePerm)
     			if err != nil {
     				return err
     			}
        
     			sourceFile, err := os.Open(path)
     			if err != nil {
     				return err
     			}
     			defer sourceFile.Close()
        
     			destinationFile, err := os.Create(destPath)
     			if err != nil {
     				return err
     			}
     			defer destinationFile.Close()
        
     			_, err = io.Copy(destinationFile, sourceFile)
     			if err != nil {
     				return err
     			}
     		}
        
     		return nil
     	})
        
     	fmt.Println("Backup completed successfully!")
     }
    
  5. Save the file and build and run the tool using the command go run main.go backup /path/to/source /path/to/destination. This command will back up all the files from the source directory to the destination directory.

Restoring Files

Finally, let’s implement the functionality to restore files using our CLI tool.

  1. Add the following function to the main.go file to handle the restore command:

     func restore(args []string) {
     	if len(args) != 2 {
     		fmt.Println("Invalid number of arguments. Usage: backup-tool restore <source> <destination>")
     		return
     	}
        
     	source := args[0]
     	destination := args[1]
        
     	filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
     		if err != nil {
     			return err
     		}
        
     		if !info.IsDir() {
     			relativePath, err := filepath.Rel(source, path)
     			if err != nil {
     				return err
     			}
        
     			destPath := filepath.Join(destination, relativePath)
     			err = os.MkdirAll(filepath.Dir(destPath), os.ModePerm)
     			if err != nil {
     				return err
     			}
        
     			sourceFile, err := os.Open(path)
     			if err != nil {
     				return err
     			}
     			defer sourceFile.Close()
        
     			destinationFile, err := os.Create(destPath)
     			if err != nil {
     				return err
     			}
     			defer destinationFile.Close()
        
     			_, err = io.Copy(destinationFile, sourceFile)
     			if err != nil {
     				return err
     			}
     		}
        
     		return nil
     	})
        
     	fmt.Println("Restoration completed successfully!")
     }
    
  2. Save the file and build and run the tool using the command go run main.go restore /path/to/source /path/to/destination. This command will restore all the files from the source directory to the destination directory.

Conclusion

In this tutorial, we have learned how to write a Go-based CLI tool for backup management. We covered the process of creating the CLI tool, backing up files, and restoring files. You can now expand on this tool by adding additional functionality like compression, encryption, or scheduling backups. Go provides a powerful set of libraries and tools to make CLI tool development efficient and straightforward.

Remember to explore the Go documentation and experiment with different features to enhance your CLI tool further. Happy coding!