Ubuntu Golang 项目的持续集成实践
一 方案总览与前置准备
二 GitHub Actions 完整示例
name: Go CI
on:
push:
branches: [ main ]
tags: [ 'v*' ]
pull_request:
branches: [ main ]
jobs:
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.21'
- name: Cache Go modules
uses: actions/cache@v3
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Tidy dependencies
run: go mod tidy -compat=1.21
- name: Build
run: go build -v ./...
- name: Test with race detector
run: go test -race -coverprofile=coverage.txt -covermode=atomic ./...
- name: Vet
run: go vet ./...
- name: Lint
run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh \
| sh -s -- -b $(go env GOPATH)/bin v1.57.2
$(go env GOPATH)/bin/golangci-lint run --timeout=5m
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.txt
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: binary-${{ github.sha }}
path: |
myapp
bin/
release:
needs: build-test
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: binary-${{ github.sha }}
path: dist
- name: Release
uses: softprops/action-gh-release@v1
with:
files: dist/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
三 GitLab CI 完整示例
stages:
- build
- test
variables:
CGO_ENABLED: 0
build:
stage: build
image: golang:1.21
script:
- go mod tidy -compat=1.21
- go build -v -o bin/app ./...
artifacts:
paths:
- bin/
test:
stage: test
image: golang:1.21
script:
- go test -race -coverprofile=coverage.txt -covermode=atomic ./...
- go vet ./...
四 质量与效率优化要点
五 部署与扩展选项