跳到主要内容

CI/CD

问题

Go 项目如何搭建 CI/CD 流水线?

答案

GitHub Actions

# .github/workflows/ci.yml
name: CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'

- name: Lint
uses: golangci/golangci-lint-action@v6

- name: Test
run: go test -race -coverprofile=coverage.out ./...

- name: Coverage
run: go tool cover -func=coverage.out

build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'

- name: Build
run: CGO_ENABLED=0 go build -o app ./cmd/server

- name: Docker Build & Push
uses: docker/build-push-action@v5
with:
push: true
tags: myregistry/app:${{ github.sha }}

CI 流程

CD 部署

  deploy:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Deploy to K8s
run: |
kubectl set image deployment/app \
app=myregistry/app:${{ github.sha }}

常见面试问题

Q1: Go 项目 CI 最少该做什么?

答案

  1. golangci-lint — 代码质量
  2. go test -race — 单元测试 + 竞态检测
  3. go build — 确保编译通过

这三步能拦住大部分问题。

相关链接