在CentOS上实现Golang打包的自动化,可以通过编写Shell脚本来完成。以下是一个简单的示例,展示了如何创建一个自动化脚本,用于构建和打包Golang应用程序。
sudo yum install golang
build.sh
的Shell脚本文件:#!/bin/bash
# 设置项目路径和输出目录
project_path="/path/to/your/golang/project"
output_dir="/path/to/output/directory"
# 进入项目目录
cd $project_path
# 获取当前Git分支名
branch_name=$(git rev-parse --abbrev-ref HEAD)
# 构建二进制文件
GOOS=linux GOARCH=amd64 go build -o $output_dir/your_app_name-$branch_name main.go
# 输出构建结果
if [ $? -eq 0 ]; then
echo "Build successful: $output_dir/your_app_name-$branch_name"
else
echo "Build failed"
fi
build.sh
脚本添加可执行权限:chmod +x build.sh
build.sh
脚本进行自动构建:./build.sh
这个示例脚本会在每次运行时获取当前Git分支名,并将构建好的二进制文件输出到指定的目录。你可以根据实际需求修改脚本中的项目路径、输出目录和二进制文件名。
如果你想要在每次代码提交时自动运行这个脚本,可以考虑使用Git钩子(Git Hooks)。具体来说,可以在.git/hooks
目录下创建一个名为post-commit
的文件,并在其中添加以下内容:
#!/bin/bash
# 运行构建脚本
/path/to/build.sh
然后为post-commit
文件添加可执行权限:
chmod +x .git/hooks/post-commit
这样,每次提交代码时,都会自动运行build.sh
脚本进行构建。