1.安装
go get -u gorm.io/gorm go get -u gorm.io/driver/mysql
|
2.配置相关
2.1 编写配置文件
[mysql] host=127.0.01 port=3306 database=test userName=root password=root charset=utf8mb4
table_pre=app_
max_idle_conn=10
max_open_conn=100
max_life_time=1h
parse_time=true
loc=Local
timeout=10s
slow_sql_time=50ms
print_sql_log=true
|
2.2 定义Mysql配置结构体
文件: app/config/mysql_config.go
package config
type MysqlConfig struct { Host string `ini:"host"` Port string `ini:"port"` Database string `ini:"database"` UserName string `ini:"userName"` Password string `ini:"password"` Charset string `ini:"charset"` MaxIdleConn int `ini:"max_idle_conn"` MaxOpenConn int `ini:"max_open_conn"` ParseTime string `ini:"parse_time"` Loc string `ini:"loc"` Timeout string `ini:"timeout"` MaxLifeTime string `ini:"max_life_time"` TablePre string `ini:"table_pre"` SlowSqlTime string `ini:"slow_sql_time"` PrintSqlLog bool `ini:"print_sql_log"` }
|
3.初始化
3.1 定义全局客户端变量
文件:app/common/global.go
var ( GormDBClient *gorm.DB )
|
3.2 映射配置到结构体
func (app *App) loadConfig() { iniPath := ConfigPath + app.Env + ".ini" fmt.Println("加载配置文件: " + iniPath) cfg, err := ini.Load(iniPath) BusErrorInstance.ThrowError(err) err = cfg.Section("mysql").MapTo(MysqlConfigInstance) }
|
3.3 连接MySQL
func connectMysql() { dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%s&loc=%s", MysqlConfigInstance.UserName, MysqlConfigInstance.Password, MysqlConfigInstance.Host, MysqlConfigInstance.Port, MysqlConfigInstance.Database, MysqlConfigInstance.Charset, MysqlConfigInstance.ParseTime, MysqlConfigInstance.Loc)
gormConfig := &gorm.Config{ NamingStrategy: schema.NamingStrategy{ TablePrefix: MysqlConfigInstance.TablePre, SingularTable: true, }, } if MysqlConfigInstance.PrintSqlLog { slowSqlTime, err := time.ParseDuration(MysqlConfigInstance.SlowSqlTime) BusErrorInstance.ThrowError(err) loggerNew := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{ SlowThreshold: slowSqlTime, LogLevel: logger.Info, Colorful: true, }) gormConfig.Logger = loggerNew } GormDBClient, err = gorm.Open(mysql.Open(dataSourceName), gormConfig) BusErrorInstance.ThrowError(err) db, err2 := GormDBClient.DB() BusErrorInstance.ThrowError(err2) db.SetMaxIdleConns(MysqlConfigInstance.MaxIdleConn) db.SetMaxOpenConns(MysqlConfigInstance.MaxOpenConn) duration, err := time.ParseDuration(MysqlConfigInstance.MaxLifeTime) BusErrorInstance.ThrowError(err) db.SetConnMaxLifetime(duration) }
|
4.创建模型
4.1 创建父模型
文件: app/common/base_model.go
package common import ( "gorm.io/gorm" ) type BaseModel struct { ID uint `gorm:"primaryKey;autoincrement;not null" json:"id"` CreatedAt int `json:"createdAt"` UpdatedAt int `json:"updatedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` }
|
4.2 创建用户模型
文件:app/models/user.go
package models
import ( "goe/app/common" )
type User struct { common.BaseModel NickName string `json:"nickName"` Password string `json:"password"` Email string `json:"email"` Mobile string `json:"mobile"` Gender int8 `json:"gender"` Birthday common.DateTime `json:"birthday"` Status int8 `json:"status"` }
func (um *User) FindById(id int) { if result := common.GormDBClient.First(um, id); result.Error != nil { common.BusErrorInstance.ThrowError(result.Error) } }
func (um *User) Add() { if result := common.GormDBClient.Create(um); result.Error != nil { common.BusErrorInstance.ThrowError(result.Error) } }
func (um *User) FindByMobile(mobile string) { if result := common.GormDBClient.Where("mobile=?", mobile).Find(um); result.Error != nil { common.BusErrorInstance.ThrowError(result.Error) } }
func (um *User) UpdateStatus(user User) { if result := common.GormDBClient.Model(um).Updates(user); result.Error != nil { common.BusErrorInstance.ThrowError(result.Error) } }
func (um *User) DelUser(id int) { if result := common.GormDBClient.Delete(um,id);result.Error != nil { common.BusErrorInstance.ThrowError(result.Error) } }
|
5.使用
创建user
控制器,调用模型中的方法,具体代码如下:
文件: app/cntrollers/v1/user.go
package v1
import ( "crypto/md5" "fmt" "goe/app/common" "goe/app/models" "strconv" "time" )
type UserController struct { common.BaseController }
func init() { common.RouteListInstance.AddRoute("v1", "user", &UserController{}) }
func (uc UserController) GetUser() error { uid := uc.GetParam("uid") phone := uc.GetParam("phone") userModel := &models.User{} if uid != "" { id, _ := strconv.Atoi(uid) userModel.FindById(id) } else if phone != "" { userModel.FindByMobile(phone) } else { return uc.Error("查询条件不能为空!") } return uc.Success(userModel) }
func (uc UserController) Register() error { nickName := uc.GetParam("nickName") email := uc.GetParam("email") mobile := uc.GetParam("mobile") birthday := uc.GetParam("birthday") notEmptyParam := []string{nickName, email, mobile, birthday} for _, v := range notEmptyParam { if v == "" { return uc.Error(fmt.Sprintf("%s不能为空!", v)) } } userExist := &models.User{} userExist.FindByMobile(mobile) if userExist.ID != 0 { return uc.Error(fmt.Sprintf("手机号%s已经存在!", mobile)) }
location, _ := time.LoadLocation("Asia/Shanghai") birthdayTime, _ := time.ParseInLocation("2006-01-02", birthday, location)
userOne := &models.User{ NickName: nickName, Email: email, Mobile: mobile, Birthday: common.DateTime(birthdayTime), Status: 1, Password: fmt.Sprintf("%x", md5.Sum([]byte(mobile))), } userOne.Add() return uc.Success(userOne) }
func (uc UserController) Update() error { uid := uc.GetParam("uid") name := uc.GetParam("name") phone := uc.GetParam("phone") userModel := &models.User{} id, _ := strconv.Atoi(uid) userModel.FindById(id) userUpdate := models.User{ NickName: name, Mobile: phone, } userModel.UpdateStatus(userUpdate) return uc.Success(userModel) }
func (uc UserController) Del() error { uid := uc.GetParam("uid") if uid == "" { return uc.Error("缺少参数!") } userModel := &models.User{} id, _ := strconv.Atoi(uid) userModel.FindById(id) if userModel.ID == 0 { return uc.Error("用户不存在!") } userModel.DelUser(id) return uc.Success(userModel) }
|
6.相关地址
源代码: https://github.com/52lu/goe
Gorm文档: https://gorm.io/zh_CN/docs/index.html