golang-continuous-integration

作者: samber

使用 GitHub Actions 為 Golang 專案配置 CI/CD 管道 — 包含測試、程式碼檢查、SAST、安全掃描、程式碼覆蓋率、Dependabot、Renovate、GoReleaser、程式碼審查自動化以及發布管道。適用於設定或改善 Go 專案的 CI、配置 GitHub Actions 工作流程、加入程式碼檢查工具或安全掃描器、自動化相依性更新,或加入品質關卡。

npx skills add https://github.com/samber/cc-skills-golang --skill golang-continuous-integration

Persona: You are a Go DevOps engineer. You treat CI as a quality gate — every pipeline decision is weighed against build speed, signal reliability, and security posture.

Modes:

  • Setup — adding CI to a project for the first time: start with the Quick Reference table, then generate workflows in this order: test → lint → security → release. Prefer the latest stable major version for each GitHub Action.
  • Improve — auditing or extending an existing pipeline: read current workflow files first, identify gaps against the Quick Reference table, then propose targeted additions without duplicating existing steps.

Dependencies:

  • goreleaser: go install github.com/goreleaser/goreleaser/v2@latest
  • gh: brew install gh

Go Continuous Integration

Set up production-grade CI/CD pipelines for Go projects using GitHub Actions.

Action Versions

The versions in the examples below are reference versions that may be outdated. GitHub Actions release frequently — the current major version for each action (actions/checkout, actions/setup-go, golangci/golangci-lint-action, codecov/codecov-action, goreleaser/goreleaser-action, etc.) may differ from what is shown here.

Quick Reference

StageToolPurpose
Testgo test -raceUnit + race detection
Coveragecodecov/codecov-actionCoverage reporting
Lintgolangci-lintComprehensive linting
Vetgo vetBuilt-in static analysis
SASTgosec, CodeQL, BearerSecurity static analysis
Vuln scangovulncheckKnown vulnerability detection
Dockerdocker/build-push-actionMulti-platform image builds
DepsDependabot / RenovateAutomated dependency updates
ReleaseGoReleaserAutomated binary releases
AI ReviewClaude Code / CopilotAI-powered PR review

Testing

.github/workflows/test.yml — see test.yml

Adapt the Go version matrix to match go.mod:

go 1.23   → matrix: ["1.23", "1.24", "1.25", "1.26", "stable"]
go 1.24   → matrix: ["1.24", "1.25", "1.26", "stable"]
go 1.25   → matrix: ["1.25", "1.26", "stable"]
go 1.26   → matrix: ["1.26", "stable"]

Use fail-fast: false so a failure on one Go version doesn't cancel the others.

Test flags:

  • -race: CI MUST run tests with the -race flag (catches data races — undefined behavior in Go)
  • -shuffle=on: Randomize test order to catch inter-test dependencies
  • -coverprofile: Generate coverage data
  • git diff --exit-code: Fails if go mod tidy changes anything

Coverage Configuration

CI SHOULD enforce code coverage thresholds. Configure thresholds in codecov.yml at the repo root — see codecov.yml


Integration Tests

.github/workflows/integration.yml — see integration.yml

Use -count=1 to disable test caching — cached results can hide flaky service interactions.


Linting

golangci-lint MUST be run in CI on every PR. .github/workflows/lint.yml — see lint.yml

golangci-lint Configuration

Create .golangci.yml at the root of the project. See the samber/cc-skills-golang@golang-lint skill for the recommended configuration.


Security & SAST

.github/workflows/security.yml — see security.yml

CI MUST run govulncheck. It only reports vulnerabilities in code paths your project actually calls — unlike generic CVE scanners. CodeQL results appear in the repository's Security tab. Bearer is good at detecting sensitive data flow issues.

CodeQL Configuration

Create .github/codeql/codeql-config.yml to use the extended security query suite — see codeql-config.yml

Available query suites:

  • default: Standard security queries
  • security-extended: Extra security queries with slightly lower precision
  • security-and-quality: Security queries plus maintainability and reliability checks

Container Image Scanning

If the project produces Docker images, Trivy container scanning is included in the Docker workflow — see docker.yml


Dependency Management

Dependabot

.github/dependabot.yml — see dependabot.yml

Minor/patch updates are grouped into a single PR. Major updates get individual PRs since they may have breaking changes.

Auto-Merge for Dependabot

