A CI workflow for Go: lint, test with the race detector and cache
Part 5 of the shorty series: a GitHub Actions CI workflow for a Go service. golangci-lint v2 with a config that fits, go test with the race detector against a real Postgres service container, setup-go caching, and a coverage summary on every pull request.
shorty has tests, a Dockerfile and a compose stack now. What it doesn't have is anything that runs those tests when someone opens a pull request. Right now it's basically me remembering to type go test ./... before I push, and I forget.
In this blog we will write the CI workflow for shorty in GitHub Actions: golangci-lint, go vet, go test with the race detector, a real Postgres for the integration test, caching, and a coverage summary on the pull request. This is part 5 of the shorty series and comes after hardening the container image in part 4. Level is beginner. If workflows, jobs and steps are new to you, read GitHub Actions from zero first.
Versions I used: Go 1.27.4, golangci-lint v2.15.0, actions/checkout@v7, actions/setup-go@v7, golangci/golangci-lint-action@v9, actions/upload-artifact@v7 and Postgres 18 (postgres:18-alpine). I checked the workflow with actionlint 1.7.12 and ran every step on my Mac first, which turned out to matter a lot for the lint part.
The whole workflow
It goes in .github/workflows/ci.yml in the shorty repo. Two jobs, lint and test, and they run in parallel.
name: ci
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: false # golangci-lint-action keeps its own cache
- uses: golangci/golangci-lint-action@v9
with:
version: v2.15
test:
runs-on: ubuntu-latest
timeout-minutes: 15
services:
postgres:
image: postgres:18-alpine
env:
POSTGRES_USER: shorty
POSTGRES_PASSWORD: shorty
POSTGRES_DB: shorty
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -h 127.0.0.1 -U shorty -d shorty"
--health-interval 2s
--health-timeout 3s
--health-retries 20
env:
SHORTY_TEST_DATABASE_URL: postgres://shorty:shorty@localhost:5432/shorty?sslmode=disable
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache-dependency-path: go.sum
- name: go mod tidy
run: go mod tidy -diff
- name: go vet
run: go vet ./...
- name: go test
run: go test -race -count=1 -coverprofile=coverage.out ./...
- name: Coverage summary
if: ${{ !cancelled() && hashFiles('coverage.out') != '' }}
run: |
{
echo "### Coverage"
echo
echo "Total: $(go tool cover -func=coverage.out | tail -1 | awk '{print $NF}')"
echo
echo '<details><summary>Per function</summary>'
echo
echo '```text'
go tool cover -func=coverage.out
echo '```'
echo '</details>'
} >> "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() && hashFiles('coverage.out') != '' }}
with:
name: coverage
path: coverage.out
retention-days: 7
permissions: contents: read at the top means the GITHUB_TOKEN can only read the repo. Nothing in CI needs more, so I start every workflow from read-only and add per job when a job really needs something. The next post needs more for pushing images.
Let us go through the parts that are not obvious.
Which Go version setup-go picks
go-version-file: go.mod tells setup-go to read the version from go.mod instead of me hard-coding it in YAML. I like this, one place to bump. But look at what the shorty go.mod had:
module github.com/fenixara/shorty
go 1.27.0
The setup-go README says it uses the toolchain line if there is one and otherwise the go line. So CI would have installed Go 1.27.0, while my Mac has 1.27.3 and the Dockerfile builds with golang:1.27.4-alpine. See, the problem here is three different Go versions for the same code. The go line is the minimum version the module needs, not the one you want to build with, so the fix is a toolchain line:
go mod edit -toolchain=go1.27.4
go 1.27.0
toolchain go1.27.4
After that, go version on my Mac printed go1.27.4 even though 1.27.3 is what I have installed. Go saw the toolchain line and switched to 1.27.4 by itself. Now CI, the image and my laptop all agree.
Caching
setup-go caches the module cache and the build cache. One thing changed in v6: the cache key is based on go.mod by default, not go.sum. If you bump a dependency, go.sum changes but go.mod may only change one line, or none for an indirect update. I'd rather key on go.sum, that's what cache-dependency-path: go.sum does.
In the lint job I turned setup-go's cache off. The golangci-lint action saves its own cache, and two steps restoring into the same Go directories just wastes time.
golangci-lint, and what it found
I installed the same version locally first, because I'd rather fight the linter on my laptop than in a pull request:
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0
golangci-lint run ./...
With no config at all, v2 runs its standard set (errcheck, govet, ineffassign, staticcheck, unused). It found four things, all the same:
cmd/shorty/main.go:84:16: Error return value of `r.Close` is not checked (errcheck)
defer r.Close()
cmd/shorty/main.go:173:19: Error return value of `sqlDB.Close` is not checked (errcheck)
cmd/shorty/main.go:224:23: Error return value of `resp.Body.Close` is not checked (errcheck)
internal/links/pg_test.go:34:19: Error return value of `sqlDB.Close` is not checked (errcheck)
4 issues:
* errcheck: 4
defer x.Close() everywhere. Wrapping each one in defer func() { _ = x.Close() }() makes the code worse, not better. golangci-lint v2 has an exclusion preset called std-error-handling for exactly this, so I used it. Then I added a few more linters I find useful for HTTP services. This is the .golangci.yml:
version: "2"
linters:
default: standard # errcheck, govet, ineffassign, staticcheck, unused
enable:
- bodyclose
- errorlint
- gosec
- misspell
- nilerr
- noctx
- unconvert
exclusions:
presets:
- std-error-handling # unchecked Close() on defer and friends
rules:
# healthcheck calls 127.0.0.1 on our own PORT, not a user supplied URL
- path: cmd/shorty/main.go
linters: [gosec]
text: "G704"
formatters:
enable:
- gofmt
- goimports
settings:
goimports:
local-prefixes:
- github.com/fenixara/shorty
The extra linters found five more:
internal/httpapi/middleware.go:84:9: comparing with == will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint)
internal/links/pg_test.go:57:57: comparing with != will fail on wrapped errors. Use errors.Is to check for a specific error (errorlint)
cmd/shorty/main.go:220:25: G704: SSRF via taint analysis (gosec)
internal/httpapi/handlers.go:81:15: G710: Open redirect via taint analysis (gosec)
internal/httpapi/server_test.go:77:28: net/http/httptest.NewRequest must not be called. use net/http/httptest.NewRequestWithContext (noctx)
The test one was a real fix, err != ErrCodeTaken became !errors.Is(err, ErrCodeTaken). The middleware one compares a recovered panic value with http.ErrAbortHandler. That value is never wrapped, it's the sentinel itself, so I kept == with a //nolint:errorlint and a reason.
G710, open redirect, made me laugh. The redirect handler of a URL shortener redirects to a URL the user gave us. That is the product. Create only accepts http and https URLs, so this one got a //nolint:gosec with that reason on the line.
The noctx one in the test helper was an easy change to httptest.NewRequestWithContext(t.Context(), ...).
G704 actually took me three tries. The healthcheck subcommand from part 4 calls http://127.0.0.1:$PORT/healthz, and gosec thinks PORT from the environment is attacker input. First I put a //nolint:gosec on the client.Get line. Then noctx complained about client.Get having no context, so I rewrote it with http.NewRequestWithContext and a 2 second timeout. That moved the G704 warning to the new line. I tried parsing the port with strconv.Atoi to convince the taint analysis it's just a number. It did not care. In the end I wrote the exclusion rule above, scoped to one file and one rule ID, with a comment saying why. I'm OK with that. A blanket "disable gosec" would have been the lazy fix and it would hide the next real finding.
After all that:
0 issues.
The action prints findings as annotations on the pull request diff, on the exact line. That's most of the "results on the PR" I want from lint.
Tests with the race detector and a real Postgres
go test -race builds the tests with the race detector, which catches two goroutines touching the same memory without a lock. shorty has a click counter that's written from request handlers and flushed by a background goroutine, which is exactly the kind of code where races hide. The race detector needs cgo, and the Ubuntu runners have gcc, so it just works there.
-count=1 turns off the test cache. In CI the cache is usually cold anyway, but the Postgres test depends on something outside the code, so I never want a cached pass for it.
The interesting part is the services: block. In part 2 the TestPostgres test skips itself unless SHORTY_TEST_DATABASE_URL is set. Without a database in CI, that test would quietly skip on every run and I would think it's passing. The service container gives the job a Postgres 18 on localhost:5432, and the health options make the runner wait until pg_isready says yes before the steps start. The test runs goose migrations itself, so there's no separate migrate step.
Before writing the workflow, I started same image locally on a spare port and ran the exact test command:
docker run -d --rm --name pg-ci -e POSTGRES_USER=shorty -e POSTGRES_PASSWORD=shorty \
-e POSTGRES_DB=shorty -p 127.0.0.1:55439:5432 postgres:18-alpine
SHORTY_TEST_DATABASE_URL='postgres://shorty:shorty@localhost:55439/shorty?sslmode=disable' \
go test -race -count=1 -coverprofile=coverage.out ./...
ok github.com/fenixara/shorty/internal/config 2.285s coverage: 89.7% of statements
ok github.com/fenixara/shorty/internal/httpapi 1.485s coverage: 89.4% of statements
ok github.com/fenixara/shorty/internal/links 2.878s coverage: 76.3% of statements
ok github.com/fenixara/shorty/internal/shortcode 1.843s coverage: 95.8% of statements
Without the database, internal/links was at 61.3%. With it, 76.3%, and the total went from 48.0% to 51.0%. Those 15 points are the ones that check the real SQL, the ON CONFLICT path and the batched click flush. They are the tests I care most about, and those only were the ones skipping.
If you run the integration tests with the full compose stack instead, like in part 3, that works too. For one database, a service container is less moving parts.
Coverage on the pull request
$GITHUB_STEP_SUMMARY is a file. Whatever Markdown you append to it shows up on the run's summary page, which is linked from the checks on the pull request. The step writes the total and a collapsed per-function table. I checked the awk line against my local coverage.out and it printed Total: 51.0%.
if: ${{ !cancelled() && hashFiles('coverage.out') != '' }} means: run even if the tests failed, but not if the run was cancelled or the file was never written. A failing test still gives you coverage for everything else, and that's useful.
I didn't add a coverage threshold that fails the build. I find those turn into people writing tests for getters to push the number up. The number on every PR is enough to notice when it drops.
Tidy and vet
go mod tidy -diff (Go 1.23 and newer) prints what tidy would change and exits non-zero if anything would. It catches the pull request where someone added an import and forgot to commit go.sum. go vet overlaps a bit with golangci-lint's govet, but it's fast and it runs in the test job with the full build cache, so I keep it. If go vet ./... fails in CI on files that aren't really part of your module, this post on go list failing on stray scripts has the fix.
One more check worth adding later is govulncheck. I left it out here to keep this workflow about lint and tests.
Making it required
A workflow that runs but doesn't block anything gets ignored after the first red build. In the repo settings, add a branch rule (or ruleset) for main that requires the lint and test checks to pass before merging. The check names are the job names, which is one more reason to keep them short.
That's the CI part done. Next in the series the image from part 4 gets built for amd64 and arm64 and pushed to ECR and GHCR from this same repo.