gin结合gorm实现mysql增删改查

2024-03-12 19:38

本文主要是介绍gin结合gorm实现mysql增删改查,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

https://gin-gonic.com/

https://gorm.io/zh_CN/docs/index.html

https://github.com/gin-gonic/gin/

https://github.com/go-gorm/gorm

集成

go mod方式

require (github.com/gin-contrib/sessions v0.0.3github.com/gin-gonic/gin v1.6.2github.com/go-sql-driver/mysql v1.5.0gorm.io/driver/mysql v1.0.3gorm.io/gorm v1.20.5
)

链接mysql

package coreimport ("gorm.io/driver/mysql""gorm.io/gorm"
)func Connection() (*gorm.DB) {dsn := "root:123456@tcp(127.0.0.1:3306)/goblog?charset=utf8&parseTime=True&loc=Local"db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})if err !=  nil {panic(err)}return db
}

 

使用

model

package modelstype Post struct {ID         int64 CategoryId int64 `form:"category_id"`Title      string `form:"title"`Image      string `form:"image"`Content    string `form:"content"`Sort       int `form:"sort"`Status     int `form:"status"`CreatedAt  int64UpdatedAt  int64
}

增删改查

package logicsimport ("myweb/app/models"
)func ListPost(datas []models.Post, page int) ([]models.Post, int64, error) {var pageSize = 2offset := (page - 1) * pageSizeresult := db.Order("id desc").Offset(offset).Limit(pageSize).Find(&datas)return datas, result.RowsAffected, result.Error
}func CreatePost(data models.Post) (int64, error) {result := db.Create(&data) return data.ID, result.Error
}func FindPost(id int64) (models.Post, error) {var model models.Postresult := db.First(&model, id)return model, result.Error
}func UpdatePost(data models.Post, id int64) (int64, error) {var model models.Postrow := db.First(&model, id)if row.Error == nil {result := db.Model(&model).Updates(&data)return model.ID, result.Error}return 0, row.Error
}func DeletePost(id int64) (int64, error) {var model models.Postresult := db.Delete(&model, id)return result.RowsAffected, result.Error
}

 

congroller

package controllersimport ("github.com/gin-gonic/gin""net/http""myweb/app/logics""myweb/app/models""myweb/app/utils""strconv""path"
)func ListPost(c *gin.Context) {page, _ := strconv.Atoi(c.Query("page"))if page == 0 {page = 1}var list []models.Postres, rows, err := logics.ListPost(list, page)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=文章错误&href=/home&err=" + err.Error())}c.HTML(http.StatusOK, "post_list.html", gin.H{"title": "文章列表", "list": res, "pageTotal": rows})
}func NewPost(c *gin.Context) {var list []models.Categorycategories, err := logics.ListCategory(list)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=分类错误&href=/home&err=" + err.Error())}c.HTML(http.StatusOK, "post_new.html", gin.H{"title": "新增文章", "categories": categories})
}func CreatePost(c *gin.Context) {var model models.Postfile, err := c.FormFile("file")if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=请选择文件&href=/posts/new&err=" + err.Error())}if err := c.Bind(&model); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=新增文章错误&href=/posts/new&err=" + err.Error())}if file != nil {// 获取后缀fileSuffix := path.Ext(file.Filename)// 新文件名称newFileName := utils.GetRoundName(12) + fileSuffix// 创建保存文件夹saveDir := utils.GetSaveDir("app/static/upload")SaveFile := saveDir + "/" + newFileNamec.SaveUploadedFile(file, SaveFile)model.Image = SaveFile}if _, err := logics.CreatePost(model); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=新增文章错误&href=/posts/new&err=" + err.Error())}c.Redirect(http.StatusMovedPermanently, "/posts")
}func EditPost(c *gin.Context) {id, _ := strconv.ParseInt(c.Param("id"), 10, 64)res, err := logics.FindPost(id)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=获取文章错误&href=/posts&err=" + err.Error())}var list []models.Categorycategories, err := logics.ListCategory(list)if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=分类错误&href=/home&err=" + err.Error())}c.HTML(http.StatusOK, "post_edit.html", gin.H{"title": "修改文章", "id": id, "model": res, "categories": categories})
}func UpdatePost(c *gin.Context) {id, _ := strconv.ParseInt(c.Param("id"), 10, 64)var model models.Postfile, err := c.FormFile("file")if err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=请选择文件&href=/posts/new&err=" + err.Error())}if file != nil {// 获取后缀fileSuffix := path.Ext(file.Filename)// 新文件名称newFileName := utils.GetRoundName(12) + fileSuffix// 创建保存文件夹saveDir := utils.GetSaveDir("app/static/upload")SaveFile := saveDir + "/" + newFileNamec.SaveUploadedFile(file, SaveFile)model.Image = SaveFile}if err := c.Bind(&model); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=更新文章错误&href=/posts/edit/"+ strconv.FormatInt(id,10) +"&err=" + err.Error())}if _, err := logics.UpdatePost(model, id); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=更新文章错误&href=/posts/edit/"+ strconv.FormatInt(id,10) +"&err=" + err.Error())}c.Redirect(http.StatusMovedPermanently, "/posts")return
}func DeletePost(c *gin.Context) {id, _ := strconv.ParseInt(c.Param("id"), 10, 64)if _, err := logics.DeletePost(id); err != nil {c.Redirect(http.StatusMovedPermanently, "/error?title=删除文章错误&href=/posts&err=" + err.Error())}c.Redirect(http.StatusMovedPermanently, "/posts")return
}

 