.github/workflows/dependabot-auto-merge.yml — see dependabot-auto-merge.yml

Security warning: This workflow requires contents: write and pull-requests: write — these are elevated permissions that allow merging PRs and modifying repository content. The if: github.actor == 'dependabot[bot]' guard restricts execution to Dependabot only. Do not remove this guard. Note that github.actor checks are not fully spoof-proof — branch protection rules are the real safety net. Ensure branch protection is configured (see Repository Security Settings) with required status checks and required approvals so that auto-merge only succeeds after all checks pass, regardless of who triggered the workflow.

Renovate (alternative)

Renovate is a more mature and configurable alternative to Dependabot. It supports automerge natively, grouping, scheduling, regex managers, and monorepo-aware updates. If Dependabot feels too limited, Renovate is the go-to choice.

Install the Renovate GitHub App, then create renovate.json at the repo root — see renovate.json

Key advantages over Dependabot:

  • gomodTidy: Automatically runs go mod tidy after updates
  • Native automerge: No separate workflow needed
  • Better grouping: More flexible rules for grouping PRs
  • Regex managers: Can update versions in Dockerfiles, Makefiles, etc.
  • Monorepo support: Handles Go workspaces and multi-module repos

Release Automation

GoReleaser automates binary builds, checksums, and GitHub Releases. The configuration varies significantly depending on the project type.

Release Workflow

.github/workflows/release.yml — see release.yml

Security warning: This workflow requires contents: write to create GitHub Releases. It is restricted to tag pushes (tags: ["v*"]) so it cannot be triggered by pull requests or branch pushes. Only users with push access to the repository can create tags.

GoReleaser for CLI/Programs

Programs need cross-compiled binaries, archives, and optionally Docker images.

.goreleaser.yml — see goreleaser-cli.yml

GoReleaser for Libraries

Libraries don't produce binaries — they only need a GitHub Release with a changelog. Use a minimal config that skips the build.

.goreleaser.yml — see goreleaser-lib.yml

For libraries, you may not even need GoReleaser — a simple GitHub Release created via the UI or gh release create is often sufficient.

GoReleaser for Monorepos / Multi-Binary

When a repository contains multiple commands (e.g., cmd/api/, cmd/worker/).

.goreleaser.yml — see goreleaser-monorepo.yml

Docker Build & Push

For projects that produce Docker images. This workflow builds multi-platform images, generates SBOM and provenance attestations, pushes to both GitHub Container Registry (GHCR) and Docker Hub, and includes Trivy container scanning.

.github/workflows/docker.yml — see docker.yml

Security warning: Permissions are scoped per job: the container-scan job only gets contents: read + security-events: write, while the docker job gets packages: write (to push to GHCR) and attestations: write + id-token: write (for provenance/SBOM signing). This ensures the scan job cannot push images even if compromised. The push flag is set to false on pull requests so untrusted code cannot publish images. The DOCKERHUB_USERNAME and DOCKERHUB_TOKEN secrets must be configured in the repository secrets settings — never hardcode credentials.

Key details:

  • QEMU + Buildx: Required for multi-platform builds (linux/amd64,linux/arm64). Remove platforms you don't need.
  • push: false on PRs: Images are built but never pushed on pull requests — this validates the Dockerfile without publishing untrusted code.
  • Metadata action: Automatically generates semver tags (v1.2.31.2.3, 1.2, 1), branch tags (main), and SHA tags.
  • Provenance + SBOM: provenance: mode=max and sbom: true generate supply chain attestations. These require attestations: write and id-token: write permissions.
  • Dual registry: Pushes to both GHCR (using GITHUB_TOKEN, no extra secret needed) and Docker Hub (requires DOCKERHUB_USERNAME + DOCKERHUB_TOKEN secrets). Remove the Docker Hub login and image line if not needed.
  • Trivy: Scans the built image for CRITICAL and HIGH vulnerabilities and uploads results to the Security tab.
  • Adapt the image names and registries to your project. For GHCR-only, remove the Docker Hub login step and the docker.io/ line from images:.

Repository Security Settings

Repository security settings (branch protection, workflow permissions, secrets, environments) form the security foundation for the CI pipeline — these are documented in repo-security.md.


AI-Driven Code Review

Add AI agents as PR reviewers alongside traditional static analysis. When loaded with this skill plugin, the agent applies the relevant Go skills per review area — catching architectural drift, logic bugs, missing error context, and concurrency hazards that linters cannot detect.

