Alaways be curious to learn more and achieve more.
0%
Build Go Executables for Multiple Platforms
发表于阅读次数:本文字数:2.6k阅读时长 ≈2 分钟
构建Go可执行文件
Go most powerful features is the ability to cross-build(跨平台交叉编译构建可执行文件)executables for any Go-supported foreign platform.
Installing Go Programs from Version Control
1
$ go get -u package-import-path
Building an Executable
1 2
# This command creates the executable, and also create the ./build directory if it doesn't exist $ go build -o build/caddy-server github.com/mholt/caddy/caddy
Installing an Executable
1
$ go install github.com/mholt/caddy/caddy
Cross Compiling
1 2 3 4 5 6
> Cross-compiling works by setting required environment variables that specify the target operating systemand architecture. - GOOS: the target operating system - GOARCH: the target architecture
# the env command runs a program in a modified environment. $ env GOOS=target-OS GOARCH=target-architecture go build package-import-path
$ cd ~ $ vim go-executable-build.sh #!/usr/bin/env bash
###################################################################### # @author : chyiyaqing (404@gmail.com) # @file : go-executable-build # @created : Tuesday Oct 26, 202118:22:35 CST # # @description : Creating a Script to Automate Cross-Compilation go build ######################################################################
# $0 -- contains the name of the script you executed package=$1
# Make sure the user provided this value if [[ -z "$package" ]]; then echo "usage: $0 <package-name>" # 0 for successful executions and any non-zero value for unsuccessful executions exit 1 fi
# extract the package name from the ath package_split=(${package//\// }) package_name=${package_split[-1]}
# ierate though the array of platforms, split each platform into values for the GOOS and GOARCH for platform in"${platform[@]}" do platform_split = (${platform//\// }) GOOS=${platform_split[0]} GOARCH=${platform_split[1]}
output_name=$package_name'-'$GOOS'-'$GOARCH
if [ $GOOS = "windows" ]; then ¦ output_name+='.exe' fi
env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package
# check if there were errors building the executable if [ $? -ne 0 ]; then echo 'An error has occurred! Aborting the script execution...' ¦exec 1 fi done