Gin+Gorm實(shí)現(xiàn)增刪改查的示例代碼
1.安裝 Gin 和 Gorm
go get -u github.com/gin-gonic/gin go get -u gorm.io/gorm
新建項(xiàng)目,main 函數(shù)import 他們的包
"github.com/gin-gonic/gin" "gorm.io/driver/mysql" "gorm.io/gorm"
2.連接MySQL
var DB *gorm.DB // 全局DB,方便后續(xù)擴(kuò)展其他包調(diào)用 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 配置信息。
高級(jí)配置:參考 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 類型字段的默認(rèn)長(zhǎng)度 DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的數(shù)據(jù)庫(kù)不支持 DontSupportRenameIndex: true, // 重命名索引時(shí)采用刪除并新建的方式,MySQL 5.7 之前的數(shù)據(jù)庫(kù)和 MariaDB 不支持重命名索引 DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的數(shù)據(jù)庫(kù)和 MariaDB 不支持重命名列 SkipInitializeWithVersion: false, // 根據(jù)當(dāng)前 MySQL 版本自動(dòng)配置 }), &gorm.Config{})
3.聲明模型并綁定
type Todo struct { ID int `json:"id"` Title string `json:"title"` Status bool `json:"status"` }
如想在數(shù)據(jù)庫(kù)表中增加 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:設(shè)置主鍵 CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time }
接下來最重要的一步,一定要綁定模型:
// 模型綁定 err = DB.AutoMigrate(&Todo{}) if err != nil { return }
后續(xù)執(zhí)行綁定模型后會(huì)在你的 MySQL 數(shù)據(jù)庫(kù)中生成一張 Todo 表:
一般情況下表名會(huì)顯示復(fù)數(shù) Todos,改為單數(shù)的話要在 &gorm.Config 中指定啟用單數(shù) SingularTable 為 true:
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ SingularTable: true, }, })
4.結(jié)合 Gin 完成增刪改查
流程主要分為三步:
- 從請(qǐng)求中取出數(shù)據(jù)
- 操作數(shù)據(jù)庫(kù)
- 返回響應(yīng)
完整代碼:
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() { // 連接數(shù)據(jù)庫(kù) 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.從請(qǐng)求中取出數(shù)據(jù) var todo Todo if err = c.ShouldBindJSON(&todo); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } // 2.存入數(shù)據(jù)庫(kù) if err = DB.Create(&todo).Error; err != nil { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } else { // 3.返回響應(yīng) c.JSON(http.StatusOK, gin.H{"data": todo}) } }) // 查看所有的待辦事項(xiàng) 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}) } }) // 查看某個(gè)待辦事項(xiàng) 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}) } }) // 更新某一個(gè)待辦事項(xiàng) 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}) } }) // 刪除某個(gè)待辦事項(xiàng) 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 } }
執(zhí)行 go run main.go 項(xiàng)目啟動(dòng)在8080端口。
到此這篇關(guān)于Gin+Gorm實(shí)現(xiàn)增刪改查的示例代碼的文章就介紹到這了,更多相關(guān)Gin Gorm增刪改查內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言單元測(cè)試模擬服務(wù)請(qǐng)求和接口返回
這篇文章主要為大家介紹了Go語言單元測(cè)試模擬服務(wù)請(qǐng)求和接口返回示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06Golang實(shí)現(xiàn)smtp郵件發(fā)送的示例代碼
這篇文章主要為大家詳細(xì)介紹了Golang實(shí)現(xiàn)smtp郵件發(fā)送的相關(guān)知識(shí),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03Go?通過?Map/Filter/ForEach?等流式?API?高效處理數(shù)據(jù)的思路詳解
Stream?的實(shí)現(xiàn)思想就是將數(shù)據(jù)處理流程抽象成了一個(gè)數(shù)據(jù)流,每次加工后返回一個(gè)新的流供使用。這篇文章主要介紹了Go?通過?Map/Filter/ForEach?等流式?API?高效處理數(shù)據(jù),需要的朋友可以參考下2022-01-01