Cost note: AI review agents run concurrently per PR. For cost control, remove jobs you don't need or raise the PR trigger filter to specific branches only.

Claude Code

.github/workflows/ai-review.yml — see claude-code-review.yml

The workflow runs parallel jobs, each scoped to a set of review areas and priority level:

JobAreasPriority
qualityCode style, Naming, Documentation, Design patternsSuggestion-first
correctnessError handling, Code safety, ConcurrencyBlocking-first
securitySecurity, DependenciesBlocking-first
quality-depthTests, Performance, Observability, ModernizeMixed

Additional skills that may be relevant depending on the project: golang-cli, golang-context, golang-data-structures, golang-database, golang-dependency-injection, or any library-specific skill.

The Claude Code GitHub App integration is configured via the /install-github-app command, which sets up the required API secrets.

GitHub Copilot

Copy skills into your repo, then append copilot-review-instructions.md to .github/copilot-instructions.md:

npx skills add https://github.com/samber/cc-skills-golang --agent github-copilot --skill '*' -y --copy
ln -s .agents .copilot

Common Mistakes

MistakeFix
Missing -race in CI testsAlways use go test -race
No -shuffle=onRandomize test order to catch inter-test dependencies
Caching integration test resultsUse -count=1 to disable caching
go mod tidy not checkedAdd go mod tidy && git diff --exit-code step
Missing fail-fast: falseOne Go version failing shouldn't cancel other jobs
Not pinning action versionsGitHub Actions MUST use pinned major versions (e.g. @vN, not @master)
No permissions blockFollow least-privilege per job
Ignoring govulncheck findingsFix or suppress with justification
No AI review in CIAdd Claude Code or Copilot review — catches logic, security, and architectural issues that static analysis misses

Related Skills

See samber/cc-skills-golang@golang-lint, samber/cc-skills-golang@golang-security, samber/cc-skills-golang@golang-testing, samber/cc-skills-golang@golang-dependency-management, samber/cc-skills-golang@golang-modernize skills.

來自 samber 的更多技能

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
符合慣例的 Golang 設計模式 — 函數選項、建構子、錯誤流程與串聯、資源管理與生命週期、優雅關閉、韌性、架構、依賴注入、資料處理、串流等。適用於明確選擇架構模式、實作函數選項、設計建構子 API、設定優雅關閉、應用韌性模式,或詢問哪種慣用 Go 模式適合特定問題時。
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Golang 性能優化模式與方法論 - 若遇到 X 瓶頸,則應用 Y。涵蓋減少分配、CPU 效率、記憶體佈局、GC 調校、池化、快取以及熱路徑優化。適用於當性能分析或基準測試已識別出瓶頸,且需要正確的優化模式來解決時。亦適用於進行性能代碼審查時,提出改進建議或可協助快速識別性能增益的基準測試。不適用於測量方法論(→...
developmentcode-review
golang-security
samber
Golang的安全最佳實踐與漏洞防範。涵蓋注入攻擊(SQL、命令、XSS)、密碼學、檔案系統安全、網路安全、Cookie、機密管理、記憶體安全及日誌記錄。適用於撰寫、審查或稽核Go程式碼的安全性,或處理涉及加密、I/O、機密管理、使用者輸入處理或身分驗證的高風險程式碼。包含安全工具的配置。
securitycode-reviewdevelopment
golang-database
samber
Go 資料庫存取的全面指南 — 參數化查詢、結構掃描、可空欄位、交易、隔離層級、SELECT FOR UPDATE、連線池、批次處理、上下文傳遞與遷移工具。適用於撰寫、審查或除錯與 PostgreSQL、MariaDB、MySQL 或 SQLite 互動的 Golang 程式碼;資料庫測試;或關於 database/sql、sqlx 或 pgx 的問題。不產生資料庫結構或遷移 SQL。
developmentdatabase
golang-lint
samber
針對 Golang 專案的 lint 最佳實務與 golangci-lint 配置 — 執行 linter、設定 .golangci.yml、使用 nolint 指令抑制警告、解讀 lint 輸出,以及選擇 linter。適用於配置 golangci-lint、詢問 lint 警告或 nolint 抑制方式、設定程式碼品質工具,或挑選 linter 時。亦適用於使用者提及 golangci-lint、go vet、staticcheck 或 revive 時。
developmentcode-reviewtesting