项目实战

在项目中新建一个demo模块,模块中添加员工管理功能,此处为了演示关联查询,做了2个表,demo_gen_class是分类表,demo_gen是员工表。

注意:实战案例基于授权版,如果您使用的是开源版本,其中部分功能可能没有。

创建对应数据表

1、创建员工分类表:

CREATE TABLE `demo_gen_class` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '分类id',
  `class_name` varchar(30) NOT NULL DEFAULT '' COMMENT '分类名',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='员工分类表';

2、创建员工表

CREATE TABLE `demo_gen` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `demo_name` varchar(20) NOT NULL DEFAULT '' COMMENT '姓名',
  `demo_age` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '年龄',
  `classes` varchar(30) NOT NULL DEFAULT '' COMMENT '班级',
  `demo_born` datetime DEFAULT NULL COMMENT '出生年月',
  `demo_gender` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '性别',
  `created_at` datetime DEFAULT NULL COMMENT '创建日期',
  `updated_at` datetime DEFAULT NULL COMMENT '修改日期',
  `deleted_at` datetime DEFAULT NULL COMMENT '删除日期',
  `created_by` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '创建人',
  `updated_by` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '修改人',
  `demo_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态',
  `demo_cate` varchar(30) NOT NULL DEFAULT '' COMMENT '分类',
  `demo_thumb` text COMMENT '头像',
  `demo_photo` text COMMENT '相册',
  `demo_info` text COMMENT '个人描述',
  `demo_file` text COMMENT '相关附件',
  `classes_two` varchar(30) NOT NULL DEFAULT '' COMMENT '班级二',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='员工表';

3、使用gf-cli 生成对应dao及model

注意:请使用最新的gf-cli工具
在项目根目录下hack/config.yaml下编辑生成dao相关配置。

# CLI.
gfcli:
  gen:
    dao:
      - link:            "mysql:gfast3:gfast333@tcp(127.0.0.1:3306)/gfast-v32"
        tables:          "demo_gen,demo_gen_class"
        removePrefix:    "gf_"
        descriptionTag:  true
        noModelComment:  true
        path: "./internal/app/demo"

tables可以指定需要将哪些表生成dao
path指定生成的路径
在项目internal/app下新建demo目录(模块):

生成dao:

gf gen dao

则会在demo模块下生成daomodel

internal/app/demo/model目录下创建相关model文件:
demo_gen_class.go:


package model


import (
"github.com/gogf/gf/v2/util/gmeta"
)


// DemoGenClassInfoRes is the golang structure for table demo_gen_class.
type DemoGenClassInfoRes struct {
    gmeta.Meta   `orm:"table:demo_gen_class"`
    Id       uint         `orm:"id,primary" json:"id"`    // 分类id
    ClassName    string         `orm:"class_name" json:"className"`    // 分类名
}




type DemoGenClassListRes struct{
    Id  uint   `json:"id"`
    ClassName  string   `json:"className"`
}

demo_gen.go:


package model


import (
    "github.com/gogf/gf/v2/os/gtime"
    "github.com/gogf/gf/v2/util/gmeta"
)


// DemoGenInfoRes is the golang structure for table demo_gen.
type DemoGenInfoRes struct {
    gmeta.Meta   `orm:"table:demo_gen"`
    Id       uint         `orm:"id,primary" json:"id"`    // ID
    DemoName    string         `orm:"demo_name" json:"demoName"`    // 姓名
    DemoAge    uint         `orm:"demo_age" json:"demoAge"`    // 年龄
    Classes    string         `orm:"classes" json:"classes"`    // 班级
    LinkedClasses  *LinkedDemoGenDemoGenClass  `orm:"with:id=classes" json:"linkedClasses"`
    ClassesTwo    string         `orm:"classes_two" json:"classesTwo"`    // 班级2
    LinkedClassesTwo  *LinkedDemoGenDemoGenClass  `orm:"with:id=classes_two" json:"linkedClassesTwo"`
    DemoBorn    *gtime.Time         `orm:"demo_born" json:"demoBorn"`    // 出生年月
    DemoGender    uint         `orm:"demo_gender" json:"demoGender"`    // 性别
    CreatedAt    *gtime.Time         `orm:"created_at" json:"createdAt"`    // 创建日期
    UpdatedAt    *gtime.Time         `orm:"updated_at" json:"updatedAt"`    // 修改日期
    DeletedAt    *gtime.Time         `orm:"deleted_at" json:"deletedAt"`    // 删除日期
    CreatedBy    uint64         `orm:"created_by" json:"createdBy"`    // 创建人
    UpdatedBy    uint64         `orm:"updated_by" json:"updatedBy"`    // 修改人
    DemoStatus    int         `orm:"demo_status" json:"demoStatus"`    // 状态
    DemoCate    string         `orm:"demo_cate" json:"demoCate"`    // 分类
    DemoThumb    string         `orm:"demo_thumb" json:"demoThumb"`    // 头像
    DemoPhoto    string         `orm:"demo_photo" json:"demoPhoto"`    // 相册
    DemoInfo    string         `orm:"demo_info" json:"demoInfo"`    // 个人描述
    DemoFile    string         `orm:"demo_file" json:"demoFile"`    // 相关附件
}


type LinkedDemoGenDemoGenClass struct {
    gmeta.Meta   `orm:"table:demo_gen_class"`
    Id    uint         `orm:"id" json:"id"`    // 分类id
    ClassName    string         `orm:"class_name" json:"className"`    // 分类名
}


type DemoGenListRes struct{
    Id  uint   `json:"id"`
    DemoName  string   `json:"demoName"`
    DemoAge  uint   `json:"demoAge"`
    Classes  string   `json:"classes"`
    LinkedClasses  *LinkedDemoGenDemoGenClass  `orm:"with:id=classes" json:"linkedClasses"`
    ClassesTwo  string   `json:"classesTwo"`
    LinkedClassesTwo  *LinkedDemoGenDemoGenClass  `orm:"with:id=classes_two" json:"linkedClassesTwo"`
    DemoBorn  *gtime.Time   `json:"demoBorn"`
    DemoGender  uint   `json:"demoGender"`
    CreatedAt  *gtime.Time   `json:"createdAt"`
    CreatedBy  uint64   `json:"createdBy"`
    DemoStatus  int   `json:"demoStatus"`
    DemoCate  string   `json:"demoCate"`
    DemoThumb  string   `json:"demoThumb"`
}

model结构如下:

4、创建路由和对应api接口

api/v1下创建demo目录

demo目录中创建对应的增删改查规范路由:
demo_gen_class.go:


package demo


import (
"github.com/gogf/gf/v2/frame/g"
commonApi "github.com/tiger1103/gfast/v3/api/v1/common"
"github.com/tiger1103/gfast/v3/internal/app/demo/model"
)
// DemoGenClassSearchReq 分页请求参数
type DemoGenClassSearchReq struct {
    g.Meta   `path:"/list" tags:"分类信息" method:"get" summary:"分类信息列表"`
    ClassName  string `p:"className"` //分类名
    commonApi.PageReq
    commonApi.Author
}
// DemoGenClassSearchRes 列表返回结果
type DemoGenClassSearchRes struct {
    g.Meta `mime:"application/json"`
    commonApi.ListRes
    List []*model.DemoGenClassListRes `json:"list"`
}
// DemoGenClassAddReq 添加操作请求参数
type DemoGenClassAddReq struct {
    g.Meta   `path:"/add" tags:"分类信息" method:"post" summary:"分类信息添加"`
    commonApi.Author
    ClassName  string   `p:"className" v:"required#分类名不能为空"`
}
// DemoGenClassAddRes 添加操作返回结果
type DemoGenClassAddRes  struct {
    commonApi.EmptyRes
}
// DemoGenClassEditReq 修改操作请求参数
type DemoGenClassEditReq struct {
    g.Meta   `path:"/edit" tags:"分类信息" method:"put" summary:"分类信息修改"`
    commonApi.Author
    Id    uint  `p:"id" v:"required#主键ID不能为空"`
    ClassName  string `p:"className" v:"required#分类名不能为空"`
}
// DemoGenClassEditRes 修改操作返回结果
type DemoGenClassEditRes  struct {
    commonApi.EmptyRes
}
// DemoGenClassGetReq 获取一条数据请求
type DemoGenClassGetReq struct {
    g.Meta `path:"/get" tags:"分类信息" method:"get" summary:"获取分类信息信息"`
    commonApi.Author
    Id    uint `p:"id" v:"required#主键必须"` //通过主键获取
}
// DemoGenClassGetRes 获取一条数据结果
type DemoGenClassGetRes struct {
    g.Meta `mime:"application/json"`
    *model.DemoGenClassInfoRes
}
// DemoGenClassDeleteReq 删除数据请求
type DemoGenClassDeleteReq struct {
    g.Meta `path:"/delete" tags:"分类信息" method:"delete" summary:"删除分类信息"`
    commonApi.Author
    Ids    []uint `p:"ids" v:"required#主键必须"` //通过主键删除
}
// DemoGenClassDeleteRes 删除数据返回
type DemoGenClassDeleteRes struct {
    commonApi.EmptyRes
}

demo_gen.go:


package demo


import (
    "github.com/gogf/gf/v2/container/garray"
    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/os/gtime"
    commonApi "github.com/tiger1103/gfast/v3/api/v1/common"
    comModel "github.com/tiger1103/gfast/v3/internal/app/common/model"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
)
// DemoGenSearchReq 分页请求参数
type DemoGenSearchReq struct {
    g.Meta   `path:"/list" tags:"代码生成测试" method:"get" summary:"代码生成测试列表"`
    DemoName  string `p:"demoName"` //姓名
    DemoAge  string `p:"demoAge" v:"demoAge@integer#年龄需为整数"` //年龄
    Classes  string `p:"classes"` //班级
    ClassesTwo  string `p:"classesTwo"` //班级2
    DemoBorn  string `p:"demoBorn" v:"demoBorn@datetime#出生年月需为YYYY-MM-DD hh:mm:ss格式"` //出生年月
    DemoGender  string `p:"demoGender" v:"demoGender@integer#性别需为整数"` //性别
    DemoStatus  string `p:"demoStatus" v:"demoStatus@integer#状态需为整数"` //状态
    DemoCate  string `p:"demoCate"` //分类
    commonApi.PageReq
    commonApi.Author
}
// DemoGenSearchRes 列表返回结果
type DemoGenSearchRes struct {
    g.Meta `mime:"application/json"`
    commonApi.ListRes
    List []*model.DemoGenListRes `json:"list"`
}
// DemoGenAddReq 添加操作请求参数
type DemoGenAddReq struct {
    g.Meta   `path:"/add" tags:"代码生成测试" method:"post" summary:"代码生成测试添加"`
    commonApi.Author
    DemoName  string   `p:"demoName" v:"required#姓名不能为空"`
    DemoAge  uint   `p:"demoAge" `
    Classes  string   `p:"classes" `
    ClassesTwo  string   `p:"classesTwo" `
    DemoBorn  *gtime.Time   `p:"demoBorn" `
    DemoGender  uint   `p:"demoGender" `
    DemoStatus  int   `p:"demoStatus" v:"required#状态不能为空"`
    DemoCate  garray.StrArray   `p:"demoCate" `
    DemoThumb  string   `p:"demoThumb" `
    DemoPhoto  []*comModel.UpFile   `p:"demoPhoto" `
    DemoInfo  string   `p:"demoInfo" `
    DemoFile  []*comModel.UpFile   `p:"demoFile" `
    CreatedBy       uint64
}
// DemoGenAddRes 添加操作返回结果
type DemoGenAddRes  struct {
    commonApi.EmptyRes
}
// DemoGenEditReq 修改操作请求参数
type DemoGenEditReq struct {
    g.Meta   `path:"/edit" tags:"代码生成测试" method:"put" summary:"代码生成测试修改"`
    commonApi.Author
    Id    uint  `p:"id" v:"required#主键ID不能为空"`
    DemoName  string `p:"demoName" v:"required#姓名不能为空"`
    DemoAge  uint `p:"demoAge" `
    Classes  string `p:"classes" `
    ClassesTwo  string `p:"classesTwo" `
    DemoBorn  *gtime.Time `p:"demoBorn" `
    DemoGender  uint `p:"demoGender" `
    DemoStatus  int `p:"demoStatus" v:"required#状态不能为空"`
    DemoCate  garray.StrArray `p:"demoCate" `
    DemoThumb  string `p:"demoThumb" `
    DemoPhoto  []*comModel.UpFile `p:"demoPhoto" `
    DemoInfo  string `p:"demoInfo" `
    DemoFile  []*comModel.UpFile `p:"demoFile" `
    UpdatedBy       uint64
}
// DemoGenEditRes 修改操作返回结果
type DemoGenEditRes  struct {
    commonApi.EmptyRes
}
// DemoGenGetReq 获取一条数据请求
type DemoGenGetReq struct {
    g.Meta `path:"/get" tags:"代码生成测试" method:"get" summary:"获取代码生成测试信息"`
    commonApi.Author
    Id    uint `p:"id" v:"required#主键必须"` //通过主键获取
}
// DemoGenGetRes 获取一条数据结果
type DemoGenGetRes struct {
    g.Meta `mime:"application/json"`
    *model.DemoGenInfoRes
}
// DemoGenDeleteReq 删除数据请求
type DemoGenDeleteReq struct {
    g.Meta `path:"/delete" tags:"代码生成测试" method:"delete" summary:"删除代码生成测试"`
    commonApi.Author
    Ids    []uint `p:"ids" v:"required#主键必须"` //通过主键删除
}
// DemoGenDeleteRes 删除数据返回
type DemoGenDeleteRes struct {
    commonApi.EmptyRes
}

api中的结构如下:

5、创建logic与service

gen_class.go:

package demoGenClass

import (
    "context"
    "github.com/gogf/gf/v2/frame/g"
    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/dao"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model/do"
    "github.com/tiger1103/gfast/v3/internal/app/system/consts"
    "github.com/tiger1103/gfast/v3/library/liberr"
)


func New() *sDemoGenClass {
    return &sDemoGenClass{}
}


type sDemoGenClass struct{}


func (s *sDemoGenClass)List(ctx context.Context, req *demo.DemoGenClassSearchReq) (listRes *demo.DemoGenClassSearchRes, err error){
    listRes = new(demo.DemoGenClassSearchRes)
    err = g.Try(ctx, func(ctx context.Context) {
        m := dao.DemoGenClass.Ctx(ctx).WithAll()
        if req.ClassName != "" {
            m = m.Where(dao.DemoGenClass.Columns().ClassName+" like ?", "%"+req.ClassName+"%")
        }
        listRes.Total, err = m.Count()
        liberr.ErrIsNil(ctx, err, "获取总行数失败")
        if req.PageNum == 0 {
            req.PageNum = 1
        }
        listRes.CurrentPage = req.PageNum
        if req.PageSize == 0 {
            req.PageSize = consts.PageSize
        }
        order:= "id asc"
        if req.OrderBy!=""{
            order = req.OrderBy
        }
        var res []*model.DemoGenClassInfoRes
        err = m.Fields(demo.DemoGenClassSearchRes{}).Page(req.PageNum, req.PageSize).Order(order).Scan(&res)
        liberr.ErrIsNil(ctx, err, "获取数据失败")
        listRes.List = make([]*model.DemoGenClassListRes,len(res))
        for k,v:=range res{
            listRes.List[k] = &model.DemoGenClassListRes{
                Id : v.Id,
                ClassName : v.ClassName,
            }
        }
    })
    return
}


func (s *sDemoGenClass)GetById(ctx context.Context, id uint) (res *model.DemoGenClassInfoRes,err error){
    err =g.Try(ctx, func(ctx context.Context){
        err = dao.DemoGenClass.Ctx(ctx).WithAll().Where(dao.DemoGenClass.Columns().Id,  id).Scan(&res)
        liberr.ErrIsNil(ctx,err,"获取信息失败")
    })
    return
}


func (s *sDemoGenClass)Add(ctx context.Context, req *demo.DemoGenClassAddReq) (err error){
    err = g.Try(ctx, func(ctx context.Context) {
        _, err = dao.DemoGenClass.Ctx(ctx).Insert(do.DemoGenClass{
            ClassName:req.ClassName,
        })
        liberr.ErrIsNil(ctx, err, "添加失败")
    })
    return
}


func (s *sDemoGenClass)Edit(ctx context.Context, req *demo.DemoGenClassEditReq) (err error){
    err = g.Try(ctx, func(ctx context.Context) {
        _, err = dao.DemoGenClass.Ctx(ctx).WherePri(req.Id).Update(do.DemoGenClass{
            ClassName:req.ClassName,
        })
        liberr.ErrIsNil(ctx, err, "修改失败")
    })
    return
}


func (s *sDemoGenClass)Delete(ctx context.Context, ids []uint) (err error){
    err = g.Try(ctx,func(ctx context.Context){
        _, err = dao.DemoGenClass.Ctx(ctx).Delete(dao.DemoGenClass.Columns().Id+" in (?)", ids)
        liberr.ErrIsNil(ctx,err,"删除失败")
    })
    return
}

gen.go:

package demoGen


import (
    "context"
    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/util/gconv"
    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/dao"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model/do"
    "github.com/tiger1103/gfast/v3/internal/app/system/consts"
    systemService "github.com/tiger1103/gfast/v3/internal/app/system/service"
    "github.com/tiger1103/gfast/v3/library/libUtils"
    "github.com/tiger1103/gfast/v3/library/liberr"
)


func New() *sDemoGen {
    return &sDemoGen{}
}


type sDemoGen struct{}


func (s *sDemoGen)List(ctx context.Context, req *demo.DemoGenSearchReq) (listRes *demo.DemoGenSearchRes, err error){
    listRes = new(demo.DemoGenSearchRes)
    err = g.Try(ctx, func(ctx context.Context) {
        m := dao.DemoGen.Ctx(ctx).WithAll()
        if req.DemoName != "" {
            m = m.Where(dao.DemoGen.Columns().DemoName+" like ?", "%"+req.DemoName+"%")
        }
        if req.DemoAge != "" {
            m = m.Where(dao.DemoGen.Columns().DemoAge+" = ?", gconv.Uint(req.DemoAge))
        }
        if req.Classes != "" {
            m = m.Where(dao.DemoGen.Columns().Classes+" = ?", req.Classes)
        }
        if req.ClassesTwo != "" {
            m = m.Where(dao.DemoGen.Columns().ClassesTwo+" = ?", req.ClassesTwo)
        }
        if req.DemoBorn != "" {
            m = m.Where(dao.DemoGen.Columns().DemoBorn+" = ?", gconv.Time(req.DemoBorn))
        }
        if req.DemoGender != "" {
            m = m.Where(dao.DemoGen.Columns().DemoGender+" = ?", gconv.Uint(req.DemoGender))
        }
        if req.DemoStatus != "" {
            m = m.Where(dao.DemoGen.Columns().DemoStatus+" = ?", gconv.Int(req.DemoStatus))
        }
        if req.DemoCate != "" {
            m = m.Where(dao.DemoGen.Columns().DemoCate+" = ?", req.DemoCate)
        }
        listRes.Total, err = m.Count()
        liberr.ErrIsNil(ctx, err, "获取总行数失败")
        if req.PageNum == 0 {
            req.PageNum = 1
        }
        listRes.CurrentPage = req.PageNum
        if req.PageSize == 0 {
            req.PageSize = consts.PageSize
        }
        order:= "id asc"
        if req.OrderBy!=""{
            order = req.OrderBy
        }
        var res []*model.DemoGenInfoRes
        err = m.Fields(demo.DemoGenSearchRes{}).Page(req.PageNum, req.PageSize).Order(order).Scan(&res)
        liberr.ErrIsNil(ctx, err, "获取数据失败")
        listRes.List = make([]*model.DemoGenListRes,len(res))
        for k,v:=range res{
            listRes.List[k] = &model.DemoGenListRes{
                Id : v.Id,
                DemoName : v.DemoName,
                DemoAge : v.DemoAge,
                Classes : v.Classes,
                LinkedClasses:v.LinkedClasses,
                ClassesTwo : v.ClassesTwo,
                LinkedClassesTwo:v.LinkedClassesTwo,
                DemoBorn : v.DemoBorn,
                DemoGender : v.DemoGender,
                CreatedAt : v.CreatedAt,
                CreatedBy : v.CreatedBy,
                DemoStatus : v.DemoStatus,
                DemoCate : v.DemoCate,
                DemoThumb : v.DemoThumb,
            }
        }
    })
    return
}


func (s *sDemoGen)GetById(ctx context.Context, id uint) (res *model.DemoGenInfoRes,err error){
    err =g.Try(ctx, func(ctx context.Context){
        err = dao.DemoGen.Ctx(ctx).WithAll().Where(dao.DemoGen.Columns().Id,  id).Scan(&res)
        liberr.ErrIsNil(ctx,err,"获取信息失败")
    })
    return
}


func (s *sDemoGen)Add(ctx context.Context, req *demo.DemoGenAddReq) (err error){
    err = g.Try(ctx, func(ctx context.Context) {
        demoCate := ""
        req.DemoCate.FilterEmpty()
        if !req.DemoCate.IsEmpty(){
            demoCate=req.DemoCate.Join(",")
        }
        for _,obj:=range req.DemoPhoto{
            obj.Url,err = libUtils.GetFilesPath(ctx,obj.Url)
            liberr.ErrIsNil(ctx, err)
        }
        for _,obj:=range req.DemoFile{
            obj.Url,err = libUtils.GetFilesPath(ctx,obj.Url)
            liberr.ErrIsNil(ctx, err)
        }
        _, err = dao.DemoGen.Ctx(ctx).Insert(do.DemoGen{
            DemoName:req.DemoName,
            DemoAge:req.DemoAge,
            Classes:req.Classes,
            ClassesTwo:req.ClassesTwo,
            DemoBorn:req.DemoBorn,
            DemoGender:req.DemoGender,
            DemoStatus:req.DemoStatus,
            DemoCate:demoCate,
            DemoThumb:req.DemoThumb,
            DemoPhoto:req.DemoPhoto,
            DemoInfo:req.DemoInfo,
            DemoFile:req.DemoFile,
            CreatedBy:systemService.Context().GetUserId(ctx),
        })
        liberr.ErrIsNil(ctx, err, "添加失败")
    })
    return
}


func (s *sDemoGen)Edit(ctx context.Context, req *demo.DemoGenEditReq) (err error){
    err = g.Try(ctx, func(ctx context.Context) {
        demoCate := ""
        req.DemoCate.FilterEmpty()
        if !req.DemoCate.IsEmpty(){
            demoCate=req.DemoCate.Join(",")
        }
        for _,obj:=range req.DemoPhoto{
            obj.Url,err = libUtils.GetFilesPath(ctx,obj.Url)
            liberr.ErrIsNil(ctx, err)
        }
        for _,obj:=range req.DemoFile{
            obj.Url,err = libUtils.GetFilesPath(ctx,obj.Url)
            liberr.ErrIsNil(ctx, err)
        }
        _, err = dao.DemoGen.Ctx(ctx).WherePri(req.Id).Update(do.DemoGen{
            DemoName:req.DemoName,
            DemoAge:req.DemoAge,
            Classes:req.Classes,
            ClassesTwo:req.ClassesTwo,
            DemoBorn:req.DemoBorn,
            DemoGender:req.DemoGender,
            DemoStatus:req.DemoStatus,
            DemoCate:demoCate,
            DemoThumb:req.DemoThumb,
            DemoPhoto:req.DemoPhoto,
            DemoInfo:req.DemoInfo,
            DemoFile:req.DemoFile,
            UpdatedBy:systemService.Context().GetUserId(ctx),
        })
        liberr.ErrIsNil(ctx, err, "修改失败")
    })
    return
}


func (s *sDemoGen)Delete(ctx context.Context, ids []uint) (err error){
    err = g.Try(ctx,func(ctx context.Context){
        _, err = dao.DemoGen.Ctx(ctx).Delete(dao.DemoGen.Columns().Id+" in (?)", ids)
        liberr.ErrIsNil(ctx,err,"删除失败")
    })
    return
}

logic文件创建以后,可通过 gf gen service 生成对应的接口
终端输入命令:

gf gen service -s internal/app/demo/logic -d internal/app/demo/service

-s指定logic文件所在目录
-d 指定生成service 文件目录
运行以上命令后可一看到对应的service已经生成


package service

import (
    "context"

    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
)

type (
    IDemoGenClass interface {
        List(ctx context.Context, req *demo.DemoGenClassSearchReq) (listRes *demo.DemoGenClassSearchRes, err error)
        GetById(ctx context.Context, id uint) (res *model.DemoGenClassInfoRes, err error)
        Add(ctx context.Context, req *demo.DemoGenClassAddReq) (err error)
        Edit(ctx context.Context, req *demo.DemoGenClassEditReq) (err error)
        Delete(ctx context.Context, ids []uint) (err error)
    }
)

var (
    localDemoGenClass IDemoGenClass
)

func DemoGenClass() IDemoGenClass {
    if localDemoGenClass == nil {
        panic("implement not found for interface IDemoGenClass, forgot register?")
    }
    return localDemoGenClass
}

func RegisterDemoGenClass(i IDemoGenClass) {
    localDemoGenClass = i
}

package service

import (
    "context"

    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
)

type (
    IDemoGen interface {
        List(ctx context.Context, req *demo.DemoGenSearchReq) (listRes *demo.DemoGenSearchRes, err error)
        GetById(ctx context.Context, id uint) (res *model.DemoGenInfoRes, err error)
        Add(ctx context.Context, req *demo.DemoGenAddReq) (err error)
        Edit(ctx context.Context, req *demo.DemoGenEditReq) (err error)
        Delete(ctx context.Context, ids []uint) (err error)
    }
)

var (
    localDemoGen IDemoGen
)

func DemoGen() IDemoGen {
    if localDemoGen == nil {
        panic("implement not found for interface IDemoGen, forgot register?")
    }
    return localDemoGen
}

func RegisterDemoGen(i IDemoGen) {
    localDemoGen = i
}

修改logic注册对应的实例,在文件开头,添加对应的init方法即可:


package demoGenClass

import (
    "context"
    "github.com/gogf/gf/v2/frame/g"
    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/dao"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model/do"
    "github.com/tiger1103/gfast/v3/internal/app/demo/service"
    "github.com/tiger1103/gfast/v3/internal/app/system/consts"
    "github.com/tiger1103/gfast/v3/library/liberr"
)


func init() {
    service.RegisterDemoGenClass(New())
}


func New() *sDemoGenClass {
    return &sDemoGenClass{}
}

....

package demoGen

import (
    "context"
    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/util/gconv"
    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/dao"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model"
    "github.com/tiger1103/gfast/v3/internal/app/demo/model/do"
    "github.com/tiger1103/gfast/v3/internal/app/demo/service"
    "github.com/tiger1103/gfast/v3/internal/app/system/consts"
    systemService "github.com/tiger1103/gfast/v3/internal/app/system/service"
    "github.com/tiger1103/gfast/v3/library/libUtils"
    "github.com/tiger1103/gfast/v3/library/liberr"
)


func init() {
    service.RegisterDemoGen(New())
}


func New() *sDemoGen {
    return &sDemoGen{}
}

.....

注册logic,在boot中引入demo 模块的logic


package boot

import (
    _ "github.com/tiger1103/gfast/v3/internal/app/common/logic"
    _ "github.com/tiger1103/gfast/v3/internal/app/demo/logic"
    _ "github.com/tiger1103/gfast/v3/internal/app/system/logic"
)

6、创建对应controller


package controller


import (
    "context"
    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/service"
    systemController "github.com/tiger1103/gfast/v3/internal/app/system/controller"
)


type demoGenClassController struct {
    systemController.BaseController
}


var DemoGenClass = new(demoGenClassController)


// List 列表
func (c *demoGenClassController) List(ctx context.Context, req *demo.DemoGenClassSearchReq) (res *demo.DemoGenClassSearchRes, err error) {
    res, err = service.DemoGenClass().List(ctx, req)
    return
}


// Get 获取分类信息
func (c *demoGenClassController) Get(ctx context.Context, req *demo.DemoGenClassGetReq) (res *demo.DemoGenClassGetRes, err error) {
    res = new(demo.DemoGenClassGetRes)
    res.DemoGenClassInfoRes,err = service.DemoGenClass().GetById(ctx, req.Id)
    return
}


// Add 添加分类信息
func (c *demoGenClassController) Add(ctx context.Context, req *demo.DemoGenClassAddReq) (res *demo.DemoGenClassAddRes, err error) {
    err = service.DemoGenClass().Add(ctx, req)
    return
}


// Edit 修改分类信息
func (c *demoGenClassController) Edit(ctx context.Context, req *demo.DemoGenClassEditReq) (res *demo.DemoGenClassEditRes, err error) {
    err = service.DemoGenClass().Edit(ctx, req)
    return
}


// Delete 删除分类信息
func (c *demoGenClassController) Delete(ctx context.Context, req *demo.DemoGenClassDeleteReq) (res *demo.DemoGenClassDeleteRes, err error) {
    err = service.DemoGenClass().Delete(ctx, req.Ids)
    return
}

package controller


import (
    "context"
    "github.com/tiger1103/gfast/v3/api/v1/demo"
    "github.com/tiger1103/gfast/v3/internal/app/demo/service"
    systemController "github.com/tiger1103/gfast/v3/internal/app/system/controller"
)


type demoGenController struct {
    systemController.BaseController
}


var DemoGen = new(demoGenController)


// List 列表
func (c *demoGenController) List(ctx context.Context, req *demo.DemoGenSearchReq) (res *demo.DemoGenSearchRes, err error) {
    res, err = service.DemoGen().List(ctx, req)
    return
}


// Get 获取代码生成测试
func (c *demoGenController) Get(ctx context.Context, req *demo.DemoGenGetReq) (res *demo.DemoGenGetRes, err error) {
    res = new(demo.DemoGenGetRes)
    res.DemoGenInfoRes,err = service.DemoGen().GetById(ctx, req.Id)
    return
}


// Add 添加代码生成测试
func (c *demoGenController) Add(ctx context.Context, req *demo.DemoGenAddReq) (res *demo.DemoGenAddRes, err error) {
    err = service.DemoGen().Add(ctx, req)
    return
}


// Edit 修改代码生成测试
func (c *demoGenController) Edit(ctx context.Context, req *demo.DemoGenEditReq) (res *demo.DemoGenEditRes, err error) {
    err = service.DemoGen().Edit(ctx, req)
    return
}


// Delete 删除代码生成测试
func (c *demoGenController) Delete(ctx context.Context, req *demo.DemoGenDeleteReq) (res *demo.DemoGenDeleteRes, err error) {
    err = service.DemoGen().Delete(ctx, req.Ids)
    return
}

7、创建router


注意:主路由文件,此文件只需首次创建模块的时候创建,用于处理登录验证,日志记录,用户信息记录,并自动扫描模块中其它路由等。


package router


import (
    "context"
    "github.com/gogf/gf/v2/net/ghttp"
    "github.com/tiger1103/gfast/v3/internal/app/system/service"
    "github.com/tiger1103/gfast/v3/library/libRouter"
)


var R = new(Router)


type Router struct{}


func (router *Router) BindController(ctx context.Context, group *ghttp.RouterGroup) {
    group.Group("/demo", func(group *ghttp.RouterGroup) {
        //登录验证拦截
        service.GfToken().Middleware(group)
        //context拦截器
        group.Middleware(service.Middleware().Ctx, service.Middleware().Auth)
        //后台操作日志记录
        group.Hook("/*", ghttp.HookAfterOutput, service.OperateLog().OperationLog)
        //自动绑定定义的控制器
        if err := libRouter.RouterAutoBind(ctx, router, group); err != nil {
            panic(err)
        }
    })
}

功能路由,对应具体功能的路由文件:(会被主路由自动扫描加载)


package router


import (
"context"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/tiger1103/gfast/v3/internal/app/demo/controller"
)
func (router *Router) BindDemoGenClassController(ctx context.Context, group *ghttp.RouterGroup) {
    group.Group("/demoGenClass", func(group *ghttp.RouterGroup) {
        group.Bind(
            controller.DemoGenClass,
        )
    })
}


package router


import (
    "context"
    "github.com/gogf/gf/v2/net/ghttp"
    "github.com/tiger1103/gfast/v3/internal/app/demo/controller"
)
func (router *Router) BindDemoGenController(ctx context.Context, group *ghttp.RouterGroup) {
    group.Group("/demoGen", func(group *ghttp.RouterGroup) {
        group.Bind(
            controller.DemoGen,
        )
    })
}

8、 注册模块路由

注意:主路由文件,此文件只需首次创建模块的时候创建,用于处理登录验证,日志记录,用户信息记录,并自动扫描模块中其它路由等。

9、重启后端服务,查看api文档


查看api文档中已注册了对应的功能路由,说明后端功能已正常。

作者:管理员  创建时间:2023-01-06 15:04
最后编辑:管理员  更新时间:2024-02-21 17:36