众所周知,Github Actions可以执行工作流任务,而且免费版本还具备三种系统和两种架构可选,这就非常适合拿来编译代码。
这是一个编译 Go 代码 Github Actions Workflow 文件模版,可以把简单的 Go 项目分别编译成 3 个平台 2 种架构的可执行程序。
工作流文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| name: Build Go Project
on: workflow_dispatch:
jobs: build: runs-on: ${{ matrix.os }}
strategy: matrix: os: [windows-latest, ubuntu-latest, macos-latest] arch: [amd64, arm64]
steps: - name: Checkout code uses: actions/checkout@v2
- name: Set up Go uses: actions/setup-go@v2 with: go-version: '1.24'
- name: Build for ${{ matrix.os }} ${{ matrix.arch }} shell: bash run: | repo_full_name="${{ github.repository }}" repo_name=$(echo "$repo_full_name" | cut -d'/' -f2) export GOARCH=${{ matrix.arch }} echo "运行平台架构:$RUNNER_OS/$GOARCH" if [ "$RUNNER_OS" = "Windows" ]; then export GOOS=windows suffix='.exe' elif [ "$RUNNER_OS" = "Linux" ]; then export GOOS=linux suffix='' elif [ "$RUNNER_OS" = "macOS" ]; then export GOOS=macos suffix='' fi go build -o output/${repo_name}_${{ matrix.os }}_${{ matrix.arch }}${suffix} main.go
- name: Upload Build Artifacts uses: actions/upload-artifact@v4 with: name: ${{ matrix.os }}_${{ matrix.arch }} path: output/*
|
使用说明
1. 在你的 Go 项目仓库根目录创建一个go.yml文件,并填入上面的内容。
2. 在 GitHub 仓库页面的 Actions 选项卡中手动点击 Run workflow 开始构建。
3. 工作流会根据go.yml文件中matrix选择的平台架构矩阵,自动执行并构建对应平台架构的可执行文件。
4. 构建完成后,指定目录构建产物(target/)会被上传至对应的构建产物列表中,便于下载和后续使用。
注意事项
这个工作流只会把go的编译产物(output/)上传到构建产物中,如果需要上传多个文件,请自行配置go.yml中path: output/*
依赖项目
其中使用了 actions/setup-go 的脚本安装 stable 版本的 go 工具链,感谢脚本作者的辛勤维护~