Go Gin SQL 全栈CRUD、事务、迁移、监控全攻略Gin SQL 是后端项目最常见的搭配。本文带你看一眼真实项目的完整闭环。一、项目布局cmd/server internal/{handler, service, repo} internal/config pkg/types configs/config.yaml二、main.gofuncmain(){cfg,_:config.Load()db,_:sql.Open(mysql,cfg.DB.DSN)db.SetMaxOpenConns(50)db.SetMaxIdleConns(10)deferdb.Close()userRepo:repo.NewUserRepo(db)userSvc:service.NewUserService(userRepo)handler:handler.NewUserHandler(userSvc)r:gin.Default()handler.Register(r)log.Println(server listens on :8080)http.ListenAndServe(:8080,r)}三、配置加载typeConfigstruct{DBstruct{DSNstringMaxint}PortstringAppEnvstring}funcLoad()(*Config,error){viper.SetConfigName(config)viper.AddConfigPath(./configs)err:viper.ReadInConfig()varc Configreturnc,err}四、Repo 层typeUserRepointerface{Find(idint)(User,error);Create(u User)(int64,error)}typeuserRepostruct{db*sql.DB}funcNewUserRepo(db*sql.DB)UserRepo{returnuserRepo{db:db}}func(r*userRepo)Find(idint)(User,error){varu User err:r.db.QueryRow(SELECT id, name FROM users WHERE id?,id).Scan(u.ID,u.Name)returnu,err}func(r*userRepo)Create(u User)(int64,error){res,err:r.db.Exec(INSERT INTO users(name) VALUES(?),u.Name)iferr!nil{return0,err}returnres.LastInsertId()}五、Service 层typeuserServicestruct{repo UserRepo}func(s*userService)CreateUser(ctx context.Context,namestring)(int64,error){ifname{return0,ErrEmptyName}returns.repo.Create(User{Name:name})}六、Handler 层func(h*UserHandler)Register(r*gin.Engine){r.GET(/users/:id,h.Get)r.POST(/users,h.Post)}func(h*UserHandler)Get(c*gin.Context){id,_:strconv.Atoi(c.Param(id))u,err:h.svc.Find(c.Request.Context(),id)iferr!nil{c.JSON(http.StatusNotFound,gin.H{err:not found});return}c.JSON(http.StatusOK,u)}func(h*UserHandler)Post(c*gin.Context){varreqstruct{Namestringjson:name}iferr:c.ShouldBindJSON(req);err!nil{c.JSON(400,gin.H{err:err.Error()});return}id,err:h.svc.CreateUser(c.Request.Context(),req.Name)iferr!nil{c.JSON(500,gin.H{err:err.Error()});return}c.JSON(200,gin.H{id:id})}七、事务与一致性func(s*userService)TransferMoney(ctx context.Context,from,toint,amountint64)error{tx,err:s.db.BeginTx(ctx,nil)iferr!nil{returnerr}defertx.Rollback()if_,err:tx.Exec(UPDATE balances SET amountamount-? WHERE user?,amount,from);err!nil{returnerr}if_,err:tx.Exec(UPDATE balances SET amountamount? WHERE user?,amount,to);err!nil{returnerr}returntx.Commit()}八、迁移 版本管理migrate create-extsql-dirmigrations-seqadd_users migrate-pathmigrations-databasemysql://user:pwdhost:3306/appup九、监控importgithub.com/prometheus/client_golang/prometheus/promhttphttp.Handle(/metrics,promhttp.Handler())业务层用中间件记录 QPS、error_rater.Use(func(c*gin.Context){deferfunc(){requestCount.WithLabelValues(c.Request.Method,c.FullPath(),strconv.Itoa(c.Writer.Status())).Inc()}()c.Next()})十、链路追踪importgo.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelginr.Use(otelgin.Middleware(user-svc))业务也加上ctx,span:tracer.Start(ctx,service.CreateUser)deferspan.End()十一、中间件限流importgolang.org/x/time/ratelimiter:rate.NewLimiter(10,20)r.Use(func(c*gin.Context){if!limiter.Allow(){c.AbortWithStatusJSON(429,gin.H{err:rate limited})return}c.Next()})十二、CI/CDtest:script:-go test ./...-racebuild:script:-go build-o app .deploy:script:-kubectl apply-f deployment.yaml十三、踩坑清单忘记读取 ctx所有 repo / service 方法必带 ctx业务事务跨多个流程 → 改 sagajson.bigint 精度丢失十四、未来Serverless 部署一体化可观测平台十五、总结与展望三层架构 Gin SQL 是 Go 后端的金标准。掌握它能为以后快速搭建业务铺路。十六、参考文献Gin 文档Go database/sql 标准库sqlmigrate
企业数字化 ERP 产品动态
相关推荐
互信息详解:从信息熵到特征选择的实战指南 1. 互信息到底是什么:从“信息重叠”说起我第一次接触互信息这个概念,是在做特征工程的时候。当时手里有一堆用户行为特征,想从中挑出对预测“用户是否流失”最有用的那几组。常规做法是先算皮尔逊相关系数,看看特征和标签之间线性… · 2026/9/25 18:45:29
Agent技能层实战:从工具调用失控到稳定执行链路 1. 从工具调用失控到技能层诞生:这个项目到底解决了什么问题如果你在做一个稍微复杂一点的Agent应用,大概率会撞上同一堵墙:模型能力没问题,工具也写好了接口,但把它们拼在一起之后,整体就是不稳。我最初的… · 2026/9/25 18:45:29
Atlas 300V 24G推理卡部署YOLO全链路与避坑指南 前两天有位朋友跑来问我:"Atlas 300V 24G 这卡是运算加速卡吗?网上说法实在太乱了。"我第一反应是——这问题还真不是一句"是"或"不是"能说清的。很多刚接触昇腾生态的人,把 Atlas 300V 当成一块可以无脑替代 … · 2026/9/25 18:45:10
Python FastApi 安装使用、中间件、依赖注入 fastApi 安装pip install fastapi -i https://pypi.tuna.tsinghua.edu.cn/simplepip install uvicorn -i https://pypi.tuna.tsinghua.edu.cn/simple命令运行项目
uvicorn myapi:app --reloadfrom fastapi import FastAPI
appFastAPI()app.get("/")
def read_root():… · 2026/9/25 20:07:13
Atlas 300V 24G部署YOLO实战:NPU推理卡的环境、转换与调优全记录 一张24GB“运算加速卡”的真相:Atlas 300V 部署YOLO的完整记录最近后台收到好几条留言,都在问同一个问题:“Atlas 300V 24G是运算加速卡吗?能不能跑YOLO?”问的人多了,我觉得有必要把这块卡从拆解、部署到调… · 2026/9/25 20:07:13
腾讯云WorkBuddy Enterprise:从超级个体到超级团队的Agent平台实战 1. 从「超级个体」到「超级团队」:这个平台到底在解决什么问题第一次看到 WorkBuddy Enterprise 这个名字,我的直觉是:腾讯云终于把 CodeBuddy 那套「一个人顶一个团队」的玩法,往组织协作方向推了一步。过去一年我一直在用 CodeB… · 2026/9/25 20:07:07
GEOFlow Chrome运营助手使用指南:设备配对与最小权限Token半自动化发布 GEOFlow Chrome运营助手使用指南:设备配对与最小权限Token半自动化发布 【免费下载链接】GEOFlow Open-source GEO content engineering and multi-site distribution platform with AI quality inspection, illustrated admin help, hosted sites, browser-assiste… · 2026/9/25 20:06:36
Kali ToolKit 781 个 Kali 工具 2053 条命令,装进一个 20MB 的 exe:我开源了 Kali ToolKit
hello大家好,我是Malcode,一个专注于网安以及开发的人。
用 Kali 的人都懂一个痛点:工具实在太多了。
Kali 官方收录了七百多个工具&#… · 2026/9/25 20:06:17
创维E900V22D刷机全攻略:S905L3SB芯片兼容性解析与救砖实战 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 1:00:31
MQTT协议原理与Broker服务器搭建实战:从Mosquitto到EMQX /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 1:00:37