Gin + Gorm 实现增删改查

1.安装 Gin 和 Gorm

go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm

新建项目,main 函数import 他们的包

"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"

2.连接MySQL

var DB *gorm.DB // 全局DB,方便后续扩展其他包调用

func initMySQL() (err error) {
    dsn := "root:root@tcp(127.0.0.1:13306)/bubble?charset=utf8mb4&parseTime=True&loc=Local"
    DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            SingularTable: true,
        },
    })
    if err != nil {
        return
    }
    return nil
}

dsn 处换成自己的 MySQL 配置信息。
高级配置:参考 https://gorm.io/zh_CN/docs/connecting_to_the_database.html

db, err := gorm.Open(mysql.New(mysql.Config{
   DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name
   DefaultStringSize: 256, // string 类型字段的默认长度
   DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
   DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
   DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
   SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
}), &gorm.Config{})

3.声明模型并绑定

type Todo struct {
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Status bool   `json:"status"`
}

如想在数据库表中增加 CreatedAt , UpdatedAt 和 DeletedAt 字段,可在 Todo 模型中引入 gorm.Model 字段:

type Todo struct {
    gorm.Model
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Status bool   `json:"status"`
}

gorm.Model 定义如下:

type Model struct {
  ID        uint `gorm:"primary_key"`//primary_key:设置主键
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}

接下来最重要的一步,一定要绑定模型:

// 模型绑定
err = DB.AutoMigrate(&Todo{})
if err != nil {
    return
}

后续执行绑定模型后会在你的 MySQL 数据库中生成一张 Todo 表:
todo_table.jpg
一般情况下表名会显示复数 Todos,改为单数的话要在 &gorm.Config 中指定启用单数 SingularTable 为 true:

 DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            SingularTable: true,
        },
    })

4.结合 Gin 完成增删改查

流程主要分为三步:

  1. 从请求中取出数据
  2. 操作数据库
  3. 返回响应

完整代码:

package main

import (
    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/schema"
    "net/http"
)

var DB *gorm.DB

func initMySQL() (err error) {
    dsn := "root:root@tcp(127.0.0.1:13306)/bubble?charset=utf8mb4&parseTime=True&loc=Local"
    DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            SingularTable: true,
        },
    })
    if err != nil {
        return
    }
    return nil
}

type Todo struct {
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Status bool   `json:"status"`
}

func main() {
    // 连接数据库
    err := initMySQL()
    if err != nil {
        panic(err)
    }
    // 模型绑定
    err = DB.AutoMigrate(&Todo{})
    if err != nil {
        return
    }

    r := gin.Default()

    v1Group := r.Group("/v1")
    {
        // 添加
        v1Group.POST("/todo", func(c *gin.Context) {
            // 1.从请求中取出数据
            var todo Todo
            if err = c.ShouldBindJSON(&todo); err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            }
            // 2.存入数据库
            if err = DB.Create(&todo).Error; err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            } else {
                // 3.返回响应
                c.JSON(http.StatusOK, gin.H{"data": todo})
            }

        })
        // 查看所有的待办事项
        v1Group.GET("/todo", func(c *gin.Context) {
            var todoList []Todo
            if err = DB.Find(&todoList).Error; err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            } else {
                c.JSON(http.StatusOK, gin.H{"data": todoList})
            }
        })
        // 查看某个待办事项
        v1Group.GET("/todo/:id", func(c *gin.Context) {
            var todo Todo
            if err = DB.First(&todo, c.Param("id")).Error; err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            } else {
                c.JSON(http.StatusOK, gin.H{"data": todo})
            }
        })
        // 更新某一个待办事项
        v1Group.PUT("/todo/:id", func(c *gin.Context) {
            id, ok := c.Params.Get("id")
            if !ok {
                c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
            }
            var todo Todo
            if err = DB.Where("id = ?", id).First(&todo).Error; err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            }
            c.ShouldBindJSON(&todo)
            if err = DB.Save(&todo).Error; err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            } else {
                c.JSON(http.StatusOK, gin.H{"data": todo})
            }
        })
        // 删除某个待办事项
        v1Group.DELETE("/todo/:id", func(c *gin.Context) {
            var todo Todo
            id, ok := c.Params.Get("id")
            if !ok {
                c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
            }
            if err = DB.Where("id = ?", id).Delete(&Todo{}).Error; err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            } else {
                c.JSON(http.StatusOK, gin.H{"data": todo})
            }

        })
    }

    err = r.Run(":8080")
    if err != nil {
        return
    }
}

执行 go run main.go 项目启动在8080端口。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值