Back Up GitHub and GitLab Repositories Using Golang

github logo

Want to learn Golang and build something useful? Learn how to write a tool to back up your GitHub and GitLab repositories.

GitHub and GitLab are two popular Git repository hosting services that are used to host and manage open-source projects. They also have become an easy way for content creators to be able to invite others to share and collaborate without needing to have their own infrastructure setup.

Using hosted services that you don't manage yourself, however, comes with a downside. Systems fail, services go down and disks crash. Content hosted on remote services can simply vanish. Wouldn't it be nice if you could have an easy way to back up your git repositories periodically into a place you control?

If you follow along with this article, you will write a Golang program to back up git repositories from GitHub and GitLab (including custom GitLab installations). Being familiar with Golang basics will be helpful, but not required. Let's get started!

Hello Golang

The latest stable release of Golang at the time of this writing is 1.8. The package name is usually golang, but if your Linux distro doesn't have this release, you can download the Golang compiler and other tools for Linux. Once downloaded, extract it to /usr/local:

$ sudo tar -C /usr/local -xzf 
$ export PATH=$PATH:/usr/local/go/bin

Opening a new terminal and typing $ go version should show the following:

$ go version
go version go1.8 linux/amd64

Let's write your first program. Listing 1 shows a program that expects a -name flag (or argument) when run and prints a greeting using the specified name. Compile and run the program as follows:

$ go build listing1.go
$ ./listing1 -name "Amit"
Hello Amit

$ ./listing1
2017/02/18 22:48:25 Please specify your name using -name
$ echo $?

If you don't specify the -name argument, it exits printing a message with a non-zero exit code. You can combine both compiling and running the program using go run:

$ go run listing1.go -name Amit
2017/03/04 23:08:11 Hello Amit

Listing 1. Example Program listing1.go