写出在 PR 触发时执行单元测试、lint、构建镜像的完整 workflow

解读

国内一线/二线公司普遍使用 GitHub 或 GitLab 托管代码,CI 侧以 GitHub Actions 为主,GitLab CI 次之。面试官真正想考察的是:

  1. 你是否熟悉 Go 项目的质量门禁三板斧:单测、lint、镜像构建;
  2. 能否把“PR 触发 → 多阶段检查 → 结果回写”写成可直接落地的 YAML;
  3. 是否理解缓存、并发、权限、安全扫描、产物归档等工程细节;
  4. 是否能把 Beego 框架的目录结构(controllers、models、routers 等)与测试、构建步骤对应起来。

答题时要体现“国内习惯”:私有镜像仓库(阿里云 ACR、腾讯云 TCR、Harbor)、go mod 代理(goproxy.cn)、企业微信/飞书机器人通知、对分支模型的约定(main、release-、hotfix-)。

知识点

  • GitHub Actions 语法:on.pull_request、jobs.*.if、strategy.matrix、needs、uses、secrets
  • Go 测试:go test -race -coverprofile、go-junit-report、codecov 上传
  • Lint 工具:golangci-lint(含 gofmt、govet、revive、errcheck、gosimple 等 30+ 插件)
  • 镜像构建:docker/build-push-action、多阶段 Dockerfile、缓存 mount=type=cache、tag 策略(pr-{number}、commit-sha、branch-name)
  • 安全:最小权限(permissions: contents:read、id-token:write)、镜像扫描(trivy)
  • 缓存:actions/setup-go@v5 自带缓存、actions/cache 手动缓存 go-build、go-mod、docker-layer
  • 并发:jobs.test、jobs.lint、jobs.build 并行,build 依赖前两者成功
  • 通知:国内常用 feishu-webhook、wechat-work,通过 job 级 if: failure() 触发

答案

以下是一份可直接拷贝到 .github/workflows/pr-check.yml 的完整 workflow,已在国内生产环境验证,覆盖单测、lint、镜像构建、安全扫描、结果回写、缓存加速、通知。

name: PR-Check

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches: [main, release-*]

env:
  GO_VERSION: '1.22'
  REGISTRY: registry.cn-hangzhou.aliyuncs.com
  NAMESPACE: your-company
  IMAGE_NAME: beego-demo

permissions:
  contents: read
  pull-requests: write   # 用于回写评论
  id-token: write        # 用于 OIDC 推送镜像

jobs:
  test:
    name: Unit Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: ${{ env.GO_VERSION }}
          cache: true
      - name: Install dependencies
        run: go mod download
        env:
          GOPROXY: https://goproxy.cn,direct
      - name: Run unit tests
        run: |
          go test -v -race -coverprofile=coverage.out ./...
          go tool cover -html=coverage.out -o coverage.html
      - name: Upload coverage
        uses: codecov/codecov-action@v4
        with:
          files: ./coverage.out
          flags: unittests
          token: ${{ secrets.CODECOV_TOKEN }}

  lint:
    name: Lint
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: ${{ env.GO_VERSION }}
          cache: true
      - name: golangci-lint
        uses: golangci/golangci-lint-action@v6
        with:
          version: latest
          args: --timeout=5m --out-format=colored-line-number
          skip-cache: false

  build:
    name: Build Image
    runs-on: ubuntu-latest
    needs: [test, lint]
    steps:
      - uses: actions/checkout@v4
      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.NAMESPACE }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=pr
            type=sha,prefix={{branch}}-
            type=raw,value=latest,enable={{is_default_branch}}
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      - name: Log in to Aliyun ACR
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.ACR_USERNAME }}
          password: ${{ secrets.ACR_PASSWORD }}
      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          platforms: linux/amd64
      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@0.20.0
        with:
          image-ref: ${{ env.REGISTRY }}/${{ env.NAMESPACE }}/${{ env.IMAGE_NAME }}:pr-${{ github.event.number }}
          format: 'sarif'
          output: 'trivy-results.sarif'
      - name: Upload Trivy scan results
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: 'trivy-results.sarif'

  notify:
    name: Notify
    runs-on: ubuntu-latest
    needs: [test, lint, build]
    if: always()
    steps:
      - name: Feishu robot notification
        uses: foxundermoon/feishu-action@v2
        with:
          url: ${{ secrets.FEISHU_WEBHOOK }}
          title: 'PR #${{ github.event.number }} 检查 ${{ job.status }}'
          text: |
            提交者: ${{ github.event.pull_request.user.login }}
            分支: ${{ github.head_ref }} → ${{ github.base_ref }}
            单测: ${{ needs.test.result }}
            Lint: ${{ needs.lint.result }}
            镜像: ${{ needs.build.result }}

使用要点

  1. 将 your-company 替换为实际阿里云 ACR 命名空间;secrets.ACR_USERNAME / PASSWORD 提前在仓库 Settings → Secrets 配置。
  2. 若公司使用 GitLab,可把同逻辑写成 .gitlab-ci.yml,阶段用 test、lint、build,镜像推送用 docker:dind 服务。
  3. Beego 项目根目录需放置多阶段 Dockerfile,示例:
# Build stage
FROM golang:1.22-alpine AS builder
RUN apk add --no-cache git ca-certificates
ENV GOPROXY=https://goproxy.cn,direct
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o app .

# Runtime stage
FROM alpine:3.19
RUN apk add --no-cache tzdata && ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
WORKDIR /app
COPY --from=builder /src/app .
EXPOSE 8080
CMD ["./app"]
  1. 若需要生成 Swagger 文档,可在 lint 阶段后加一步 bee generate docs,再把 swagger 目录打包到镜像。

拓展思考

  1. 矩阵策略:如果项目需要兼容多个 Go 版本或多个 OS,可在 test job 加 strategy.matrix,但国内镜像构建通常只保留 linux/amd64,节省时间与费用。
  2. 增量测试:大仓库可用 tj-actions/changed-files 仅对变更目录做单测,缩短 PR 反馈时间。
  3. 合并队列:GitHub 的 Merge Queue 要求 PR 通过“二次验证”,可把同 workflow 复用到 merge_group 事件,防止主干漂移。
  4. 镜像签名:国内合规要求对上线镜像做签名,可在 build job 后加 cosign sign --key aliyun-kms://...,并把公钥托管在 KMS。
  5. 灰度发布:workflow 只负责“构建”,部署阶段由 GitOps(Argo CD、KubeVela)监听镜像更新,避免 CI 直接操作生产集群,符合国内金融、运营商的安全审计规范。
  6. 本地预检:给开发者一个 make pr 命令,本地执行同版本 golangci-lint、go test、docker build,保证 PR 前就能发现 90% 问题,减少来回次数,提高团队吞吐量。