package main import ( "log" "net/http" "github.com/gin-gonic/gin" "gorm.io/driver/mysql" "gorm.io/gorm" ) // 初始化数据库, 能过与数据库交互的 连接池对象: db func setupDatabase() *gorm.DB { dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect database") } db.AutoMigrate(&Book{}) // 自动迁移 return db } // 规定好风格: JSON Restful Api func main() { // gin Engine, 它包装了http server server := gin.Default() db := setupDatabase() // 配置业务路有, Book类型的资源的 一套简单的CRUD // 创建Book -> Book // POST, Body book := server.Group("/api/books") book.POST("", func(ctx *gin.Context) { // 获取Book用户传达的参数 ins := new(Book) if err := ctx.ShouldBindJSON(ins); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"code": 0, "msg": err.Error()}) return } // book, save if err := db.Save(ins).Error; err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"code": 0, "msg": err.Error()}) return } ctx.JSON(http.StatusOK, ins) }) // 查询Book列表 -> []*Book book.GET("", func(ctx *gin.Context) { }) // 查询Book详情 book.GET("/:isbn", func(ctx *gin.Context) { }) // 更新Book book.PUT("/:isbn", func(ctx *gin.Context) { }) // 删除Book book.DELETE("/:isbn", func(ctx *gin.Context) { }) if err := server.Run("127.0.0.1:8080"); err != nil { log.Println(err) } } // Book 结构体定义 type Book struct { // grom:"column:isbn;", 具体文档: https://gorm.io/docs/models.html#Fields-Tags IsBN uint `json:"isbn" gorm:"primaryKey;column:isbn"` Title string `json:"title" gorm:"column:title;type:varchar(200)"` Author string `json:"author" gorm:"column:author;type:varchar(200);index"` Price float64 `json:"price" gorm:"column:price"` } // 定义该对象映射到数据里 表的名称 func (t *Book) TableName() string { return "books" }