Skip to content
鼓励作者:欢迎打赏犒劳

go打包部署

在 Go 语言中,跨平台编译非常简单,只需设置相应的环境变量即可。下面是针对 Linux 和 Windows 系统的打包方法。

linux环境部署

在 Linux 环境下编译(最简单)

shell
# 在 Linux 终端中执行
go build -o myapp-linux main.go

在其他系统上交叉编译为 Linux

shell
# 在 Windows 或 macOS 上编译 Linux 可执行文件
set GOOS=linux&& set GOARCH=amd64&& go build -o myapp-linux main.go

# 如果是 32 位 Linux 系统
set GOOS=linux&& set GOARCH=386&& go build -o myapp-linux-32 main.go

# 如果是 ARM 架构的 Linux(如树莓派)
set GOOS=linux&& set GOARCH=arm&& go build -o myapp-linux-arm main.go

设置权限

确保文件有执行权限:

shell
chmod +x myapp-linux

win环境部署

在 Windows 环境下编译

shell
# 在 Windows 命令提示符中执行  -o 参数用于指定输出文件的名称和位置。
go build -o myapp.exe main.go

在其他系统上交叉编译为 Windows

shell
# 在 Linux 或 macOS 上编译 Windows 可执行文件
GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go

# 如果是 32 位 Windows 系统
GOOS=windows GOARCH=386 go build -o myapp-32.exe main.go

常用环境变量说明

  • GOOS: 目标操作系统

    • linux: Linux 系统
    • windows: Windows 系统
    • darwin: macOS 系统
    • freebsd: FreeBSD 系统
  • GOARCH: 目标架构

    • amd64: 64 位 x86 架构(最常见)
    • 386: 32 位 x86 架构
    • arm: ARM 架构
    • arm64: 64 位 ARM 架构

如有转载或 CV 的请标注本站原文地址