在 Debian 上运行 Golang 程序通常分为 安装 Go → 编写/获取代码 → 编译 → 运行 几个步骤。下面给你一套最常用、最稳妥的做法。
sudo apt update
sudo apt install golang-go
查看版本:
go version
cd /tmp
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
添加到环境变量(~/.bashrc 或 ~/.profile):
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
使配置生效:
source ~/.bashrc
验证:
go version
mkdir ~/hello && cd ~/hello
go mod init hello
nano main.go
内容示例:
package main
import "fmt"
func main() {
fmt.Println("Hello Debian!")
}
go run main.go
go build -o hello
./hello
git clone https://github.com/xxx/yyy.git
cd yyy
go mod tidy
go run main.go
# 或
go build
./yyy
nohup ./hello > app.log 2>&1 &
创建服务文件:
sudo nano /etc/systemd/system/hello.service
内容:
[Unit]
Description=Go Hello Service
After=network.target
[Service]
ExecStart=/home/youruser/hello/hello
WorkingDirectory=/home/youruser/hello
User=youruser
Restart=always
[Install]
WantedBy=multi-user.target
启用并启动:
sudo systemctl daemon-reload
sudo systemctl enable hello
sudo systemctl start hello
查看状态:
sudo systemctl status hello
go: command not found说明 PATH 没配置好,检查:
which go
echo $PATH
go mod tidy
GOOS=linux GOARCH=arm64 go build
如果你愿意,可以告诉我:
我可以给你更针对性的方案。