go gin 封装gorm
编辑于 2022-09-01 22:30:28 阅读 1566
封装
package db
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var Db *gorm.DB
func init() {
var err error
dsn := "root:@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local&timeout=10ms"
Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Printf("mysql connect error %v", err)
}
if Db.Error != nil {
fmt.Printf("database error %v", Db.Error)
}
}
使用
model
package model
import (
orm "gin-demo/api/core/db"
)
type User struct {
Id int `json:"id"`
Username string `json:"username"`
Nickname string `json:"nickname"`
}
// 设置表名
func (User) TableName() string { //默认为结构体名称的复数,即users
return "user"
}
// 根据id查询用户User
func GetUserById(id string) (user User, err error) {
orm.Db.First(&user, "id = ?", id)
return
}
controller
package controller
import (
"gin-demo/api/core"
"gin-demo/api/model"
"github.com/gin-gonic/gin"
)
func GetUserDetail(c *gin.Context) {
id, ok := c.Params.Get("id")
if !ok {
core.Error(c, 400, "无效的id")
}
detail, err := model.GetUserById(id)
if err != nil {
core.Error(c, 404, err.Error())
} else {
core.Success(c, 0, detail)
}
}