goctl api new hello
配置文件
配置文件在etc/open-api.yaml
Postgres数据源
Name: hello-api
Host: 0.0.0.0
Port: 8888
DbHost : 192.168.0.207
DbPort : 5437
DbName : postgres
DbUser : postgres
DbPasswd : "123456"
config/config.go
package config
import "github.com/zeromicro/go-zero/rest"
type Config struct {
rest.RestConf
DbHost string
DbPort int
DbName string
DbUser string
DbPasswd string
}
修改svc/servicecontext.go代码如下
package svc
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"hello/internal/config"
"hello/internal/models"
)
type ServiceContext struct {
Config config.Config
DbEngin *gorm.DB
}
func NewServiceContext(c config.Config) *ServiceContext {
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai",
c.DbHost, c.DbUser, c.DbPasswd, c.DbName, c.DbPort)
//dsn := "host=192.168.0.207 user=postgres password=Ab123456 dbname=postgres port=5437 sslmode=disable TimeZone=Asia/Shanghai"
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})
// //自动同步更新表结构,不要建表了O(∩_∩)O哈哈~
db.AutoMigrate(models.User{})
return &ServiceContext{
Config: c,
DbEngin: db,
}
}
Mysql数据源
Name: hello-api
Host: 0.0.0.0
Port: 8888
DataSourceName: root:1D007648b4f8@(127.0.0.1:3306)/gozero?charset=utf8
在etc/open-api.yaml中添加参数DataSourceName,
在internal/config/config.go中添加DataSourceName
关于配置文件,系统内置了一部分关键字 如Cache,资料不多;基本上可以随便配置,然后在Conf中定义同名变量即可。
启动Gorm支持
package svc
import (
"hello/internal/config"
"hello/internal/models"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type ServiceContext struct {
Config config.Config
DbEngin *gorm.DB
}
func NewServiceContext(c config.Config) *ServiceContext {
//启动Gorm支持
db, err := gorm.Open(mysql.Open(c.DataSourceName), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: "t_", // 表名前缀,`User` 的表名应该是 `t_users`
SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user`
},
})
//如果出错就GameOver了
if err != nil {
panic(err)
}
//自动同步更新表结构,不要建表了O(∩_∩)O哈哈~
db.AutoMigrate(&models.User{})
return &ServiceContext{Config: c, DbEngin: db}
}
如果有多张表需要同步创建:
// 禁用复数形式
db.SingularTable(true)
err := db.AutoMigrate(
system.SysApi{},
system.SysUser{},
system.SysBaseMenu{},
)
if err != nil {
os.Exit(0)
}
或者
tables := []interface{}{
models.SysApi{},
models.SysUser{},
models.SysBaseMenu{},
models.SysAuthority{},
}
for _, t := range tables {
_ = db.AutoMigrate(&t)
}
新建模型文件
新建models\models.go文件
//models\models.go文件
package models
import (
"database/sql"
"errors"
"gorm.io/gorm"
"hello/internal/utils"
"time"
)
type User struct {
ID uint
Name string
Passwd string
Email string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
// TableName PdInoutstationinfo's table name
func (*User) TableName() string {
return "ta_user"
}
// 在创建前检验验证一下密码的有效性
func (u *User) BeforeCreate(db *gorm.DB) error {
if len(u.Passwd) < 6 {
return errors.New("密码太简单了")
}
//对密码进行加密存储
u.Passwd = utils.Password(u.Passwd)
return nil
}
utils.Password是我们编写的工具包,代码如下
package utils
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
//密码加密
func Password(plainpwd string) string {
//谷歌的加密包
hash, err := bcrypt.GenerateFromPassword([]byte(plainpwd), bcrypt.DefaultCost) //加密处理
if err != nil {
fmt.Println(err)
}
encodePWD := string(hash) // 保存在数据库的密码,虽然每次生成都不同,只需保存一份即可
return encodePWD
}
//密码校验
func CheckPassword(plainpwd, cryptedpwd string) bool {
err := bcrypt.CompareHashAndPassword([]byte(cryptedpwd), []byte(plainpwd)) //验证(对比)
return err == nil
}
实现业务逻辑
在logic\hellologic.go中修改代码如下
package logic
import (
"context"
"fmt"
"hello/internal/models"
"hello/internal/svc"
"hello/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type HelloLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewHelloLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HelloLogic {
return &HelloLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *HelloLogic) Hello(req *types.Request) (resp *types.Response, err error) {
// 这里写死啦
user := models.User{
Name: "zhan san",
Email: "zhan san@126.com",
Passwd: "Ab123456",
Age: 24,
}
tx := l.svcCtx.DbEngin.Create(&user)
fmt.Println(tx.RowsAffected)
return
}
测试一下:
GET http://localhost:8888/from/me
Accept: application/json
###
网友评论