Gin+Gorm實現(xiàn)增刪改查的示例代碼
1.安裝 Gin 和 Gorm
go get -u github.com/gin-gonic/gin go get -u gorm.io/gorm
新建項目,main 函數(shù)import 他們的包
"github.com/gin-gonic/gin" "gorm.io/driver/mysql" "gorm.io/gorm"
2.連接MySQL
var DB *gorm.DB // 全局DB,方便后續(xù)擴展其他包調用 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 之前的數(shù)據(jù)庫不支持 DontSupportRenameIndex: true, // 重命名索引時采用刪除并新建的方式,MySQL 5.7 之前的數(shù)據(jù)庫和 MariaDB 不支持重命名索引 DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的數(shù)據(jù)庫和 MariaDB 不支持重命名列 SkipInitializeWithVersion: false, // 根據(jù)當前 MySQL 版本自動配置 }), &gorm.Config{})
3.聲明模型并綁定
type Todo struct { ID int `json:"id"` Title string `json:"title"` Status bool `json:"status"` }
如想在數(shù)據(jù)庫表中增加 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 }
后續(xù)執(zhí)行綁定模型后會在你的 MySQL 數(shù)據(jù)庫中生成一張 Todo 表:
一般情況下表名會顯示復數(shù) Todos,改為單數(shù)的話要在 &gorm.Config 中指定啟用單數(shù) SingularTable 為 true:
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ SingularTable: true, }, })
4.結合 Gin 完成增刪改查
流程主要分為三步:
- 從請求中取出數(shù)據(jù)
- 操作數(shù)據(jù)庫
- 返回響應
完整代碼:
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ù)庫 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.從請求中取出數(shù)據(jù) var todo Todo if err = c.ShouldBindJSON(&todo); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } // 2.存入數(shù)據(jù)庫 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 } }
執(zhí)行 go run main.go 項目啟動在8080端口。
到此這篇關于Gin+Gorm實現(xiàn)增刪改查的示例代碼的文章就介紹到這了,更多相關Gin Gorm增刪改查內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Golang實現(xiàn)smtp郵件發(fā)送的示例代碼
這篇文章主要為大家詳細介紹了Golang實現(xiàn)smtp郵件發(fā)送的相關知識,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-03-03Go?通過?Map/Filter/ForEach?等流式?API?高效處理數(shù)據(jù)的思路詳解
Stream?的實現(xiàn)思想就是將數(shù)據(jù)處理流程抽象成了一個數(shù)據(jù)流,每次加工后返回一個新的流供使用。這篇文章主要介紹了Go?通過?Map/Filter/ForEach?等流式?API?高效處理數(shù)據(jù),需要的朋友可以參考下2022-01-01