GitHub Actions for Go

Run lint and tests on every push: workflows, jobs, steps and triggers, caching Go modules, and service containers that give a job real MySQL and Redis.

Learning outcomes

  • Write a workflow file with on, jobs and steps.
  • Use actions/checkout and actions/setup-go and pin versions.
  • Run golangci-lint and go test -race in CI.
  • Start MySQL and Redis as service containers and pass their addresses to the tests.
  • Read a failing run and find the step that failed.

Why run tests automatically?

So far, you have been running checks on your own machine. You write Go code, run make lint, execute the tests, and fix anything that fails.

That workflow depends on remembering to run every check before sharing your changes. It also depends on your local environment being configured correctly. A test might pass on your machine but fail elsewhere because of a missing dependency, a different Go version, or an overlooked configuration file.

Continuous integration (CI) is the practice of automatically building and testing code whenever changes are pushed or proposed for merging. Instead of relying on every developer to remember the checks, the repository runs them consistently.

For this course, CI will:

  1. Check out the repository.
  2. Install the Go version declared by the backend module.
  3. Run golangci-lint.
  4. Run the Go unit tests with the race detector.
  5. Start Redis and run the Redis integration tests.
  6. Report whether the checks passed.

A successful run produces a green check on the commit or pull request. A failed run produces a red check and a log showing which step failed.

This matters because a green check gives the team evidence that the change passed the repository's automated checks in a clean environment. It does not prove the code is bug-free, but it catches many mistakes before they reach the main branch.

Show a CI pipeline for a push: GitHub receives the push, a runner checks out the repository, sets up Go, runs golangci-lint, runs go test with the race detector alongside a Redis service container, and reports a green or red check on the commit.Show a CI pipeline for a push: GitHub receives the push, a runner checks out the repository, sets up Go, runs golangci-lint, runs go test with the race detector alongside a Redis service container, and reports a green or red check on the commit.

What GitHub Actions does

GitHub Actions is GitHub's automation platform. It runs automated tasks in response to events such as pushes, pull requests, scheduled times, or manually triggered runs.

A workflow is an automated process defined in a YAML file inside the repository. YAML is a human-readable data format that uses indentation to express nested structures.

For this project, the workflow file will live at:

.github/workflows/backend.yml

GitHub automatically discovers workflow files in .github/workflows/. You do not need to register the file separately.

A workflow contains several important concepts:

  • name: the display name shown in the Actions interface.
  • on: the events that trigger the workflow.
  • jobs: the independent units of work in the workflow.
  • runs-on: the machine environment used to run a job.
  • steps: the ordered operations performed by a job.
  • uses: an existing action that performs a reusable operation.
  • run: a shell command executed by the runner.

A runner is the machine that executes the workflow. GitHub-hosted runners provide a clean environment for each job. Your workflow describes what that environment should do.

Start with a minimal workflow

Create .github/workflows/backend.yml at the repository root.

Begin with the workflow name and its trigger:

yaml
name: Backend CI

on:
  push:
    paths:
      - "backend/**"
      - ".github/workflows/backend.yml"
  pull_request:
    paths:
      - "backend/**"
      - ".github/workflows/backend.yml"

This workflow runs when someone pushes changes or opens or updates a pull request that modifies files under backend/. It also runs when the workflow file itself changes.

The paths filter prevents unrelated changes from triggering this backend workflow. For example, a change only to a React Native screen does not need to run the Go backend checks.

Be careful with paths. They are relative to the repository root, not to the workflow file or the backend directory. If you write internal/** here, it will not match backend/internal/ratelimit/limiter.go.

The quotes around the path patterns are valid YAML and make the intended string values explicit.

Define a job

A workflow can contain multiple jobs. Jobs are independent units that can run in parallel unless dependencies are declared.

For now, define one job:

yaml
jobs:
  backend:
    name: Backend checks
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

backend is the job identifier. name is the human-readable label displayed in the Actions interface.

runs-on: ubuntu-latest asks GitHub to provide an Ubuntu runner. The runner starts with a clean environment and executes the steps in order.

The first step uses actions/checkout. An action is a reusable unit of workflow logic. Checkout downloads the repository contents into the runner's workspace so subsequent steps can access the source code.

The @v4 suffix selects a major version of the action. You should pin action versions rather than using a moving latest reference. A stable version makes workflow behavior more predictable and reduces the risk of an unexpected upstream change breaking CI. In production repositories, teams may pin actions to a full commit SHA for stronger supply-chain control.

Set up the correct Go version

Your backend's Go version is declared in backend/go.mod.

CI should use that same version. If your local environment uses one Go version and CI silently uses another, you can get confusing differences in compiler behavior, standard library features, and dependency compatibility.

Add a setup step:

yaml
      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version-file: backend/go.mod

actions/setup-go installs the Go version specified by the module's go.mod file. The go-version-file field tells the action where to find it.

The action also supports caching Go modules and build artifacts. Its built-in caching can reuse downloaded dependencies and compiled package data between runs when the cache key matches. This reduces setup time without requiring you to write your own cache configuration.

Do not hardcode a separate Go version in the workflow if the module already declares it. Keeping one source of truth prevents CI from drifting away from local development.

Run lint and unit tests

The repository already has a Makefile with lint and test targets, and a golangci-lint v2 configuration.

CI should use the same checks that developers run locally. This avoids maintaining one set of rules for local development and another for automation.

Run golangci-lint

Add the lint action:

yaml
      - name: Run golangci-lint
        uses: golangci/golangci-lint-action@v6
        with:
          version: v2.1.6
          working-directory: backend

The action installs and runs golangci-lint. The version field pins the linter version rather than relying on whichever version happens to be available later.

The working-directory field tells the action to operate from backend, where the Go module and linter configuration live.

This detail matters. Running the linter from the repository root may cause it to miss the intended module or configuration file.

The exact pinned action and linter versions are part of the workflow's dependency choices. Update them deliberately when the project adopts newer compatible versions.

Run unit tests with the race detector

Add a shell step:

yaml
      - name: Run unit tests
        run: go test -race -count=1 ./...
        working-directory: backend

The command runs all packages in the backend module.

Two flags are important:

  • -race enables Go's race detector, which reports data races exercised by the tests.
  • -count=1 disables test result caching so the tests actually execute on every workflow run.

The rate limiter uses shared state accessed by concurrent HTTP handlers. A test suite that passes without the race detector might still contain unsafe concurrent access. Running with -race makes the check part of every CI run.

The working-directory is essential. The go test ./... pattern should run from backend, where go.mod is located.

Do not add a separate go vet command here. The repository's lint target already runs the configured lint checks, and this workflow's test step is specifically for race-enabled tests.

Run integration tests with Redis

Unit tests should not need external services. They should be fast, isolated, and repeatable.

Integration tests are different. They verify that your application interacts correctly with an external dependency. The Redis-backed rate limiter tests need an actual Redis server.

A workflow can provide that dependency using a service container. A service container is a Docker container started alongside a job so its services are available to the steps running in that job.

For this project, we need Redis 7.

Add the Redis service

Add a services section under the backend job:

yaml
  backend:
    name: Backend checks
    runs-on: ubuntu-latest
    services:
      redis:
        image: redis:7-alpine
        ports:
          - 6379:6379
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 5s
          --health-timeout 3s
          --health-retries 10

The service uses the Redis 7 Alpine image. The port mapping exposes Redis's container port 6379 on port 6379 of the runner.

The options field configures a container health check:

  • --health-cmd runs redis-cli ping.
  • --health-interval 5s checks every five seconds.
  • --health-timeout 3s allows up to three seconds for each check.
  • --health-retries 10 allows ten failed checks before marking the container unhealthy.

A container being started does not necessarily mean the service inside it is ready. Docker may report that the container is running while Redis is still initializing. The health check gives the runner a way to wait until Redis can answer commands before the job proceeds.

Show a job with its Redis service container: the container starts, a health check repeatedly runs redis-cli ping, the job waits until Redis is healthy, and the test steps connect to Redis at localhost:6379.Show a job with its Redis service container: the container starts, a health check repeatedly runs redis-cli ping, the job waits until Redis is healthy, and the test steps connect to Redis at localhost:6379.

Connect to Redis from the runner

The workflow uses a GitHub-hosted runner, and the job itself runs directly on that host rather than inside another container.

For this arrangement, the service is reachable at:

127.0.0.1:6379

If you instead configure a job to run inside a container, the connection model changes. The job container can reach the Redis service using its service name, such as redis:6379, because GitHub places the job and service containers on a shared network.

Do not blindly copy localhost into every containerized workflow. Inside a container, localhost refers to that container itself.

Understand the Redis test convention

The course's Redis integration tests use the redis build tag and the TEST_REDIS_ADDR environment variable.

A build tag is a condition that controls whether Go includes particular source or test files when compiling a package.

The Redis tests are skipped in the ordinary test run unless the Redis test configuration is explicitly enabled. This keeps unit tests independent of external services.

The integration test command is:

bash
TEST_REDIS_ADDR=127.0.0.1:6379 go test -race -count=1 -tags redis ./internal/...

The environment variable tells the tests where Redis is listening. The -tags redis flag includes the Redis-specific test files.

Add the integration test step:

yaml
      - name: Run Redis integration tests
        run: go test -race -count=1 -tags redis ./internal/...
        working-directory: backend
        env:
          TEST_REDIS_ADDR: 127.0.0.1:6379

The env section defines environment variables available to that step. The test process reads TEST_REDIS_ADDR and connects to the service container.

Environment variables are useful for configuration that changes between environments. They let the same test code run locally and in CI without hardcoding different Redis addresses.

Environment variables and secrets

An ordinary environment variable is appropriate for non-sensitive configuration such as a Redis address or a feature flag.

A secret is sensitive configuration such as an API token, password, or private key. GitHub Actions supports storing secrets in repository or organization settings and exposing them to workflow steps when needed.

This workflow does not need any secrets. The Redis service is local to the job and has no password configured. Do not invent credentials or add unnecessary secrets just because the feature exists.

Add concurrency control

A developer might push several commits quickly. GitHub could then run multiple workflow jobs for the same branch even though only the newest commit matters.

A concurrency group lets GitHub manage overlapping workflow runs.

Add this at the top level of the workflow:

yaml
concurrency:
  group: backend-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

The group name combines the workflow and Git reference. cancel-in-progress: true tells GitHub to cancel an older run in the same group when a newer one starts.

This is a convenience, not a correctness requirement. It avoids spending runner time on outdated commits that are no longer the latest version of a branch.

Put the workflow together

You have now seen the workflow in pieces. The complete file below combines the trigger, concurrency policy, Go setup, linting, unit tests, and Redis integration tests.

Create or update .github/workflows/backend.yml with this content:

yaml
name: Backend CI

on:
  push:
    paths:
      - "backend/**"
      - ".github/workflows/backend.yml"
  pull_request:
    paths:
      - "backend/**"
      - ".github/workflows/backend.yml"

concurrency:
  group: backend-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  backend:
    name: Backend checks
    runs-on: ubuntu-latest

    services:
      redis:
        image: redis:7-alpine
        ports:
          - 6379:6379
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 5s
          --health-timeout 3s
          --health-retries 10

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version-file: backend/go.mod

      - name: Run golangci-lint
        uses: golangci/golangci-lint-action@v6
        with:
          version: v2.1.6
          working-directory: backend

      - name: Run unit tests
        run: go test -race -count=1 ./...
        working-directory: backend

      - name: Run Redis integration tests
        run: go test -race -count=1 -tags redis ./internal/...
        working-directory: backend
        env:
          TEST_REDIS_ADDR: 127.0.0.1:6379

Read the indentation carefully. YAML uses indentation to represent nesting. services and steps belong to the job. env belongs to the Redis integration test step. A single misplaced indentation level can change the structure or make the file invalid.

The workflow runs lint first, then unit tests, then Redis integration tests. If an earlier step fails, later steps are skipped by default.

The action versions and linter version are pinned. The Go version comes from backend/go.mod. Redis is provided by the job as a service container, and the health check ensures it is ready before the tests need it.

Run the same checks locally

CI should not contain mysterious commands that developers cannot reproduce.

From the repository root, run:

bash
make lint
make test

These are the normal local checks provided by the course Makefile.

For the Redis integration tests, start the local services:

bash
docker compose up -d

Then run:

bash
cd backend
TEST_REDIS_ADDR=127.0.0.1:6379 go test -race -count=1 -tags redis ./internal/...

If a CI run fails, try to reproduce the failing command locally before changing the workflow. A failure caused by a real code issue should be fixed in the code, not hidden by weakening the CI checks.

Read a failing workflow run

After pushing your changes, open the repository on GitHub.

  1. Select the Actions tab.
  2. Open the latest Backend CI run.
  3. Select the Backend checks job.
  4. Find the step marked as failed.
  5. Expand the step and read its log.
  6. Fix the underlying issue and push another commit.

A failed step is not necessarily a problem with GitHub Actions itself. It may be a compiler error, a lint violation, a failing assertion, a race detector report, or a Redis connection problem.

You can also inspect workflow runs from the terminal if the GitHub CLI is installed and authenticated:

bash
gh run list

This lists recent workflow runs. To watch a particular run:

bash
gh run watch

The command follows the latest run by default. You can also provide a run ID when you want to inspect a specific run.

If the failure is unclear, rerun the relevant check locally:

bash
make lint
make test

For a Redis-specific failure, run the tagged integration test command with TEST_REDIS_ADDR set. Reproducing the failure locally is usually faster than repeatedly pushing changes to discover what went wrong.

Common CI mistakes

Further CI improvements

The workflow above is enough for this week's backend checks. Larger repositories often need additional CI capabilities.

Matrix builds

A matrix build runs the same job across multiple configurations, such as several Go versions or operating systems.

For example, a library might test against multiple supported Go releases. This course uses one Go version declared by backend/go.mod, so a matrix is not necessary yet.

Required status checks and branch protection

A green CI result is useful only if the team pays attention to it.

GitHub branch protection rules can require selected status checks to pass before a pull request can be merged. This prevents a change from being merged while the backend checks are failing.

For a team project, configure the Backend checks job as a required status check on the main branch. The exact setting depends on the repository's branch protection or ruleset configuration.

A README status badge

A status badge displays the latest workflow result in the repository README. GitHub provides a badge URL for each workflow.

You can add a badge like this, replacing the owner and repository placeholders with the actual GitHub repository details:

markdown
![Backend CI](https://github.com/OWNER/REPOSITORY/actions/workflows/backend.yml/badge.svg)

Knowledge assessment

Question 1 of 4

A GitHub Actions workflow displays a green check for a commit. What does this establish?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.24: GitHub Actions, lint and race tests on every push. Create .github/workflows/backend.yml, configure the Go version from backend/go.mod, run lint and race-enabled unit tests, start Redis 7 as a service container, and execute the Redis integration tests.

References

Everything above is explained on this page; these are where it comes from (GitHub Actions).

Finished Lesson 1.23?