Continuous Integration and Continuous Deployment (CI/CD) are essential practices in modern software development. They enable developers to automate the process of integrating code, running tests, and, in this article, deploying Go applications via GitHub Actions.
Prerequisites
- A GitHub account
- An existing Go application repository on GitHub
- Basic understanding of YAML syntax
Step 1: Setting Up a Go Project
Ensure you have a Go project on your local machine. If you don't, here is a quick step to create one:
$ mkdir my-go-app
$ cd my-go-app
$ go mod init my-go-app
$ touch main.goEdit main.go to include a simple Go application:
package main
import "fmt"
func main() {
fmt.Println("Hello, Go world!")
}Commit and push this code to your GitHub repository:
$ git add .
$ git commit -m "Initial commit with Go application"
$ git push origin mainStep 2: Creating a GitHub Action Workflow
Create a directory in your project for GitHub Actions:
$ mkdir -p .github/workflowsCreate a new file called ci-cd.yml in the .github/workflows directory:
name: Go CI/CD
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.16
- name: Cache Go modules
uses: actions/cache@v2
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Build
run: go build -v ./...
- name: Run unit tests
run: go test -v ./...Step 3: Adding Deployment Steps
To auto deploy your Go app, you'll need additional steps tailored to your deployment environment. For illustration, let's assume we're deploying to a server via SSH:
- name: Deploy to server
uses: appleboy/[email protected]
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SERVER_SSH_KEY }}
script: |
cd /path/to/deployed/app
git pull origin main
go build ./...
./my-go-appThis assumes that deployment credentials are stored as secrets in your GitHub repository. Navigate to the repository's settings and add these secrets under "Secrets and variables" > "Actions" for secure storage.
Conclusion
By following these steps, you've automated building, testing, and deploying a Go application via GitHub Actions. While this example uses an SSH-based deployment, the deployment step can be adjusted for other environments such as AWS, GCP, or DigitalOcean.