← 中文资源

简体中文版本

Go 版 GitHub Actions CI 流水线

为 Go 项目定义矩阵 CI 流水线:双版本测试、模块缓存加速、整洁检查与 vet 门禁、竞态检测测试,打标签时交叉编译发布产物。

阅读英文原文

示例说明

Go 项目 CI 的四道门禁各有分工:go mod tidy 的 diff 检查抓依赖漂移——开发者本地改动没提交锁文件直接红;vet 与 lint 分层抓静态问题;-race 让数据竞争在测试期暴露而不是线上崩溃。矩阵覆盖两个小版本提前发现运行时差异,缓存键绑定 go.sum 让依赖下载秒级完成。

技术要点

  • tidy diff 检查防依赖漂移入库
  • race 检测器抓数据竞争
  • 打标签触发交叉编译产物上传

代码解读

verify 任务先做模块卫生检查——tidy 后 git diff 非零退出即失败;vet 与 golangci-lint 两级静态把关;测试带 -race -count=1 防缓存假绿,覆盖率档案仅在一个矩阵分支上传避免重复。release 任务用 needs 与标签条件门控,交叉编译出 Linux 与 macOS 两个二进制。

使用建议

race 检测有数倍开销,超慢套件可拆夜间全量。发布产物建议附带校验和文件。action 版本锁定主版本号防上游突变。

代码示例

// .github/workflows/ci.yml
name: go-ci

on:
  push:
    branches: [main]
  pull_request:

env:
  GOFLAGS: -trimpath

jobs:
  verify:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        go: ['1.22', '1.23']
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version: ${{ matrix.go }}
          cache: true
          cache-dependency-path: go.sum

      - name: Check module hygiene
        run: |
          go mod tidy
          git diff --exit-code go.mod go.sum

      - name: Vet
        run: go vet ./...

      - name: Lint
        uses: golangci/golangci-lint-action@v6
        with:
          version: latest

      - name: Test with race detector
        run: go test -race -count=1 -coverprofile=cover.out ./...

      - name: Upload coverage
        if: matrix.go == '1.23'
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: cover.out

  release:
    needs: verify
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.23'
          cache: true
      - name: Build release binaries
        run: |
          CGO_ENABLED=0 go build -ldflags="-s -w" -o dist/tool-linux-amd64 ./cmd/tool
          CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o dist/tool-darwin-arm64 ./cmd/tool
      - uses: actions/upload-artifact@v4
        with:
          name: release-binaries
          path: dist/