在CentOS上使用Golang搭建Web服务器是一个相对简单的过程。以下是详细的步骤:
首先,你需要在CentOS上安装Golang。你可以从Golang的官方网站下载适合你系统的安装包。
sudo yum install -y golang
如果你更喜欢手动安装,可以按照以下步骤进行:
wget https://golang.org/dl/go1.20.4.linux-amd64.tar.gz
/usr/local
目录:sudo tar -C /usr/local -xzf go1.20.4.linux-amd64.tar.gz
编辑~/.bashrc
或~/.bash_profile
文件,添加以下内容:
export PATH=$PATH:/usr/local/go/bin
然后使配置生效:
source ~/.bashrc
创建一个新的Go文件,例如main.go
,并添加以下代码:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
fmt.Println("Starting server at port 8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println(err)
}
}
在终端中导航到包含main.go
文件的目录,然后运行以下命令来启动服务器:
go run main.go
你应该会看到输出:
Starting server at port 8080
打开浏览器,访问http://your_server_ip:8080
,你应该会看到页面上显示“Hello, World!”。
如果你希望从外部网络访问你的Web服务器,你需要设置防火墙规则以允许HTTP流量。
sudo firewall-cmd --permanent --zone=public --add-port=8080/tcp
sudo firewall-cmd --reload
为了更方便地管理Golang服务,你可以创建一个systemd服务文件。
sudo nano /etc/systemd/system/golang-server.service
[Unit]
Description=Golang Web Server
After=network.target
[Service]
ExecStart=/usr/local/go/bin/go run /path/to/your/main.go
Restart=always
User=your_username
Group=your_groupname
Environment=PATH=/usr/local/go/bin
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start golang-server
sudo systemctl enable golang-server
现在,你的Golang Web服务器已经systemd服务运行,并且会在系统启动时自动启动。
通过以上步骤,你就可以在CentOS上成功搭建一个简单的Golang Web服务器了。