在CentOS上使用Golang开发项目是一个相对简单的过程,以下是详细的步骤:
更新系统包:
sudo yum update -y
安装Golang:
sudo yum install golang -y
sudo dnf install golang -y
/usr/local
目录。wget https://golang.org/dl/go1.20.5.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.20.5.linux-amd64.tar.gz
~/.bashrc
或~/.bash_profile
文件,添加以下内容:export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
使配置生效:source ~/.bashrc
go version
安装IDE(可选):
sudo yum install code -y
Ctrl+Shift+P
,输入Go: Install/Update Tools
,选择并安装所需的工具。File -> Settings -> Go -> GOROOT
和GOPATH
,配置相应的路径。创建第一个Go程序:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
hello.go
,然后在终端中运行:go run hello.go
Hello, World!
初始化Go模块: 在你的项目目录中运行:
go mod init <module-name>
添加依赖:
使用go get
命令安装项目所需的依赖:
go get <dependency>
构建和运行项目:
使用go build
和go run
命令构建和运行你的Go项目。
编译项目:
使用go build
命令对应用程序进行编译:
go build -o myapp main.go
运行项目: 在项目目录中,运行可执行文件:
./myapp
使用systemd管理服务(可选):
/etc/systemd/system/
目录下,新建一个名为myapp.service
的服务文件,填入以下内容:[Unit]
Description=My Go Application
After=syslog.target
[Service]
Type=simple
User=root
WorkingDirectory=/root/myapp
ExecStart=/root/myapp/main
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start myapp.service
sudo systemctl status myapp.service
sudo systemctl enable myapp.service
通过以上步骤,你可以在CentOS上成功搭建Golang开发环境,并开始进行项目开发。如果有更多高级需求,如使用Docker容器化部署,可以参考相关文档进行操作。