Golang交叉编译

Golang项目开发完成后最终是要放到服务器上去跑的,那么就需要编译出对应平台及CPU构架类型的可执行程序上传到服务器。由于业务需要构建多个平台,每一次都需要多次构建,非常不方便,于是乎可以将其在Shell脚本中自动化的快速构建多个不台平台程序,这样可以省去不必要的没有意义的操作。

查看Golang支持的平台及CPU框架

 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
$ go tool dist list
aix/ppc64
android/386
android/amd64
android/arm
android/arm64
darwin/amd64
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
freebsd/arm64
illumos/amd64
js/wasm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/mips
linux/mips64
linux/mips64le
linux/mipsle
linux/ppc64
linux/ppc64le
linux/riscv64
linux/s390x
netbsd/386
netbsd/amd64
netbsd/arm
netbsd/arm64
openbsd/386
openbsd/amd64
openbsd/arm
openbsd/arm64
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
windows/386
windows/amd64
windows/arm

可以看到当前系统安装的Go语言支持的操作类型及CPU构架详情列表信息,注意,每一行是一种平台及CPU构架描述,非常直观一看就会明白,不用让我们一个一个去到对应服务器上去查看平台类型及CPU构架,非常方便。

构建Shell脚本

 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/bash
#
#
# Use shell script build go program applications.
# Author: helloshaohua.
# Date: 2021.6.13.

BUILD_COMPILE_DIR="../compile"
PLATFORM_AND_CPU_ARCH=("linux/amd64" "darwin/amd64" "linux/arm64" "linux/mips64")
PLATFORM=""
CPU_ARCH=""


# PrintLogFunc Format the print log function.
# This function takes two arguments:
# This first parameter: Description of the log information.
# The second parameter: Output text rendering colors.
function PrintLogFunc()
{
  log_info=$1
  use_color=$2

  # 如果{输出文字渲染颜色}长度为0时,则使用默认颜色.
  if [ -z "$use_color" ]; then
    use_color=0
  fi

  # 如果{输出文字渲染颜色}参数为1时,时使用{蓝色}文字,否则默认文字颜色.
  if [ $use_color = "WARNING" ]; then
    echo -e "\033[31m[`date +"%Y-%m-%d %H:%M:%S"`] WARNING -  ${log_info} \033[0m"
  elif [ $use_color = "INFO" ]; then
    echo -e "\033[32m[`date +"%Y-%m-%d %H:%M:%S"`] INFO -  ${log_info} \033[0m"
  else
    echo "[`date +"%Y-%m-%d %H:%M:%S"`] DEBUG - ${log_info}"
  fi

  # 输出两行空行.
  echo;
}

# GetPlatformAndCPUArchFunc get platfrom and cpu arch info.
function GetPlatformAndCPUArchFunc()
{
  info=$1
  if [ ${#info} == 0 ]; then
    PrintLogFunc "platfrom and cpu arch info can't empty" WARNING
    exit 1
  fi

  INFO_ARR=(${info//// })

  for (( i = 0; i < ${#INFO_ARR[@]}; i++ )); do
    case $i in
    0)
      PLATFORM=${INFO_ARR[i]};;
    1)
      CPU_ARCH=${INFO_ARR[i]};;
    esac
  done
}

# Build on the loop.
for INFO in "${PLATFORM_AND_CPU_ARCH[@]}"; do
  GetPlatformAndCPUArchFunc "$INFO"

  BUILD_PROGRAM_NAME="features.$PLATFORM.$CPU_ARCH"
  GOOS="$PLATFORM" GOARCH="$CPU_ARCH" go build -o "$BUILD_COMPILE_DIR/$BUILD_PROGRAM_NAME" ../cmd/features

  PrintLogFunc "Build $BUILD_PROGRAM_NAME successfully~" INFO
done
comments powered by Disqus