搬瓦工部署 Gin Go 语言 API 框架教程

Gin 是 Go 语言生态中最流行的 Web 框架,以高性能和简洁的 API 设计著称。Go 语言编译生成的单一二进制文件部署极为方便,无需额外的运行时环境。本文将介绍如何在搬瓦工 VPS 上安装 Go 语言环境、创建 Gin API 项目并部署上线。购买搬瓦工 VPS 请参考 全部方案,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。

一、安装 Go 语言

apt update && apt upgrade -y

# 下载 Go
wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz
rm -rf /usr/local/go
tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz

# 配置环境变量
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
echo 'export GOPATH=$HOME/go' >> ~/.bashrc
echo 'export PATH=$PATH:$GOPATH/bin' >> ~/.bashrc
source ~/.bashrc

go version

二、创建 Gin 项目

mkdir -p /opt/myapi && cd /opt/myapi
go mod init myapi
go get -u github.com/gin-gonic/gin

2.1 编写主程序

cat > /opt/myapi/main.go << 'EOF'
package main

import (
    "log"
    "net/http"
    "os"

    "github.com/gin-gonic/gin"
)

type Response struct {
    Status  string      `json:"status"`
    Message string      `json:"message"`
    Data    interface{} `json:"data,omitempty"`
}

func main() {
    gin.SetMode(gin.ReleaseMode)
    r := gin.Default()

    // 健康检查
    r.GET("/health", func(c *gin.Context) {
        c.JSON(http.StatusOK, Response{
            Status:  "ok",
            Message: "Service is running",
        })
    })

    // API 路由组
    api := r.Group("/api/v1")
    {
        api.GET("/hello/:name", func(c *gin.Context) {
            name := c.Param("name")
            c.JSON(http.StatusOK, Response{
                Status:  "ok",
                Message: "Hello, " + name + "!",
            })
        })

        api.POST("/echo", func(c *gin.Context) {
            var body map[string]interface{}
            if err := c.ShouldBindJSON(&body); err != nil {
                c.JSON(http.StatusBadRequest, Response{
                    Status:  "error",
                    Message: err.Error(),
                })
                return
            }
            c.JSON(http.StatusOK, Response{
                Status:  "ok",
                Message: "Echo",
                Data:    body,
            })
        })
    }

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    log.Printf("Server starting on port %s", port)
    r.Run(":" + port)
}
EOF

三、编译与运行

cd /opt/myapi

# 编译(生成静态链接的二进制文件)
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o myapi .

# 查看二进制文件大小
ls -lh myapi

# 测试运行
./myapi

Go 编译后的二进制文件通常只有 10-20MB,运行时内存占用也非常低。

四、创建 Systemd 服务

cp /opt/myapi/myapi /usr/local/bin/myapi

cat > /etc/systemd/system/gin-api.service << 'EOF'
[Unit]
Description=Gin API Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myapi
Environment=PORT=8080
Environment=GIN_MODE=release
Restart=always
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable gin-api
systemctl start gin-api

五、Nginx 反向代理

apt install nginx -y

cat > /etc/nginx/sites-available/gin.conf << 'EOF'
server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}
EOF

ln -sf /etc/nginx/sites-available/gin.conf /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl restart nginx

六、SSL 证书与部署脚本

apt install certbot python3-certbot-nginx -y
certbot --nginx -d api.yourdomain.com

cat > /opt/myapi/deploy.sh << 'EOF'
#!/bin/bash
cd /opt/myapi
git pull origin main
CGO_ENABLED=0 go build -ldflags="-s -w" -o myapi .
systemctl stop gin-api
cp myapi /usr/local/bin/myapi
systemctl start gin-api
echo "[$(date)] Gin API deployed"
EOF
chmod +x /opt/myapi/deploy.sh

七、添加中间件

Gin 支持丰富的中间件功能,包括日志、认证、限流、CORS 等:

# 常用中间件安装
go get github.com/gin-contrib/cors
go get github.com/gin-contrib/gzip
go get golang.org/x/time/rate

八、数据库集成

# 使用 GORM(Go 语言 ORM)
go get -u gorm.io/gorm
go get -u gorm.io/driver/postgres
# 或使用 MySQL
go get -u gorm.io/driver/mysql

九、常见问题

端口被占用

使用 ss -tlnp | grep 8080 检查端口占用情况。修改 PORT 环境变量更换端口。

交叉编译

Go 支持方便的交叉编译。在本地编译 Linux 二进制文件后直接上传到 VPS:

# 在 macOS 或 Windows 上交叉编译
GOOS=linux GOARCH=amd64 go build -o myapi .

总结

Gin 是 Go 语言最流行的 Web 框架,编译后的二进制文件部署简单、性能优秀、资源占用低。在搬瓦工 VPS 上部署 Go 应用几乎不需要任何运行时依赖,是构建高性能 API 服务的理想选择。其他后端框架教程包括 Actix RustPhoenix ElixirLaravel PHP 等。购买搬瓦工 VPS 请访问 bwh81.net,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。

关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工的方案、优惠和教程。我们不销售主机,不提供技术服务。

新手必读
搬瓦工优惠码

NODESEEK2026(优惠 6.77%)

购买时填入即可抵扣。