快速开始api开发(二)model 代码生成 与 依赖注入
model 代码生成 与 依赖注入#
本文需要介绍 gotools 工具#
需要使用的工具命令:
gotools grom -h
代码地址:github.com/wuyan94zl/gotools
创建文件:models/user.sql#
CREATE TABLE `users`
(
`id` int(11) NOT NULL,
`nickname` varchar(255) NOT NULL COMMENT '用户昵称',
`login_id` varchar(255) NOT NULL COMMENT '登录ID',
`password` varchar(255) NOT NULL COMMENT '登录密码',
`head_img` varchar(255) NOT NULL COMMENT '用户头像',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
生成 model 代码#
进入 models 文件夹:cd models
执行:gotools gorm --src user.sql --dir user --cache false
生成目录结构(代码基于 gorm + mysql + redis) –cache 为 true 时使用 redis 做缓存代理
models
|-- user
|-- model.go
|-- model_gen.go
|-- user.sql
model 依赖注入,修改 container.go#
修改: container/container.go
package container
import (
"github.com/go-redis/redis/v9"
"gorm.io/gorm"
"github.com/wuyan94zl/example-api/models/user" // 增加代码
)
type Config struct {
DB GormConfig
Redis RedisConfig
}
type Container struct {
DB *gorm.DB
Redis *redis.Client
UserModel user.UsersModel // 增加代码
}
func NewContainer(c Config) {
dbConn, redisConn := dbConn(c.DB), redisConn(c.Redis)
container = &Container{
DB: dbConn,
Redis: redisConn,
UserModel: user.NewUsersModel(dbConn), // 增加代码
}
}
下一篇,接口注册实现
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: