03.GoReleaser配置 构建
GoReleaser 通过其 builder 接口支持多种编程语言和构建系统。 builder 接收构建配置,并将二进制文件/库输出到 dist 目录中。
Builders
各种语言的配置参见: Builders – GoReleaser
Build Hook
对于每个构建目标,无论这些目标是通过操作系统和架构的矩阵生成的,还是在 targets 中显式定义的,也无论使用何种 builder ,都会执行相应的pre钩子和post钩子。
builds:
- id: "with-hooks"
builder: go
targets:
- "darwin_amd64"
- "windows_amd64"
hooks:
pre:
- first-script.sh
- second-script.sh
post:
- upx "{{ .Path }}"
- codesign -project="{{ .ProjectName }}" "{{ .Path }}"
每个钩子还可以拥有自己的工作目录和环境变量
builds:
- id: "with-hooks"
builder: go
targets:
- "darwin_amd64"
- "windows_amd64"
hooks:
pre:
- cmd: first-script.sh
dir:
"{{ dir .Dist}}"
# Always print command output, otherwise only visible in debug mode.
output: true
env:
- HOOK_SPECIFIC_VAR={{ .Env.GLOBAL_VAR }}
- second-script.sh
钩子的所有属性(cmd、dir 和 env)均支持模板,且 post 钩子可访问二进制构建产物(因为这些钩子在构建完成后运行)。此外,以下构建详细信息对前处理钩子和后处理钩子均可见:
| Key | Description |
|---|---|
| .Name | 二进制文件名, e.g. bin.exe |
| .Ext | 扩展名, e.g. .exe |
| .Path | 二进制文件的绝对路径 |
| .Target | 构建产物的目标平台, e.g. darwin_amd64 |
环境变量的继承和覆盖按以下顺序进行
- global (
env) - build (
builds[].env) - hook (
builds[].hooks.pre[].envandbuilds[].hooks.post[].env)
可验证构建
GoReleaser 支持创建可验证构建。可验证构建是指记录了足够信息,能够精确说明如何重现该构建的构建。
所有依赖项均通过 proxy.golang.org 加载,并针对校验和数据库 sum.golang.org 进行验证。由 GoReleaser 创建的可验证构建会在生成的二进制文件中包含模块信息,可通过执行 go version -m mybinary 命令打印出来。
可用的配置选项如下所述。
gomod:
# Proxy a module from proxy.golang.org, making the builds verifiable.
# This will only be effective if running against a tag. Snapshots will ignore
# this setting.
# Notice: for this to work your `build.main` must be a package, not a `.go` file.
proxy: true
# If proxy is true, use these environment variables when running `go mod`
# commands (namely, `go mod tidy`).
#
# Default: `os.Environ()` merged with what you set the root `env` section.
env:
- GOPROXY=https://proxy.golang.org,direct
- GOSUMDB=sum.golang.org
- GOPRIVATE=example.com/blah
# Sets the `-mod` flag value.
mod: mod
# Which Go binary to use.
#
# Default: `go`.
gobinary: go1.17
# Directory in which the go.mod file is.
#
# Default: ''.
dir: ./src
UPX
保持较小的二进制文件大小非常重要,而Go语言以生成体积较大的二进制文件而著称。GoReleaser 从一开始就将 -s -w 作为默认的 ldflags,这有助于节省一些字节,但如果想进一步压缩,
upx
是完成这项任务的首选工具。
GoReleaser 已经能够通过自定义构建钩子与之集成,现在 UPX 拥有了自己的配置部分:
警告 upx 并不支持所有平台!请务必查看其问题列表,并测试打包后的二进制文件。
如果未找到
upx可执行程序,GoReleaser 会避免运行
upx:
- # Whether to enable it or not.
#
# Templates: allowed.
enabled: true
# Filter by build ID.
ids: [build1, build2]
# Filter by GOOS.
goos: [linux, darwin]
# Filter by GOARCH.
goarch: [arm, amd64]
# Filter by GOARM.
goarm: [8]
# Filter by GOAMD64.
goamd64: [v1]
# Compress argument.
# Valid options are from '1' (faster) to '9' (better), and 'best'.
compress: best
# Whether to try LZMA (slower).
lzma: true
# Whether to try all methods and filters (slow).
brute: true