目 录CONTENT

文章目录

Go学习:开发第一个gin程序,实现API

Administrator
2025-12-18 / 0 评论 / 0 点赞 / 2 阅读 / 0 字

Go学习:构建第一个Gin程序

最近我们做出了从FastAPI切换到Go Gin框架,是一个重大的技术决策。主要在于并发性能限制和硬件开销成本的考虑,因此我们选择使用Go作为我们新后端服务语言,采用Gin作为编程框架。 Gin Web Framework | Gin Web Framework

性能优势

原生并发模型Go的goroutine是轻量级线程,占用内存仅2KB左右,而Python线程通常需要数MB。这意味着Go可以轻松处理数万个并发连接,而FastAPI受限于Python的GIL(全局解释器锁)和asyncio的事件循环模型。

编译型语言优势Go编译成机器码直接执行,比Python解释执行快5-50倍不等。对于CPU密集型操作,这个差距更明显。Gin的路由性能测试显示QPS(每秒请求数)通常是FastAPI的3-10倍。

内存效率Go的内存管理更高效,垃圾回收延迟低。相同业务场景下,Go服务的内存占用通常只有Python的1/3到1/2。

并发处理能力

天然支持高并发:Go的go关键字让并发编程变得简单。不需要像Python那样考虑async/await、事件循环、线程池等复杂概念。Gin配合Go的并发特性,可以用极少的代码实现高性能并发处理。

更好的IO处理Go的网络库是为高并发设计的,epoll/kqueue等机制原生集成。FastAPI虽然基于asyncio,但Python的异步生态成熟度和性能仍逊于Go。

Gin框架特点

轻量且快速Gin是Go生态中最流行的Web框架之一,路由基于Radix树,性能极佳。框架本身非常轻量,不像一些Python框架那样臃肿。

中间件生态成熟:丰富的中间件支持,包括日志、监控、限流、认证等,且都是为高性能场景设计的。

API设计友好:Gin的API设计简洁直观,与FastAPI类似的路由定义方式,迁移学习曲线相对平缓。

运维优势

单一二进制部署Go编译后是单个可执行文件,无需依赖环境、虚拟环境或解释器。这大大简化了部署和容器化。

更低的资源消耗:相同负载下,Go服务需要的服务器资源更少,可以节省云服务成本。

更好的可观测性:Go内置pprof工具,可以方便地进行性能分析。相比Python的性能分析工具,Go的工具更成熟和准确。

Gin程序的主函数:main

package main

import (
    "fmt"
    "gin-demo/router"
    "gin-demo/utils"
)

// main 应用程序入口函数
func main() {

    // 初始化路由
    gin_router := router.InitRouter()

    // 启动HTTP服务
    utils.Logger.Info(fmt.Sprintf("服务启动中,监听端口: %d", 8992))
    if err := gin_router.Run(":8992"); err != nil {
        utils.Logger.Fatal(fmt.Sprintf("HTTP服务启动失败: %s", err.Error()))
    }
}

自定义路由: Router

package router

import (
    "gin-demo/middleware"

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

// 初始化路由: Router
func InitRouter() *gin.Engine {
    router := gin.Default()
    // 全局跨域中间件
    router.Use(middleware.CORSMiddleware())
    // 全局鉴权中间件
    router.Use(middleware.UserAuthMiddleWare())
    
    
    // 添加基本路由
    router.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Gin应用运行成功!",
            "status": "running",
            "port": 8992,
        })
    })
    
    router.GET("/api/health", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "status": "ok",
            "message": "服务健康",
        })
    })
    
    //todo 后续有新的路由就可以添加到这里,添加路由分组
    //groupV1 := router.Group("/api/v1/gin/")
    return router
}

编译并启动gin程序

ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ go build -o gin-app main.go
./gin-app
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> gin-demo/router.InitRouter.func1 (5 handlers)
[GIN-debug] GET    /api/health               --> gin-demo/router.InitRouter.func2 (5 handlers)
{"file":"main.go:16","func":"main.main","level":"info","msg":"服务启动中,监听端口: 8992","time":"2025-12-18 23:11:19"}
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8992

验证程序和API是否正常

ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ curl http://localhost:8992/
{"message":"Gin应用运行成功!","port":8992,"status":"running"}ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ 
ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ 
ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ curl http://localhost:8992/api/health/
<a href="/api/health">Moved Permanently</a>.

ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ curl http://localhost:8992/api/health
{"message":"服务健康","status":"ok"}ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ 
ctyun@00gcbjih-0OqRgn1nUE:/media/vdb/code/gin-demo$ 
在gin程序日志可以看到
```shell
[GIN] 2025/12/18 - 23:21:33 | 200 |     122.177µs |       127.0.0.1 | GET      "/"
[GIN-debug] redirecting request 301: /api/health --> /api/health
{"file":"auth_middleware.go:14","func":"gin-demo/router.InitRouter.UserAuthMiddleWare.func4","level":"debug","msg":"/api/health","time":"2025-12-18 23:11:21"}
[GIN] 2025/12/18 - 23:21:46 | 200 |     362.466µs |       127.0.0.1 | GET      "/api/health"

谢谢关注收藏

刚刷到的朋友注意啦!点击【关注】锁定宝藏库,从此升职加薪不迷路 ✨


我的个人博客网站: https://funkygod.vip


📢 腾讯云资源限时福利

云服务器、CDN、对象存储、网络防护等需求的朋友,欢迎联系下方腾讯云官方销售 👇

轻量云主机限时优惠

RackNerd

☁ 主机显示特惠:只要80元(3TB流量,1vcpu,50GB硬盘),且多区域IDC机房。 购买地址https://my.racknerd.com/aff.php?aff=14942

CloudCone

CloudCone 特惠轻量云主机购买地址https://app.cloudcone.com/?ref=12332

0
Gin
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区