本文主要是介绍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增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!