如何在CentOS上配置Golang Web服务器

986
2025/4/10 15:32:55
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上配置Golang Web服务器的步骤如下:

1. 安装Golang

首先,你需要在CentOS上安装Golang。你可以从Golang官方网站下载适用于Linux的安装包。

使用yum安装Golang

sudo yum install golang

手动安装Golang

  1. 下载Golang安装包:
wget https://golang.org/dl/go1.17.6.linux-amd64.tar.gz
  1. 解压安装包:
sudo tar -C /usr/local -xzf go1.17.6.linux-amd64.tar.gz
  1. 配置环境变量:

编辑/etc/profile.d/golang.sh文件,添加以下内容:

export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

然后使配置生效:

source /etc/profile.d/golang.sh

2. 创建Web服务器项目

在你的工作目录下创建一个新的Go项目:

mkdir mywebserver
cd mywebserver

创建一个简单的Go Web服务器:

// 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)
    }
}

3. 运行Web服务器

在项目目录下运行以下命令启动Web服务器:

go run main.go

4. 访问Web服务器

打开浏览器,访问http://your_server_ip:8080,你应该会看到"Hello, World!"的消息。

5. 配置防火墙

为了确保外部可以访问你的Web服务器,你需要配置CentOS的防火墙。

使用firewalld配置防火墙

  1. 启动firewalld服务:
sudo systemctl start firewalld
  1. 允许HTTP和HTTPS流量:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
  1. 重新加载防火墙配置:
sudo firewall-cmd --reload

6. 使用systemd管理服务(可选)

为了更方便地管理你的Web服务器,你可以创建一个systemd服务。

  1. 创建一个新的systemd服务文件:
sudo nano /etc/systemd/system/mywebserver.service
  1. 添加以下内容:
[Unit]
Description=My Go Web Server
After=network.target

[Service]
User=your_username
Group=your_groupname
ExecStart=/usr/local/go/bin/go run /path/to/your/project/main.go
Restart=always

[Install]
WantedBy=multi-user.target
  1. 启动并启用服务:
sudo systemctl daemon-reload
sudo systemctl start mywebserver
sudo systemctl enable mywebserver

现在,你的Golang Web服务器应该在CentOS上运行,并且可以通过浏览器访问。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: CentOS VirtualBox性能优化怎么做