gorm 结合 gorm
1. go-zero 初始化 gorm
首先在
config.yaml
文件中定义 datasource
Name: users
Host: 0.0.0.0
Port: 8888
Mysql:
dsn: root:Sakura@tcp(127.0.0.1:3306)/go_zero?charset=utf8mb4&parseTime=True&loc=Local
在 conf 目录中加上 Mysql 配置
package config
import (
"fmt"
"github.com/zeromicro/go-zero/rest"
"go-zero/api_study/user/api_gorm/models"
"log"
)
type Config struct {
rest.RestConf
Mysql struct {
DataSource string
}
}
在依赖注入的地方创建连接
package svc
import (
"go-zero/api_study/user/api_gorm/internal/config"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
DB *gorm.DB
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
DB: config.InitMysql(c.Mysql.DataSource),
}
}
在 config.go 中初始化 Mysql 连接
package config
import (
"fmt"
"github.com/zeromicro/go-zero/rest"
"go-zero/api_study/user/api_gorm/models"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
)
type Config struct {
rest.RestConf
Mysql struct {
DataSource string
}
}
func InitMysql(MysqlDataSource string) *gorm.DB {
// 连接服务器(池)
db, err := gorm.Open(mysql.Open(MysqlDataSource), &gorm.Config{})
if err != nil {
fmt.Println("连接失败")
log.Fatalln(err)
} else {
fmt.Println("连接成功")
}
// 连接从后直接创建表
db.AutoMigrate(&models.UserModel{})
return db
}
编写逻辑测试是否成功
func (l *LoginLogic) Login(req *types.LoginRequest) (resp string, err error) {
// todo: add your logic here and delete this line
// 测试插入
err = l.svcCtx.DB.Create(&models.UserModel{
Username: "Sakura",
Password: "1111",
}).Error
if err != nil {
fmt.Println(err)
}
// 测试查询
err = l.svcCtx.DB.Take(&models.UserModel{}, "username = ? and password = ?", req.Username, req.Password).Error
if err != nil {
return "登录失败", errors.New("用户名或密码错误")
}
return "登录成功", nil
}
测试错误的密码能否登录成功
评论区