路由

package routersimport ("github.com/gin-gonic/gin""myweb/app/controllers"
)func InitRouter() *gin.Engine {router := gin.Default()router.Static("/static", "app/static")router.LoadHTMLGlob("app/templates/*")router.GET("/error",controllers.ErrorPage)router.GET("/categories",controllers.ListCategory)router.GET("/categories/new",controllers.NewCategory)router.POST("/categories/create",controllers.CreateCategory)router.GET("/categories/edit/:id",controllers.EditCategory)router.POST("/categories/update/:id",controllers.UpdateCategory)router.GET("/categories/delete/:id",controllers.DeleteCategory)router.GET("/posts",controllers.ListPost)router.GET("/posts/new",controllers.NewPost)router.POST("/posts/create",controllers.CreatePost)router.GET("/posts/edit/:id",controllers.EditPost)router.POST("/posts/update/:id",controllers.UpdatePost)router.GET("/posts/delete/:id",controllers.DeletePost)return router}

 

列表页面

{{ range .list }}<tr><td>{{ .ID }}</td><td>{{ .Title }}</td><td>{{ .Sort }}</td><td>{{ .UpdatedAt }}</td><td><a class="layui-btn layui-btn-xs" lay-event="edit" href="/posts/edit/{{ .ID }}">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" href="/posts/delete/{{ .ID }}">删除</a></td></tr>{{end}}

 

入口

package mainimport ("myweb/app/core""myweb/app/routers"
)func main() {core.Connection()router := routers.InitRouter()//静态资源router.Run(":8081")
}

 

 

项目地址: https://github.com/tang05709/gin-learn

这篇关于gin结合gorm实现mysql增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/802362

相关文章

基于C++的UDP网络通信系统设计与实现详解

《基于C++的UDP网络通信系统设计与实现详解》在网络编程领域,UDP作为一种无连接的传输层协议,以其高效、低延迟的特性在实时性要求高的应用场景中占据重要地位,下面我们就来看看如何从零开始构建一个完整... 目录前言一、UDP服务器UdpServer.hpp1.1 基本框架设计1.2 初始化函数Init详解

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

SQL Server 中的表进行行转列场景示例

《SQLServer中的表进行行转列场景示例》本文详细介绍了SQLServer行转列(Pivot)的三种常用写法,包括固定列名、条件聚合和动态列名,文章还提供了实际示例、动态列数处理、性能优化建议... 目录一、常见场景示例二、写法 1:PIVOT(固定列名)三、写法 2:条件聚合(CASE WHEN)四、

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoo WebFlux+MongoDB实现非阻塞API过程

《SpringBooWebFlux+MongoDB实现非阻塞API过程》本文介绍了如何使用SpringBootWebFlux和MongoDB实现非阻塞API,通过响应式编程提高系统的吞吐量和响应性能... 目录一、引言二、响应式编程基础2.1 响应式编程概念2.2 响应式编程的优势2.3 响应式编程相关技术

Mybatis对MySQL if 函数的不支持问题解读

《Mybatis对MySQLif函数的不支持问题解读》接手项目后,为了实现多租户功能,引入了Mybatis-plus,发现之前运行正常的SQL语句报错,原因是Mybatis不支持MySQL的if函... 目录MyBATis对mysql if 函数的不支持问题描述经过查询网上搜索资料找到原因解决方案总结Myb

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

Nginx更新SSL证书的实现步骤

《Nginx更新SSL证书的实现步骤》本文主要介绍了Nginx更新SSL证书的实现步骤,包括下载新证书、备份旧证书、配置新证书、验证配置及遇到问题时的解决方法,感兴趣的了解一下... 目录1 下载最新的SSL证书文件2 备份旧的SSL证书文件3 配置新证书4 验证配置5 遇到的http://www.cppc