Last active
May 26, 2024 10:28
-
-
Save naranyala/07cfb522e164d465b954f97d3836e2b4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
getGoVersion() { | |
versionInfo=$(go version 2>&1) | |
if [ $? -ne 0 ]; then | |
echo "Error executing 'go version' command: $versionInfo" >&2 | |
return 1 | |
fi | |
version=$(echo $versionInfo | awk '{print $3}') | |
if [ -z "$version" ]; then | |
echo "Unable to parse Go version" >&2 | |
return 1 | |
fi | |
version=${version#go} | |
echo $version | |
return 0 | |
} | |
GO_VERSION=$(getGoVersion) | |
read -p "Do you want to create a new directory for your Go project? (y/n): " create_new_directory | |
if [ "$create_new_directory" == "y" ]; then | |
read -p "Enter your Go project name: " project_name | |
mkdir "$project_name" | |
cd "$project_name" || exit | |
fi | |
touch go.mod | |
echo "module $project_name" >>go.mod | |
echo "" >>go.mod | |
echo "go $GO_VERSION" >>go.mod | |
mkdir cmd | |
touch cmd/main.go | |
echo "package main" >>cmd/main.go | |
echo "" >>cmd/main.go | |
echo "import \"fmt\"" >>cmd/main.go | |
echo "" >>cmd/main.go | |
echo "func main() {" >>cmd/main.go | |
echo " fmt.Println(\"hello from: $project_name\")" >>cmd/main.go | |
echo "}" >>cmd/main.go | |
if [ -f "go.mod" ]; then | |
touch build.sh | |
echo "#!/bin/bash" >>build.sh | |
echo "" >>build.sh | |
echo "get_module_name() { " >>build.sh | |
echo 'grep "^module" go.mod | awk '"'"'{print $2}'"'"' | cut -d / -f 2' >>build.sh | |
echo "}" >>build.sh | |
echo "" >>build.sh | |
echo 'MODULE_NAME=$(get_module_name)' >>build.sh | |
echo "" >>build.sh | |
echo 'if [ -z "$MODULE_NAME" ]; then' >>build.sh | |
echo " echo "Error: Could not determine module name from go.mod"" >>build.sh | |
echo " exit 1" >>build.sh | |
echo "fi" >>build.sh | |
echo "" >>build.sh | |
echo 'mkdir -p bin' >>build.sh | |
echo 'GOOS=darwin GOARCH=amd64 go build -o "bin/${MODULE_NAME}-darwin-amd64" ./cmd' >>build.sh | |
echo 'GOOS=linux GOARCH=amd64 go build -o "bin/${MODULE_NAME}-linux-amd64" ./cmd' >>build.sh | |
echo 'GOOS=windows GOARCH=amd64 go build -o "bin/${MODULE_NAME}-windows-amd64.exe" ./cmd' >>build.sh | |
echo '' >>build.sh | |
echo 'echo "Build completed. Binaries are in the bin/ directory."' >>build.sh | |
chmod +x build.sh | |
else | |
echo "go.mod file does not exist in the current directory." | |
fi | |
echo -e "\nYour Go project has been initialized!" | |
echo -e "To run your Go program, use: \n\n\tgo run main.go\n" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment