本文主要为了解决以下问题
- Golang 在Windows下编译Linux下可执行文件
- Golang 在windows下编译Mac下可执行文件
- Golang 在Linux下编译Windows下可执行文件
- Golang 在Mac下编译Windows下可执行文件
golang提供的解决方案是,先设置环境变量再执行编译,但是如果要同时编译多个平台的可执行文件该怎么做呢
如下图,我们经常在github上看到好多项目下面有各种平台及架构的release,他们是怎么做到的呢
下面就来介绍一下打包神器 GoReleaser
goreleaser是一个自动化打包工具,解放双手,省去脚本编写,同时还支持对接CI/CD。
下面我们通过一个简单的例子来说明怎么使用 GoReleaser
1. 工具安装
下载安装 goreleaser
安装后执行 goreleaser -v 命令判断是否安装成功
2. 创建demo工程
创建一个简单的demo项目(demo1)
包含一个源文件 demo1.go
package main import "fmt" func main() { fmt.Println("hello world") }
3. 初始化配置
然后在该项目根目录执行 goreleaser init ,将会生成一个.goreleaser.yml配置文件
# This is an example goreleaser.yaml file with some sane defaults. # Make sure to check the documentation at http://goreleaser.com before: hooks: # you may remove this if you don't use vgo - go mod tidy # you may remove this if you don't need go generate - go generate ./... builds: - env: - CGO_ENABLED=0 archives: - replacements: darwin: Darwin linux: Linux windows: Windows 386: i386 amd64: x86_64 checksum: name_template: 'checksums.txt' snapshot: name_template: "{{ .Tag }}-next" changelog: sort: asc filters: exclude: - '^docs:' - '^test:'
4. 修改配置
默认配置文件需要稍作修改以满足我们的需求
我们的demo项目没有使用vgo,需要把 – go mod tidy 注释掉
也没有使用go generate,需要把 – go generate ./… 注释掉
添加我们需要的目标操作系统类型及架构
经过修改后的配置文件如下
# This is an example goreleaser.yaml file with some sane defaults. # Make sure to check the documentation at http://goreleaser.com before: hooks: # you may remove this if you don't use vgo # - go mod tidy # you may remove this if you don't need go generate # - go generate ./... builds: - env: - CGO_ENABLED=0 id: "demoproj" binary: "demo1" goos: - darwin - freebsd - linux - netbsd - openbsd - windows goarch: - 386 - amd64 - arm archives: - replacements: darwin: Darwin linux: Linux windows: Windows 386: i386 amd64: x86_64 checksum: name_template: 'checksums.txt' snapshot: name_template: "v1.0.0-snapshot" changelog: sort: asc filters: exclude: - '^docs:' - '^test:'
5. 打包
然后执行打包命令来验证是否打包成功
goreleaser --snapshot --skip-publish --rm-dist
打包成功后将会在项目根目录/dist下生成各种不同平台的可执行文件
配置文件说明
id:打包后目录前缀
goos:目标系统
goarch:目标CPU架构
snapshot.name_template:生成压缩包名称前缀
详细配置请参考官网
build配置: 编译配置
archives配置:打包配置
goos和goarch是乘积关系,至于为什么没有生成windows_arm64这样的可执行程序 是因为windows不能再arm上跑 哈哈哈哈哈
golang官网也列出了goos和goarch的兼容表
The valid combinations of GOOS and GOARCH are:
GOOS | GOARCH |
---|---|
aix | ppc64 |
android | 386 |
android | amd64 |
android | arm |
android | arm64 |
darwin | 386 |
darwin | amd64 |
darwin | arm |
darwin | arm64 |
dragonfly | amd64 |
freebsd | 386 |
freebsd | amd64 |
freebsd | arm |
illumos | amd64 |
js | wasm |
linux | 386 |
linux | amd64 |
linux | arm |
linux | arm64 |
linux | ppc64 |
linux | ppc64le |
linux | mips |
linux | mipsle |
linux | mips64 |
linux | mips64le |
linux | s390x |
netbsd | 386 |
netbsd | amd64 |
netbsd | arm |
openbsd | 386 |
openbsd | amd64 |
openbsd | arm |
openbsd | arm64 |
plan9 | 386 |
plan9 | amd64 |
plan9 | arm |
solaris | amd64 |
windows | 386 |
windows | amd64 |