Table of Contents
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:
-
Install Go by downloading it from the official website: https://golang.org/dl/
-
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
- Open your preferred IDE or text editor.
-
Create a new directory for your project. For example,
backup-tool
. -
Within the
backup-tool
directory, create a new file namedmain.go
.package main import ( "fmt" "os" ) func main() { fmt.Println("Welcome to Backup Tool!") }
- Save the file and open a terminal or command prompt.
-
Navigate to the
backup-tool
directory using thecd
command. - 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.
-
Add the following imports to the
main.go
file:import ( "flag" "fmt" "io" "os" "path/filepath" )
-
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.") }
-
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() } }
-
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!") }
-
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.
-
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!") }
-
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!