温馨提示×

怎样在centos上搭建golang服务器

小樊
45
2025-12-23 08:13:46
栏目: 云计算

在CentOS上搭建Go语言服务器的步骤如下:

  1. 安装Go语言环境: 首先,你需要在CentOS系统上安装Go语言。可以通过以下命令安装:

    sudo yum install golang
    

    或者,你可以从Go官方网站下载最新的Go安装包,并按照官方文档进行安装。

  2. 设置Go环境变量: 安装完成后,你需要设置GOROOTGOPATH环境变量。通常,GOROOT是Go的安装路径,而GOPATH是你工作空间的路径。你可以在你的~/.bashrc~/.bash_profile文件中添加以下内容:

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

    然后,运行以下命令使环境变量生效:

    source ~/.bashrc
    
  3. 编写Go服务器代码: 使用你喜欢的文本编辑器创建一个新的Go文件,例如server.go,并编写一个简单的HTTP服务器代码:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    }
    
    func main() {
        http.HandleFunc("/", handler)
        fmt.Println("Server starting at :8080")
        if err := http.ListenAndServe(":8080", nil); err != nil {
            fmt.Println(err)
        }
    }
    
  4. 运行Go服务器: 在终端中,切换到包含server.go文件的目录,并运行以下命令来启动服务器:

    go run server.go
    

    如果一切正常,你应该会看到输出Server starting at :8080,表示服务器已经启动并监听在8080端口。

  5. 测试服务器: 打开浏览器,访问http://your_server_ip:8080,你应该能看到输出Hello, World!

  6. (可选)使用systemd管理Go服务器: 如果你想让Go服务器作为服务在后台运行,并且在系统启动时自动启动,你可以创建一个systemd服务文件。例如,创建一个名为go-server.service的文件:

    [Unit]
    Description=Go Web Server
    After=network.target
    
    [Service]
    ExecStart=/usr/local/go/bin/go run /path/to/your/server.go
    Restart=always
    User=your_username
    Group=your_groupname
    Environment=GOROOT=/usr/local/go
    Environment=GOPATH=/home/your_username/go
    
    [Install]
    WantedBy=multi-user.target
    

    /path/to/your/server.go替换为你的Go服务器代码的实际路径,your_usernameyour_groupname替换为你的用户名和组名。然后,运行以下命令启用并启动服务:

    sudo systemctl enable go-server.service
    sudo systemctl start go-server.service
    

    现在,你的Go服务器将作为systemd服务运行,并在系统启动时自动启动。

以上步骤应该可以帮助你在CentOS上成功搭建Go语言服务器。记得根据实际情况调整路径和配置。

0