diff --git a/mayfly_go_web/src/views/ops/db/DbList.vue b/mayfly_go_web/src/views/ops/db/DbList.vue index 23c3dffc..1df8c935 100644 --- a/mayfly_go_web/src/views/ops/db/DbList.vue +++ b/mayfly_go_web/src/views/ops/db/DbList.vue @@ -479,7 +479,7 @@ const search = async () => { pageTableRef.value.loading(true); let res: any = await dbApi.dbs.request(state.query); // 切割数据库 - res.list.forEach((e: any) => { + res.list?.forEach((e: any) => { e.popoverSelectDbVisible = false; e.dbs = e.database.split(' '); }); diff --git a/mayfly_go_web/src/views/ops/tag/TeamList.vue b/mayfly_go_web/src/views/ops/tag/TeamList.vue index 69b2a3ac..82ea462d 100755 --- a/mayfly_go_web/src/views/ops/tag/TeamList.vue +++ b/mayfly_go_web/src/views/ops/tag/TeamList.vue @@ -269,9 +269,9 @@ const deleteTeam = () => { const showMembers = async (team: any) => { state.showMemDialog.query.teamId = team.id; + state.showMemDialog.visible = true; await setMemebers(); state.showMemDialog.title = `[${team.name}] 成员信息`; - state.showMemDialog.visible = true; }; const getAccount = (username: any) => { diff --git a/server/internal/common/router/common.go b/server/internal/common/router/common.go index b7290f79..ee7030ab 100644 --- a/server/internal/common/router/common.go +++ b/server/internal/common/router/common.go @@ -12,10 +12,6 @@ func InitCommonRouter(router *gin.RouterGroup) { c := &api.Common{} { // 获取公钥 - common.GET("public-key", func(g *gin.Context) { - req.NewCtxWithGin(g). - DontNeedToken(). - Handle(c.RasPublicKey) - }) + req.NewGet("public-key", c.RasPublicKey).DontNeedToken().Group(common) } } diff --git a/server/internal/common/router/index.go b/server/internal/common/router/index.go index b1fcf93d..d1ea32c0 100644 --- a/server/internal/common/router/index.go +++ b/server/internal/common/router/index.go @@ -23,9 +23,6 @@ func InitIndexRouter(router *gin.RouterGroup) { } { // 首页基本信息统计 - index.GET("count", func(g *gin.Context) { - req.NewCtxWithGin(g). - Handle(i.Count) - }) + req.NewGet("count", i.Count).Group(index) } } diff --git a/server/internal/db/api/db.go b/server/internal/db/api/db.go index 8b1b9028..3a4a46df 100644 --- a/server/internal/db/api/db.go +++ b/server/internal/db/api/db.go @@ -35,8 +35,7 @@ const DEFAULT_ROW_SIZE = 5000 // @router /api/dbs [get] func (d *Db) Dbs(rc *req.Ctx) { - condition := new(entity.DbQuery) - condition.TagPathLike = rc.GinCtx.Query("tagPath") + queryCond, page := ginx.BindQueryAndPage[*entity.DbQuery](rc.GinCtx, new(entity.DbQuery)) // 不存在可访问标签id,即没有可操作数据 tagIds := d.TagApp.ListTagIdByAccountId(rc.LoginAccount.Id) @@ -44,16 +43,14 @@ func (d *Db) Dbs(rc *req.Ctx) { rc.ResData = model.EmptyPageResult[any]() return } - condition.TagIds = tagIds - rc.ResData = d.DbApp.GetPageList(condition, ginx.GetPageParam(rc.GinCtx), new([]vo.SelectDataDbVO)) + + queryCond.TagIds = tagIds + rc.ResData = d.DbApp.GetPageList(queryCond, page, new([]vo.SelectDataDbVO)) } func (d *Db) Save(rc *req.Ctx) { form := &form.DbForm{} - ginx.BindJsonAndValid(rc.GinCtx, form) - - db := new(entity.Db) - utils.Copy(db, form) + db := ginx.BindJsonAndCopyTo[*entity.Db](rc.GinCtx, form, new(entity.Db)) // 密码解密,并使用解密后的赋值 originPwd, err := utils.DefaultRsaDecrypt(form.Password, true) @@ -319,7 +316,6 @@ func (d *Db) DumpSql(rc *req.Ctx) { writer.WriteString("COMMIT;\n") } - rc.NoRes = true rc.ReqParam = fmt.Sprintf("%s, tables: %s, dumpType: %s", dbInstance.Info.GetLogDesc(), tablesStr, dumpType) } diff --git a/server/internal/db/api/db_sql_exec.go b/server/internal/db/api/db_sql_exec.go index b7e02a80..6f764030 100644 --- a/server/internal/db/api/db_sql_exec.go +++ b/server/internal/db/api/db_sql_exec.go @@ -12,12 +12,7 @@ type DbSqlExec struct { } func (d *DbSqlExec) DbSqlExecs(rc *req.Ctx) { - g := rc.GinCtx - m := &entity.DbSqlExec{DbId: uint64(ginx.QueryInt(g, "dbId", 0)), - Db: g.Query("db"), - Table: g.Query("table"), - Type: int8(ginx.QueryInt(g, "type", 0)), - } - m.CreatorId = rc.LoginAccount.Id - rc.ResData = d.DbSqlExecApp.GetPageList(m, ginx.GetPageParam(rc.GinCtx), new([]entity.DbSqlExec)) + queryCond, page := ginx.BindQueryAndPage(rc.GinCtx, new(entity.DbSqlExecQuery)) + queryCond.CreatorId = rc.LoginAccount.Id + rc.ResData = d.DbSqlExecApp.GetPageList(queryCond, page, new([]entity.DbSqlExec)) } diff --git a/server/internal/db/application/db_sql_exec.go b/server/internal/db/application/db_sql_exec.go index 1c44d116..46445199 100644 --- a/server/internal/db/application/db_sql_exec.go +++ b/server/internal/db/application/db_sql_exec.go @@ -52,7 +52,7 @@ type DbSqlExec interface { DeleteBy(condition *entity.DbSqlExec) // 分页获取 - GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] + GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] } func newDbSqlExecApp(dbExecSqlRepo repository.DbSqlExec) DbSqlExec { @@ -152,7 +152,7 @@ func (d *dbSqlExecAppImpl) DeleteBy(condition *entity.DbSqlExec) { d.dbSqlExecRepo.DeleteBy(condition) } -func (d *dbSqlExecAppImpl) GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { +func (d *dbSqlExecAppImpl) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { return d.dbSqlExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } diff --git a/server/internal/db/domain/entity/query.go b/server/internal/db/domain/entity/query.go index eed58e80..821e4f2e 100644 --- a/server/internal/db/domain/entity/query.go +++ b/server/internal/db/domain/entity/query.go @@ -16,8 +16,17 @@ type DbQuery struct { Database string `orm:"column(database)" json:"database"` Params string `json:"params"` Remark string `json:"remark"` - TagId uint64 - TagIds []uint64 - TagPathLike string + TagIds []uint64 + TagPath string `form:"tagPath"` +} + +type DbSqlExecQuery struct { + Id uint64 `json:"id" form:"id"` + DbId uint64 `json:"dbId" form:"dbId"` + Db string `json:"db" form:"db"` + Table string `json:"table" form:"table"` + Type int8 `json:"type" form:"type"` // 类型 + + CreatorId uint64 } diff --git a/server/internal/db/domain/repository/db_sql_exec.go b/server/internal/db/domain/repository/db_sql_exec.go index aef89c1f..b0a917b4 100644 --- a/server/internal/db/domain/repository/db_sql_exec.go +++ b/server/internal/db/domain/repository/db_sql_exec.go @@ -11,5 +11,5 @@ type DbSqlExec interface { DeleteBy(condition *entity.DbSqlExec) // 分页获取 - GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] + GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] } diff --git a/server/internal/db/infrastructure/persistence/db.go b/server/internal/db/infrastructure/persistence/db.go index fd8b77d8..e0d9d052 100644 --- a/server/internal/db/infrastructure/persistence/db.go +++ b/server/internal/db/infrastructure/persistence/db.go @@ -20,7 +20,7 @@ func (d *dbRepoImpl) GetDbList(condition *entity.DbQuery, pageParam *model.PageP Like("host", condition.Host). Like("database", condition.Database). In("tag_id", condition.TagIds). - RLike("tag_path", condition.TagPathLike). + RLike("tag_path", condition.TagPath). OrderByAsc("tag_path") return gormx.PageQuery(qd, pageParam, toEntity) } @@ -30,9 +30,6 @@ func (d *dbRepoImpl) Count(condition *entity.DbQuery) int64 { if len(condition.TagIds) > 0 { where["tag_id"] = condition.TagIds } - if condition.TagId != 0 { - where["tag_id"] = condition.TagId - } return gormx.CountByCond(new(entity.Db), where) } diff --git a/server/internal/db/infrastructure/persistence/db_sql_exec.go b/server/internal/db/infrastructure/persistence/db_sql_exec.go index 154af26b..1b6dadd9 100644 --- a/server/internal/db/infrastructure/persistence/db_sql_exec.go +++ b/server/internal/db/infrastructure/persistence/db_sql_exec.go @@ -23,7 +23,7 @@ func (d *dbSqlExecRepoImpl) DeleteBy(condition *entity.DbSqlExec) { } // 分页获取 -func (d *dbSqlExecRepoImpl) GetPageList(condition *entity.DbSqlExec, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { - qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...) +func (d *dbSqlExecRepoImpl) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { + qd := gormx.NewQuery(new(entity.DbSqlExec)).WithCondModel(condition).WithOrderBy(orderBy...) return gormx.PageQuery(qd, pageParam, toEntity) } diff --git a/server/internal/db/router/db.go b/server/internal/db/router/db.go index 15ff3fd3..5f998d2e 100644 --- a/server/internal/db/router/db.go +++ b/server/internal/db/router/db.go @@ -12,103 +12,55 @@ import ( func InitDbRouter(router *gin.RouterGroup) { db := router.Group("dbs") - { - d := &api.Db{ - DbApp: application.GetDbApp(), - DbSqlExecApp: application.GetDbSqlExecApp(), - MsgApp: msgapp.GetMsgApp(), - TagApp: tagapp.GetTagTreeApp(), - } - // 获取所有数据库列表 - db.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.Dbs) - }) - saveDb := req.NewLogInfo("db-保存数据库信息").WithSave(true) - db.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveDb). - Handle(d.Save) - }) + d := &api.Db{ + DbApp: application.GetDbApp(), + DbSqlExecApp: application.GetDbSqlExecApp(), + MsgApp: msgapp.GetMsgApp(), + TagApp: tagapp.GetTagTreeApp(), + } + + reqs := [...]*req.Conf{ + // 获取数据库列表 + req.NewGet("", d.Dbs), + + req.NewPost("", d.Save).Log(req.NewLogSave("db-保存数据库信息")), // 获取数据库实例的所有数据库名 - db.POST("databases", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(d.GetDatabaseNames) - }) + req.NewGet("/databases", d.GetDatabaseNames), - db.GET(":dbId/pwd", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.GetDbPwd) - }) + req.NewGet(":dbId/pwd", d.GetDbPwd), - deleteDb := req.NewLogInfo("db-删除数据库信息").WithSave(true) - db.DELETE(":dbId", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(deleteDb). - Handle(d.DeleteDb) - }) + req.NewDelete(":dbId", d.DeleteDb).Log(req.NewLogSave("db-删除数据库信息")), - db.GET(":dbId/t-infos", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.TableInfos) - }) + req.NewGet(":dbId/t-infos", d.TableInfos), - db.GET(":dbId/t-index", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.TableIndex) - }) + req.NewGet(":dbId/t-index", d.TableIndex), - db.GET(":dbId/t-create-ddl", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.GetCreateTableDdl) - }) + req.NewGet(":dbId/t-create-ddl", d.GetCreateTableDdl), - execSqlLog := req.NewLogInfo("db-执行Sql") - db.POST(":dbId/exec-sql", func(g *gin.Context) { - rc := req.NewCtxWithGin(g).WithLog(execSqlLog) - rc.Handle(d.ExecSql) - }) + req.NewPost(":dbId/exec-sql", d.ExecSql).Log(req.NewLog("db-执行Sql")), - execSqlFileLog := req.NewLogInfo("db-执行Sql文件").WithSave(true) - db.POST(":dbId/exec-sql-file", func(g *gin.Context) { - req.NewCtxWithGin(g). - WithLog(execSqlFileLog). - Handle(d.ExecSqlFile) - }) + req.NewPost(":dbId/exec-sql-file", d.ExecSqlFile).Log(req.NewLogSave("db-执行Sql文件")), - dumpLog := req.NewLogInfo("db-导出sql文件").WithSave(true) - db.GET(":dbId/dump", func(g *gin.Context) { - req.NewCtxWithGin(g). - WithLog(dumpLog). - Handle(d.DumpSql) - }) + req.NewGet(":dbId/dump", d.DumpSql).Log(req.NewLogSave("db-导出sql文件")).NoRes(), - db.GET(":dbId/t-metadata", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.TableMA) - }) + req.NewGet(":dbId/t-metadata", d.TableMA), - db.GET(":dbId/c-metadata", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.ColumnMA) - }) + req.NewGet(":dbId/c-metadata", d.ColumnMA), - db.GET(":dbId/hint-tables", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.HintTables) - }) + req.NewGet(":dbId/hint-tables", d.HintTables), - /** db sql相关接口 */ + // 用户sql相关 + req.NewPost(":dbId/sql", d.SaveSql), - db.POST(":dbId/sql", func(c *gin.Context) { - rc := req.NewCtxWithGin(c) - rc.Handle(d.SaveSql) - }) + req.NewGet(":dbId/sql", d.GetSql), - db.GET(":dbId/sql", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.GetSql) - }) + req.NewDelete(":dbId/sql", d.DeleteSql), - db.DELETE(":dbId/sql", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.DeleteSql) - }) - - db.GET(":dbId/sql-names", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(d.GetSqlNames) - }) + req.NewGet(":dbId/sql-names", d.GetSqlNames), } + + req.BatchSetGroup(db, reqs[:]) + } diff --git a/server/internal/db/router/db_sql_exec.go b/server/internal/db/router/db_sql_exec.go index 5cdbbf77..d610fef9 100644 --- a/server/internal/db/router/db_sql_exec.go +++ b/server/internal/db/router/db_sql_exec.go @@ -10,14 +10,12 @@ import ( func InitDbSqlExecRouter(router *gin.RouterGroup) { db := router.Group("/dbs/:dbId/sql-execs") - { - d := &api.DbSqlExec{ - DbSqlExecApp: application.GetDbSqlExecApp(), - } - // 获取所有数据库sql执行记录列表 - db.GET("", func(c *gin.Context) { - rc := req.NewCtxWithGin(c) - rc.Handle(d.DbSqlExecs) - }) + + d := &api.DbSqlExec{ + DbSqlExecApp: application.GetDbSqlExecApp(), } + + // 获取所有数据库sql执行记录列表 + req.NewGet("", d.DbSqlExecs).Group(db) + } diff --git a/server/internal/machine/api/auth_cert.go b/server/internal/machine/api/auth_cert.go index 3a9bf3b2..e1d32dbe 100644 --- a/server/internal/machine/api/auth_cert.go +++ b/server/internal/machine/api/auth_cert.go @@ -18,25 +18,15 @@ type AuthCert struct { } func (ac *AuthCert) BaseAuthCerts(rc *req.Ctx) { - g := rc.GinCtx - condition := &entity.AuthCert{ - Name: g.Query("name"), - AuthMethod: int8(ginx.QueryInt(g, "authMethod", 0)), - } - condition.Id = uint64(ginx.QueryInt(g, "id", 0)) - rc.ResData = ac.AuthCertApp.GetPageList(condition, ginx.GetPageParam(g), new([]vo.AuthCertBaseVO)) + queryCond, page := ginx.BindQueryAndPage(rc.GinCtx, new(entity.AuthCertQuery)) + rc.ResData = ac.AuthCertApp.GetPageList(queryCond, page, new([]vo.AuthCertBaseVO)) } func (ac *AuthCert) AuthCerts(rc *req.Ctx) { - g := rc.GinCtx - condition := &entity.AuthCert{ - Name: g.Query("name"), - AuthMethod: int8(ginx.QueryInt(g, "authMethod", 0)), - } - condition.Id = uint64(ginx.QueryInt(g, "id", 0)) + queryCond, page := ginx.BindQueryAndPage(rc.GinCtx, new(entity.AuthCertQuery)) res := new([]*entity.AuthCert) - pageRes := ac.AuthCertApp.GetPageList(condition, ginx.GetPageParam(g), res) + pageRes := ac.AuthCertApp.GetPageList(queryCond, page, res) for _, r := range *res { r.PwdDecrypt() } diff --git a/server/internal/machine/api/machine.go b/server/internal/machine/api/machine.go index 37e6e5c9..02e83b0c 100644 --- a/server/internal/machine/api/machine.go +++ b/server/internal/machine/api/machine.go @@ -33,10 +33,7 @@ type Machine struct { } func (m *Machine) Machines(rc *req.Ctx) { - condition := new(entity.MachineQuery) - condition.Ip = rc.GinCtx.Query("ip") - condition.Name = rc.GinCtx.Query("name") - condition.TagPathLike = rc.GinCtx.Query("tagPath") + condition, pageParam := ginx.BindQueryAndPage(rc.GinCtx, new(entity.MachineQuery)) // 不存在可访问标签id,即没有可操作数据 tagIds := m.TagApp.ListTagIdByAccountId(rc.LoginAccount.Id) @@ -46,7 +43,7 @@ func (m *Machine) Machines(rc *req.Ctx) { } condition.TagIds = tagIds - res := m.MachineApp.GetMachineList(condition, ginx.GetPageParam(rc.GinCtx), new([]*vo.MachineVO)) + res := m.MachineApp.GetMachineList(condition, pageParam, new([]*vo.MachineVO)) if res.Total == 0 { rc.ResData = res return @@ -65,12 +62,8 @@ func (m *Machine) MachineStats(rc *req.Ctx) { // 保存机器信息 func (m *Machine) SaveMachine(rc *req.Ctx) { - g := rc.GinCtx machineForm := new(form.MachineForm) - ginx.BindJsonAndValid(g, machineForm) - - me := new(entity.Machine) - utils.Copy(me, machineForm) + me := ginx.BindJsonAndCopyTo(rc.GinCtx, machineForm, new(entity.Machine)) machineForm.Password = "******" rc.ReqParam = machineForm @@ -199,7 +192,7 @@ func (m *Machine) WsSSH(g *gin.Context) { biz.ErrIsNilAppendErr(err, "\033[1;31m连接失败: %s\033[0m") // 记录系统操作日志 - rc.WithLog(req.NewLogInfo("机器-终端操作").WithSave(true)) + rc.WithLog(req.NewLogSave("机器-终端操作")) rc.ReqParam = cli.GetMachine().GetLogDesc() req.LogHandler(rc) diff --git a/server/internal/machine/api/machine_file.go b/server/internal/machine/api/machine_file.go index 748c0298..c0d95922 100644 --- a/server/internal/machine/api/machine_file.go +++ b/server/internal/machine/api/machine_file.go @@ -12,7 +12,6 @@ import ( "mayfly-go/pkg/biz" "mayfly-go/pkg/ginx" "mayfly-go/pkg/req" - "mayfly-go/pkg/utils" "mayfly-go/pkg/ws" "sort" "strconv" @@ -40,22 +39,16 @@ func (m *MachineFile) MachineFiles(rc *req.Ctx) { } func (m *MachineFile) SaveMachineFiles(rc *req.Ctx) { - g := rc.GinCtx fileForm := new(form.MachineFileForm) - ginx.BindJsonAndValid(g, fileForm) - - entity := new(entity.MachineFile) - utils.Copy(entity, fileForm) - + entity := ginx.BindJsonAndCopyTo[*entity.MachineFile](rc.GinCtx, fileForm, new(entity.MachineFile)) entity.SetBaseInfo(rc.LoginAccount) + rc.ReqParam = fileForm m.MachineFileApp.Save(entity) } func (m *MachineFile) DeleteFile(rc *req.Ctx) { - g := rc.GinCtx - fid := GetMachineFileId(g) - m.MachineFileApp.Delete(fid) + m.MachineFileApp.Delete(GetMachineFileId(rc.GinCtx)) } /*** sftp相关操作 */ @@ -64,8 +57,7 @@ func (m *MachineFile) CreateFile(rc *req.Ctx) { g := rc.GinCtx fid := GetMachineFileId(g) - form := new(form.MachineCreateFileForm) - ginx.BindJsonAndValid(g, form) + form := ginx.BindJsonAndValid(g, new(form.MachineCreateFileForm)) path := form.Path mi := m.MachineFileApp.GetMachine(fid) diff --git a/server/internal/machine/api/machine_script.go b/server/internal/machine/api/machine_script.go index 7c3153b6..e43092ce 100644 --- a/server/internal/machine/api/machine_script.go +++ b/server/internal/machine/api/machine_script.go @@ -31,12 +31,9 @@ func (m *MachineScript) MachineScripts(rc *req.Ctx) { func (m *MachineScript) SaveMachineScript(rc *req.Ctx) { form := new(form.MachineScriptForm) - ginx.BindJsonAndValid(rc.GinCtx, form) - rc.ReqParam = form + machineScript := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.MachineScript)) - // 转换为entity,并设置基本信息 - machineScript := new(entity.MachineScript) - utils.Copy(machineScript, form) + rc.ReqParam = form machineScript.SetBaseInfo(rc.LoginAccount) m.MachineScriptApp.Save(machineScript) diff --git a/server/internal/machine/application/auth_cert.go b/server/internal/machine/application/auth_cert.go index 82c7b621..397071e4 100644 --- a/server/internal/machine/application/auth_cert.go +++ b/server/internal/machine/application/auth_cert.go @@ -8,7 +8,7 @@ import ( ) type AuthCert interface { - GetPageList(condition *entity.AuthCert, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] + GetPageList(condition *entity.AuthCertQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] Save(ac *entity.AuthCert) @@ -29,7 +29,7 @@ type authCertAppImpl struct { authCertRepo repository.AuthCert } -func (a *authCertAppImpl) GetPageList(condition *entity.AuthCert, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { +func (a *authCertAppImpl) GetPageList(condition *entity.AuthCertQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { return a.authCertRepo.GetPageList(condition, pageParam, toEntity) } diff --git a/server/internal/machine/domain/entity/query.go b/server/internal/machine/domain/entity/query.go index 80754f2b..b1044749 100644 --- a/server/internal/machine/domain/entity/query.go +++ b/server/internal/machine/domain/entity/query.go @@ -1,21 +1,14 @@ package entity -import "mayfly-go/pkg/model" - type MachineQuery struct { - model.Model - Name string `json:"name"` - Ip string `json:"ip"` // IP地址 - Username string `json:"username"` // 用户名 - AuthMethod int8 `json:"authMethod"` // 授权认证方式 - Password string `json:"-"` - Port int `json:"port"` // 端口号 - Status int8 `json:"status"` // 状态 1:启用;2:停用 - Remark string `json:"remark"` // 备注 - SshTunnelMachineId uint64 `json:"sshTunnelMachineId"` // ssh隧道机器id - EnableRecorder int8 `json:"enableRecorder"` // 是否启用终端回放记录 - - TagId uint64 - TagPathLike string - TagIds []uint64 + Name string `json:"name" form:"name"` + Ip string `json:"ip" form:"ip"` // IP地址 + TagPath string `json:"tagPath" form:"tagPath"` + TagIds []uint64 +} + +type AuthCertQuery struct { + Id uint64 `json:"id" form:"id"` + Name string `json:"name" form:"name"` + AuthMethod string `json:"authMethod" form:"authMethod"` // IP地址 } diff --git a/server/internal/machine/domain/repository/auth_cert.go b/server/internal/machine/domain/repository/auth_cert.go index 4940d919..cb0c7066 100644 --- a/server/internal/machine/domain/repository/auth_cert.go +++ b/server/internal/machine/domain/repository/auth_cert.go @@ -6,7 +6,7 @@ import ( ) type AuthCert interface { - GetPageList(condition *entity.AuthCert, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] + GetPageList(condition *entity.AuthCertQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] Insert(ac *entity.AuthCert) diff --git a/server/internal/machine/infrastructure/persistence/auth_cert.go b/server/internal/machine/infrastructure/persistence/auth_cert.go index 882eeb87..179581ea 100644 --- a/server/internal/machine/infrastructure/persistence/auth_cert.go +++ b/server/internal/machine/infrastructure/persistence/auth_cert.go @@ -14,8 +14,8 @@ func newAuthCertRepo() repository.AuthCert { return new(authCertRepoImpl) } -func (m *authCertRepoImpl) GetPageList(condition *entity.AuthCert, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { - qd := gormx.NewQuery(condition).WithCondModel(condition).WithOrderBy(orderBy...) +func (m *authCertRepoImpl) GetPageList(condition *entity.AuthCertQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { + qd := gormx.NewQuery(new(entity.AuthCert)).WithCondModel(condition).WithOrderBy(orderBy...) return gormx.PageQuery(qd, pageParam, toEntity) } diff --git a/server/internal/machine/infrastructure/persistence/machine.go b/server/internal/machine/infrastructure/persistence/machine.go index b6302a5e..5709ef60 100644 --- a/server/internal/machine/infrastructure/persistence/machine.go +++ b/server/internal/machine/infrastructure/persistence/machine.go @@ -21,7 +21,7 @@ func (m *machineRepoImpl) GetMachineList(condition *entity.MachineQuery, pagePar Like("ip", condition.Ip). Like("name", condition.Name). In("tag_id", condition.TagIds). - RLike("tag_path", condition.TagPathLike). + RLike("tag_path", condition.TagPath). OrderByAsc("tag_path") return gormx.PageQuery(qd, pageParam, toEntity) } @@ -31,9 +31,6 @@ func (m *machineRepoImpl) Count(condition *entity.MachineQuery) int64 { if len(condition.TagIds) > 0 { where["tag_id"] = condition.TagIds } - if condition.TagId != 0 { - where["tag_id"] = condition.TagId - } return gormx.CountByCond(new(entity.Machine), where) } diff --git a/server/internal/machine/router/auth_cert.go b/server/internal/machine/router/auth_cert.go index 717db05a..2973a091 100644 --- a/server/internal/machine/router/auth_cert.go +++ b/server/internal/machine/router/auth_cert.go @@ -10,36 +10,19 @@ import ( func InitAuthCertRouter(router *gin.RouterGroup) { r := &api.AuthCert{AuthCertApp: application.GetAuthCertApp()} - db := router.Group("sys/authcerts") - { - listAcP := req.NewPermission("authcert") - db.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(listAcP). - Handle(r.AuthCerts) - }) + + ag := router.Group("sys/authcerts") + + reqs := [...]*req.Conf{ + req.NewGet("", r.AuthCerts).RequiredPermissionCode("authcert"), // 基础授权凭证信息,不包含密码等 - db.GET("base", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(r.BaseAuthCerts) - }) + req.NewGet("base", r.BaseAuthCerts), - saveAc := req.NewLogInfo("保存授权凭证").WithSave(true) - saveAcP := req.NewPermission("authcert:save") - db.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveAc). - WithRequiredPermission(saveAcP). - Handle(r.SaveAuthCert) - }) + req.NewPost("", r.SaveAuthCert).Log(req.NewLogSave("保存授权凭证")).RequiredPermissionCode("authcert:save"), - deleteAc := req.NewLogInfo("删除授权凭证").WithSave(true) - deleteAcP := req.NewPermission("authcert:del") - db.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(deleteAc). - WithRequiredPermission(deleteAcP). - Handle(r.Delete) - }) + req.NewDelete(":id", r.Delete).Log(req.NewLogSave("删除授权凭证")).RequiredPermissionCode("authcert:del"), } + + req.BatchSetGroup(ag, reqs[:]) } diff --git a/server/internal/machine/router/machine.go b/server/internal/machine/router/machine.go index 2190e45d..b03ca757 100644 --- a/server/internal/machine/router/machine.go +++ b/server/internal/machine/router/machine.go @@ -17,73 +17,34 @@ func InitMachineRouter(router *gin.RouterGroup) { machines := router.Group("machines") { - machines.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.Machines) - }) - - machines.GET(":machineId/stats", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.MachineStats) - }) - - machines.GET(":machineId/process", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.GetProcess) - }) - - // 终止进程 - killProcessL := req.NewLogInfo("终止进程").WithSave(true) - killProcessP := req.NewPermission("machine:killprocess") - machines.DELETE(":machineId/process", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(killProcessL). - WithRequiredPermission(killProcessP). - Handle(m.KillProcess) - }) - - saveMachine := req.NewLogInfo("保存机器信息").WithSave(true) saveMachineP := req.NewPermission("machine:update") - machines.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveMachine). - WithRequiredPermission(saveMachineP). - Handle(m.SaveMachine) - }) - machines.POST("test-conn", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(m.TestConn) - }) + reqs := [...]*req.Conf{ + req.NewGet("", m.Machines), - changeStatus := req.NewLogInfo("调整机器状态").WithSave(true) - machines.PUT(":machineId/:status", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(changeStatus). - WithRequiredPermission(saveMachineP). - Handle(m.ChangeStatus) - }) + req.NewGet(":machineId/stats", m.MachineStats), - delMachine := req.NewLogInfo("删除机器").WithSave(true) - machines.DELETE(":machineId", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(delMachine). - Handle(m.DeleteMachine) - }) + req.NewGet(":machineId/process", m.GetProcess), - closeCli := req.NewLogInfo("关闭机器客户端").WithSave(true) - closeCliP := req.NewPermission("machine:close-cli") - machines.DELETE(":machineId/close-cli", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(closeCli). - WithRequiredPermission(closeCliP). - Handle(m.CloseCli) - }) + req.NewDelete(":machineId/process", m.KillProcess).Log(req.NewLogSave("终止进程")).RequiredPermissionCode("machine:killprocess"), + req.NewPost("", m.SaveMachine).Log(req.NewLogSave("保存机器信息")).RequiredPermission(saveMachineP), + + req.NewPost("test-conn", m.TestConn), + + req.NewPut(":machineId/:status", m.ChangeStatus).Log(req.NewLogSave("调整机器状态")).RequiredPermission(saveMachineP), + + req.NewDelete(":machineId", m.DeleteMachine).Log(req.NewLogSave("删除机器")), + + req.NewDelete(":machineId/close-cli", m.CloseCli).Log(req.NewLogSave("关闭机器客户端")).RequiredPermissionCode("machine:close-cli"), + + // 获取机器终端回放记录的相应文件夹名或文件名,目前具有保存机器信息的权限标识才有权限查看终端回放 + req.NewGet("rec/names", m.MachineRecDirNames).RequiredPermission(saveMachineP), + } + + req.BatchSetGroup(machines, reqs[:]) + + // 终端连接 machines.GET(":machineId/terminal", m.WsSSH) - - // 获取机器终端回放记录的相应文件夹名或文件名,目前具有保存机器信息的权限标识才有权限查看终端回放 - machines.GET("rec/names", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(saveMachineP). - Handle(m.MachineRecDirNames) - }) } } diff --git a/server/internal/machine/router/machine_file.go b/server/internal/machine/router/machine_file.go index a82ba1df..a788080f 100644 --- a/server/internal/machine/router/machine_file.go +++ b/server/internal/machine/router/machine_file.go @@ -11,84 +11,36 @@ import ( func InitMachineFileRouter(router *gin.RouterGroup) { machineFile := router.Group("machines") - { - mf := &api.MachineFile{ - MachineFileApp: application.GetMachineFileApp(), - MsgApp: msgapp.GetMsgApp(), - } - // 获取指定机器文件列表 - machineFile.GET(":machineId/files", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(mf.MachineFiles) - }) - - // 新增修改机器文件 - addFileConf := req.NewLogInfo("机器-新增文件配置").WithSave(true) - afcP := req.NewPermission("machine:file:add") - machineFile.POST(":machineId/files", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(addFileConf). - WithRequiredPermission(afcP). - Handle(mf.SaveMachineFiles) - }) - - // 删除机器文件 - delFileConf := req.NewLogInfo("机器-删除文件配置").WithSave(true) - dfcP := req.NewPermission("machine:file:del") - machineFile.DELETE(":machineId/files/:fileId", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(delFileConf). - WithRequiredPermission(dfcP). - Handle(mf.DeleteFile) - }) - - getContent := req.NewLogInfo("机器-获取文件内容").WithSave(true) - machineFile.GET(":machineId/files/:fileId/read", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(getContent). - Handle(mf.ReadFileContent) - }) - - getDir := req.NewLogInfo("机器-获取目录") - machineFile.GET(":machineId/files/:fileId/read-dir", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(getDir). - Handle(mf.GetDirEntry) - }) - - machineFile.GET(":machineId/files/:fileId/dir-size", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(mf.GetDirSize) - }) - - machineFile.GET(":machineId/files/:fileId/file-stat", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(mf.GetFileStat) - }) - - writeFile := req.NewLogInfo("机器-修改文件内容").WithSave(true) - wfP := req.NewPermission("machine:file:write") - machineFile.POST(":machineId/files/:fileId/write", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(writeFile). - WithRequiredPermission(wfP). - Handle(mf.WriteFileContent) - }) - - createFile := req.NewLogInfo("机器-创建文件or目录").WithSave(true) - machineFile.POST(":machineId/files/:fileId/create-file", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(createFile). - WithRequiredPermission(wfP). - Handle(mf.CreateFile) - }) - - uploadFile := req.NewLogInfo("机器-文件上传").WithSave(true) - ufP := req.NewPermission("machine:file:upload") - machineFile.POST(":machineId/files/:fileId/upload", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(uploadFile). - WithRequiredPermission(ufP). - Handle(mf.UploadFile) - }) - - removeFile := req.NewLogInfo("机器-删除文件or文件夹").WithSave(true) - rfP := req.NewPermission("machine:file:rm") - machineFile.DELETE(":machineId/files/:fileId/remove", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(removeFile). - WithRequiredPermission(rfP). - Handle(mf.RemoveFile) - }) + mf := &api.MachineFile{ + MachineFileApp: application.GetMachineFileApp(), + MsgApp: msgapp.GetMsgApp(), } + + reqs := [...]*req.Conf{ + // 获取指定机器文件列表 + req.NewGet(":machineId/files", mf.MachineFiles), + + req.NewPost(":machineId/files", mf.SaveMachineFiles).Log(req.NewLogSave("机器-新增文件配置")).RequiredPermissionCode("machine:file:add"), + + req.NewDelete(":machineId/files/:fileId", mf.DeleteFile).Log(req.NewLogSave("机器-删除文件配置")).RequiredPermissionCode("machine:file:del"), + + req.NewGet(":machineId/files/:fileId/read", mf.ReadFileContent).Log(req.NewLogSave("机器-获取文件内容")), + + req.NewGet(":machineId/files/:fileId/read-dir", mf.GetDirEntry).Log(req.NewLogSave("机器-获取目录")), + + req.NewGet(":machineId/files/:fileId/dir-size", mf.GetDirSize), + + req.NewGet(":machineId/files/:fileId/file-stat", mf.GetFileStat), + + req.NewPost(":machineId/files/:fileId/write", mf.WriteFileContent).Log(req.NewLogSave("机器-修改文件内容")).RequiredPermissionCode("machine:file:write"), + + req.NewPost(":machineId/files/:fileId/create-file", mf.CreateFile).Log(req.NewLogSave("机器-创建文件or目录")), + + req.NewPost(":machineId/files/:fileId/upload", mf.UploadFile).Log(req.NewLogSave("机器-文件上传")).RequiredPermissionCode("machine:file:upload"), + + req.NewDelete(":machineId/files/:fileId/remove", mf.RemoveFile).Log(req.NewLogSave("机器-删除文件or文件夹")).RequiredPermissionCode("machine:file:rm"), + } + + req.BatchSetGroup(machineFile, reqs[:]) } diff --git a/server/internal/machine/router/machine_script.go b/server/internal/machine/router/machine_script.go index efa0c10b..20def008 100644 --- a/server/internal/machine/router/machine_script.go +++ b/server/internal/machine/router/machine_script.go @@ -11,43 +11,23 @@ import ( func InitMachineScriptRouter(router *gin.RouterGroup) { machines := router.Group("machines") - { - ms := &api.MachineScript{ - MachineScriptApp: application.GetMachineScriptApp(), - MachineApp: application.GetMachineApp(), - TagApp: tagapp.GetTagTreeApp(), - } - - // 获取指定机器脚本列表 - machines.GET(":machineId/scripts", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(ms.MachineScripts) - }) - - saveMachienScriptLog := req.NewLogInfo("机器-保存脚本").WithSave(true) - smsP := req.NewPermission("machine:script:save") - // 保存脚本 - machines.POST(":machineId/scripts", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveMachienScriptLog). - WithRequiredPermission(smsP). - Handle(ms.SaveMachineScript) - }) - - deleteLog := req.NewLogInfo("机器-删除脚本").WithSave(true) - dP := req.NewPermission("machine:script:del") - // 保存脚本 - machines.DELETE(":machineId/scripts/:scriptId", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(deleteLog). - WithRequiredPermission(dP). - Handle(ms.DeleteMachineScript) - }) - - runLog := req.NewLogInfo("机器-执行脚本").WithSave(true) - rP := req.NewPermission("machine:script:run") - // 运行脚本 - machines.GET(":machineId/scripts/:scriptId/run", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(runLog). - WithRequiredPermission(rP). - Handle(ms.RunMachineScript) - }) + ms := &api.MachineScript{ + MachineScriptApp: application.GetMachineScriptApp(), + MachineApp: application.GetMachineApp(), + TagApp: tagapp.GetTagTreeApp(), } + + reqs := [...]*req.Conf{ + // 获取指定机器脚本列表 + req.NewGet(":machineId/scripts", ms.MachineScripts), + + req.NewPost(":machineId/scripts", ms.SaveMachineScript).Log(req.NewLogSave("机器-保存脚本")).RequiredPermissionCode("machine:script:save"), + + req.NewDelete(":machineId/scripts/:scriptId", ms.DeleteMachineScript).Log(req.NewLogSave("机器-删除脚本")).RequiredPermissionCode("machine:script:del"), + + req.NewGet(":machineId/scripts/:scriptId/run", ms.RunMachineScript).Log(req.NewLogSave("机器-执行脚本")).RequiredPermissionCode("machine:script:run"), + } + + req.BatchSetGroup(machines, reqs[:]) + } diff --git a/server/internal/mongo/api/mongo.go b/server/internal/mongo/api/mongo.go index 9a4c990d..5878acf7 100644 --- a/server/internal/mongo/api/mongo.go +++ b/server/internal/mongo/api/mongo.go @@ -10,7 +10,6 @@ import ( "mayfly-go/pkg/ginx" "mayfly-go/pkg/model" "mayfly-go/pkg/req" - "mayfly-go/pkg/utils" "regexp" "strconv" "strings" @@ -27,8 +26,7 @@ type Mongo struct { } func (m *Mongo) Mongos(rc *req.Ctx) { - condition := new(entity.MongoQuery) - condition.TagPathLike = rc.GinCtx.Query("tagPath") + queryCond, page := ginx.BindQueryAndPage[*entity.MongoQuery](rc.GinCtx, new(entity.MongoQuery)) // 不存在可访问标签id,即没有可操作数据 tagIds := m.TagApp.ListTagIdByAccountId(rc.LoginAccount.Id) @@ -36,16 +34,14 @@ func (m *Mongo) Mongos(rc *req.Ctx) { rc.ResData = model.EmptyPageResult[any]() return } - condition.TagIds = tagIds - rc.ResData = m.MongoApp.GetPageList(condition, ginx.GetPageParam(rc.GinCtx), new([]entity.Mongo)) + queryCond.TagIds = tagIds + + rc.ResData = m.MongoApp.GetPageList(queryCond, page, new([]entity.Mongo)) } func (m *Mongo) Save(rc *req.Ctx) { form := &form.Mongo{} - ginx.BindJsonAndValid(rc.GinCtx, form) - - mongo := new(entity.Mongo) - utils.Copy(mongo, form) + mongo := ginx.BindJsonAndCopyTo[*entity.Mongo](rc.GinCtx, form, new(entity.Mongo)) // 密码脱敏记录日志 form.Uri = func(str string) string { diff --git a/server/internal/mongo/domain/entity/query.go b/server/internal/mongo/domain/entity/query.go index 90dbb37e..e0772b54 100644 --- a/server/internal/mongo/domain/entity/query.go +++ b/server/internal/mongo/domain/entity/query.go @@ -8,9 +8,7 @@ type MongoQuery struct { Name string Uri string SshTunnelMachineId uint64 // ssh隧道机器id - TagId uint64 `json:"tagId"` - TagPath string `json:"tagPath"` + TagPath string `json:"tagPath" form:"tagPath"` - TagIds []uint64 - TagPathLike string + TagIds []uint64 } diff --git a/server/internal/mongo/infrastructure/persistence/mongo.go b/server/internal/mongo/infrastructure/persistence/mongo.go index 7a453bd2..42216456 100644 --- a/server/internal/mongo/infrastructure/persistence/mongo.go +++ b/server/internal/mongo/infrastructure/persistence/mongo.go @@ -19,7 +19,7 @@ func (d *mongoRepoImpl) GetList(condition *entity.MongoQuery, pageParam *model.P qd := gormx.NewQuery(new(entity.Mongo)). Like("name", condition.Name). In("tag_id", condition.TagIds). - RLike("tag_path", condition.TagPathLike). + RLike("tag_path", condition.TagPath). OrderByAsc("tag_path") return gormx.PageQuery(qd, pageParam, toEntity) } @@ -29,9 +29,6 @@ func (d *mongoRepoImpl) Count(condition *entity.MongoQuery) int64 { if len(condition.TagIds) > 0 { where["tag_id"] = condition.TagIds } - if condition.TagId != 0 { - where["tag_id"] = condition.TagId - } return gormx.CountByCond(new(entity.Mongo), where) } diff --git a/server/internal/mongo/router/mongo.go b/server/internal/mongo/router/mongo.go index 2ef9b50c..a6fb59cd 100644 --- a/server/internal/mongo/router/mongo.go +++ b/server/internal/mongo/router/mongo.go @@ -11,78 +11,41 @@ import ( func InitMongoRouter(router *gin.RouterGroup) { m := router.Group("mongos") - { - ma := &api.Mongo{ - MongoApp: application.GetMongoApp(), - TagApp: tagapp.GetTagTreeApp(), - } + ma := &api.Mongo{ + MongoApp: application.GetMongoApp(), + TagApp: tagapp.GetTagTreeApp(), + } + + reqs := [...]*req.Conf{ // 获取所有mongo列表 - m.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(ma.Mongos) - }) + req.NewGet("", ma.Mongos), - saveMongo := req.NewLogInfo("mongo-保存信息") - m.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveMongo). - Handle(ma.Save) - }) + req.NewPost("", ma.Save).Log(req.NewLogSave("mongo-保存信息")), - deleteMongo := req.NewLogInfo("mongo-删除信息") - m.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(deleteMongo). - Handle(ma.DeleteMongo) - }) + req.NewDelete(":id", ma.DeleteMongo).Log(req.NewLogSave("mongo-删除信息")), // 获取mongo下的所有数据库 - m.GET(":id/databases", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(ma.Databases) - }) + req.NewGet(":id/databases", ma.Databases), // 获取mongo指定库的所有集合 - m.GET(":id/collections", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(ma.Collections) - }) + req.NewGet(":id/collections", ma.Collections), - // 获取mongo runCommand - m.POST(":id/run-command", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(ma.RunCommand) - }) + // mongo runCommand + req.NewPost(":id/run-command", ma.RunCommand).Log(req.NewLogSave("mongo-runCommand")), // 执行mongo find命令 - m.POST(":id/command/find", func(c *gin.Context) { - req.NewCtxWithGin(c). - Handle(ma.FindCommand) - }) + req.NewPost(":id/command/find", ma.FindCommand), - // 执行mongo update by id命令 - updateDocById := req.NewLogInfo("mongo-更新文档").WithSave(true) - m.POST(":id/command/update-by-id", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(updateDocById). - Handle(ma.UpdateByIdCommand) - }) + req.NewPost(":id/command/update-by-id", ma.UpdateByIdCommand).Log(req.NewLogSave("mongo-更新文档")), // 执行mongo delete by id命令 - deleteDoc := req.NewLogInfo("mongo-删除文档").WithSave(true) - m.POST(":id/command/delete-by-id", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(deleteDoc). - Handle(ma.DeleteByIdCommand) - }) + req.NewPost(":id/command/delete-by-id", ma.DeleteByIdCommand).Log(req.NewLogSave("mongo-删除文档")), // 执行mongo insert 命令 - insertDoc := req.NewLogInfo("mongo-新增文档").WithSave(true) - m.POST(":id/command/insert", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(insertDoc). - Handle(ma.InsertOneCommand) - }) + req.NewPost(":id/command/insert", ma.InsertOneCommand).Log(req.NewLogSave("mogno-插入文档")), } + + req.BatchSetGroup(m, reqs[:]) + } diff --git a/server/internal/msg/router/msg.go b/server/internal/msg/router/msg.go index 4e72c95d..844ab877 100644 --- a/server/internal/msg/router/msg.go +++ b/server/internal/msg/router/msg.go @@ -13,9 +13,6 @@ func InitMsgRouter(router *gin.RouterGroup) { a := &api.Msg{ MsgApp: application.GetMsgApp(), } - { - msg.GET("/self", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.GetMsgs) - }) - } + + req.NewGet("/self", a.GetMsgs).Group(msg) } diff --git a/server/internal/redis/api/redis.go b/server/internal/redis/api/redis.go index 5aa42a6b..bc72e2d2 100644 --- a/server/internal/redis/api/redis.go +++ b/server/internal/redis/api/redis.go @@ -25,8 +25,7 @@ type Redis struct { } func (r *Redis) RedisList(rc *req.Ctx) { - condition := new(entity.RedisQuery) - condition.TagPathLike = rc.GinCtx.Query("tagPath") + queryCond, page := ginx.BindQueryAndPage[*entity.RedisQuery](rc.GinCtx, new(entity.RedisQuery)) // 不存在可访问标签id,即没有可操作数据 tagIds := r.TagApp.ListTagIdByAccountId(rc.LoginAccount.Id) @@ -34,16 +33,14 @@ func (r *Redis) RedisList(rc *req.Ctx) { rc.ResData = model.EmptyPageResult[any]() return } - condition.TagIds = tagIds - rc.ResData = r.RedisApp.GetPageList(condition, ginx.GetPageParam(rc.GinCtx), new([]vo.Redis)) + queryCond.TagIds = tagIds + + rc.ResData = r.RedisApp.GetPageList(queryCond, page, new([]vo.Redis)) } func (r *Redis) Save(rc *req.Ctx) { form := &form.Redis{} - ginx.BindJsonAndValid(rc.GinCtx, form) - - redis := new(entity.Redis) - utils.Copy(redis, form) + redis := ginx.BindJsonAndCopyTo[*entity.Redis](rc.GinCtx, form, new(entity.Redis)) // 密码解密,并使用解密后的赋值 originPwd, err := utils.DefaultRsaDecrypt(redis.Password, true) diff --git a/server/internal/redis/domain/entity/query.go b/server/internal/redis/domain/entity/query.go index 829c4757..86c2c7ab 100644 --- a/server/internal/redis/domain/entity/query.go +++ b/server/internal/redis/domain/entity/query.go @@ -12,8 +12,7 @@ type RedisQuery struct { Db string `orm:"column(database)" json:"db"` SshTunnelMachineId int `orm:"column(ssh_tunnel_machine_id)" json:"sshTunnelMachineId"` // ssh隧道机器id Remark string - TagId uint64 - TagIds []uint64 - TagPathLike string + TagIds []uint64 + TagPath string `form:"tagPath"` } diff --git a/server/internal/redis/infrastructure/persistence/redis_repo.go b/server/internal/redis/infrastructure/persistence/redis_repo.go index 20974804..8c6db917 100644 --- a/server/internal/redis/infrastructure/persistence/redis_repo.go +++ b/server/internal/redis/infrastructure/persistence/redis_repo.go @@ -19,7 +19,7 @@ func (r *redisRepoImpl) GetRedisList(condition *entity.RedisQuery, pageParam *mo qd := gormx.NewQuery(new(entity.Redis)). Like("host", condition.Host). In("tag_id", condition.TagIds). - RLike("tag_path", condition.TagPathLike). + RLike("tag_path", condition.TagPath). OrderByAsc("tag_path") return gormx.PageQuery(qd, pageParam, toEntity) } @@ -29,9 +29,6 @@ func (r *redisRepoImpl) Count(condition *entity.RedisQuery) int64 { if len(condition.TagIds) > 0 { where["tag_id"] = condition.TagIds } - if condition.TagId != 0 { - where["tag_id"] = condition.TagId - } return gormx.CountByCond(new(entity.Redis), where) } diff --git a/server/internal/redis/router/redis.go b/server/internal/redis/router/redis.go index 6b297a57..c404ef5b 100644 --- a/server/internal/redis/router/redis.go +++ b/server/internal/redis/router/redis.go @@ -11,215 +11,98 @@ import ( func InitRedisRouter(router *gin.RouterGroup) { redis := router.Group("redis") - { - rs := &api.Redis{ - RedisApp: application.GetRedisApp(), - TagApp: tagapp.GetTagTreeApp(), - } + rs := &api.Redis{ + RedisApp: application.GetRedisApp(), + TagApp: tagapp.GetTagTreeApp(), + } + + // 保存数据权限 + saveDataP := req.NewPermission("redis:data:save") + // 删除数据权限 + deleteDataP := req.NewPermission("redis:data:del") + + reqs := [...]*req.Conf{ // 获取redis list - redis.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.RedisList) - }) + req.NewGet("", rs.RedisList), - save := req.NewLogInfo("redis-保存信息").WithSave(true) - redis.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(save).Handle(rs.Save) - }) + req.NewPost("", rs.Save).Log(req.NewLogSave("redis-保存信息")), - redis.GET(":id/pwd", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.GetRedisPwd) - }) + req.NewGet(":id/pwd", rs.GetRedisPwd), - delRedis := req.NewLogInfo("redis-删除信息").WithSave(true) - redis.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(delRedis).Handle(rs.DeleteRedis) - }) + req.NewDelete(":id", rs.DeleteRedis).Log(req.NewLogSave("redis-删除信息")), - redis.GET(":id/info", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.RedisInfo) - }) + req.NewGet("/:id/info", rs.RedisInfo), - redis.GET(":id/cluster-info", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.ClusterInfo) - }) + req.NewGet(":id/cluster-info", rs.ClusterInfo), // 获取指定redis keys - redis.POST(":id/:db/scan", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.Scan) - }) + req.NewPost(":id/:db/scan", rs.Scan), - redis.GET(":id/:db/key-ttl", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.TtlKey) - }) + req.NewGet(":id/:db/key-ttl", rs.TtlKey), - // 保存数据权限 - saveDataP := req.NewPermission("redis:data:save") - // 删除数据权限 - deleteDataP := req.NewPermission("redis:data:del") + req.NewDelete(":id/:db/key", rs.DeleteKey).Log(req.NewLogSave("redis-删除key")).RequiredPermission(deleteDataP), - // 删除key - deleteKeyL := req.NewLogInfo("redis-删除key").WithSave(true) - redis.DELETE(":id/:db/key", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(deleteKeyL). - WithRequiredPermission(deleteDataP). - Handle(rs.DeleteKey) - }) + req.NewPost(":id/:db/rename-key", rs.RenameKey).Log(req.NewLogSave("redis-重命名key")).RequiredPermission(saveDataP), - renameKeyL := req.NewLogInfo("redis-重命名key").WithSave(true) - redis.POST(":id/:db/rename-key", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(renameKeyL). - WithRequiredPermission(saveDataP). - Handle(rs.RenameKey) - }) + req.NewPost(":id/:db/expire-key", rs.ExpireKey).Log(req.NewLogSave("redis-设置key过期时间")).RequiredPermission(saveDataP), - expireKeyL := req.NewLogInfo("redis-设置key过期时间").WithSave(true) - redis.POST(":id/:db/expire-key", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(expireKeyL). - WithRequiredPermission(saveDataP). - Handle(rs.ExpireKey) - }) + req.NewDelete(":id/:db/persist-key", rs.PersistKey).Log(req.NewLogSave("redis-移除key过期时间")).RequiredPermission(saveDataP), - persistKeyL := req.NewLogInfo("redis-移除key过期时间").WithSave(true) - redis.DELETE(":id/:db/persist-key", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(persistKeyL). - WithRequiredPermission(saveDataP). - Handle(rs.PersistKey) - }) - - flushDbL := req.NewLogInfo("redis-flushdb").WithSave(true) - redis.DELETE(":id/:db/flushdb", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(flushDbL). - WithRequiredPermission(saveDataP). - Handle(rs.FlushDb) - }) + req.NewDelete(":id/:db/flushdb", rs.FlushDb).Log(req.NewLogSave("redis-flushdb")).RequiredPermission(deleteDataP), // 获取string类型值 - redis.GET(":id/:db/string-value", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.GetStringValue) - }) + req.NewGet(":id/:db/string-value", rs.GetStringValue), // 设置string类型值 - setStringL := req.NewLogInfo("redis-setString").WithSave(true) - redis.POST(":id/:db/string-value", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(setStringL). - WithRequiredPermission(saveDataP). - Handle(rs.SetStringValue) - }) + req.NewPost(":id/:db/string-value", rs.SetStringValue).Log(req.NewLogSave("redis-setString")).RequiredPermission(saveDataP), - // hscan - redis.GET(":id/:db/hscan", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.Hscan) - }) + // ———————————————— hash操作 ———————————————— + req.NewGet(":id/:db/hscan", rs.Hscan), - redis.GET(":id/:db/hget", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.Hget) - }) + req.NewGet(":id/:db/hget", rs.Hget), - hsetL := req.NewLogInfo("redis-hset").WithSave(true) - redis.POST(":id/:db/hset", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(hsetL). - WithRequiredPermission(saveDataP). - Handle(rs.Hset) - }) + req.NewPost(":id/:db/hset", rs.Hset).Log(req.NewLogSave("redis-hset")).RequiredPermission(saveDataP), - hdelL := req.NewLogInfo("redis-hdel").WithSave(true) - redis.DELETE(":id/:db/hdel", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(hdelL). - WithRequiredPermission(deleteDataP). - Handle(rs.Hdel) - }) + req.NewDelete(":id/:db/hdel", rs.Hdel).Log(req.NewLogSave("redis-hdel")).RequiredPermission(deleteDataP), // 设置hash类型值 - setHashValueL := req.NewLogInfo("redis-setHashValue").WithSave(true) - redis.POST(":id/:db/hash-value", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(setHashValueL). - WithRequiredPermission(saveDataP). - Handle(rs.SetHashValue) - }) + req.NewPost(":id/:db/hash-value", rs.SetHashValue).Log(req.NewLogSave("redis-setHashValue")).RequiredPermission(saveDataP), - // set操作 - redis.GET(":id/:db/set-value", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.GetSetValue) - }) + // --------------- set操作 ---------------- + req.NewGet(":id/:db/set-value", rs.GetSetValue), - redis.POST(":id/:db/set-value", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(saveDataP). - Handle(rs.SetSetValue) - }) + req.NewPost(":id/:db/set-value", rs.SetSetValue).RequiredPermission(saveDataP), - redis.GET(":id/:db/scard", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.Scard) - }) + req.NewGet(":id/:db/scard", rs.Scard), - redis.POST(":id/:db/sscan", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.Sscan) - }) + req.NewPost(":id/:db/sscan", rs.Sscan), - redis.POST(":id/:db/sadd", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(saveDataP). - Handle(rs.Sadd) - }) + req.NewPost(":id/:db/sadd", rs.Sadd).RequiredPermission(saveDataP), - redis.POST(":id/:db/srem", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(deleteDataP). - Handle(rs.Srem) - }) + req.NewPost(":id/:db/srem", rs.Srem).RequiredPermission(deleteDataP), - // 获取list类型值 - redis.GET(":id/:db/list-value", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.GetListValue) - }) + // --------------- list操作 ---------------- + req.NewGet(":id/:db/list-value", rs.GetListValue), - redis.POST(":id/:db/list-value", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.SaveListValue) - }) + req.NewPost(":id/:db/list-value", rs.SaveListValue).RequiredPermission(saveDataP), - redis.POST(":id/:db/list-value/lset", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.SetListValue) - }) + req.NewPost(":id/:db/list-value/lset", rs.SetListValue).RequiredPermission(saveDataP), - redis.POST(":id/:db/lrem", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(deleteDataP). - Handle(rs.Lrem) - }) + req.NewPost(":id/:db/lrem", rs.Lrem).RequiredPermission(deleteDataP), - // zset操作 - redis.GET(":id/:db/zcard", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.ZCard) - }) + // --------------- zset操作 ---------------- + req.NewGet(":id/:db/zcard", rs.ZCard), - redis.GET(":id/:db/zscan", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.ZScan) - }) + req.NewGet(":id/:db/zscan", rs.ZScan), - redis.GET(":id/:db/zrevrange", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(rs.ZRevRange) - }) + req.NewGet(":id/:db/zrevrange", rs.ZRevRange), - redis.POST(":id/:db/zrem", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(deleteDataP). - Handle(rs.ZRem) - }) + req.NewPost(":id/:db/zrem", rs.ZRem).Log(req.NewLogSave("redis-zrem")).RequiredPermission(deleteDataP), - redis.POST(":id/:db/zadd", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(saveDataP). - Handle(rs.ZAdd) - }) + req.NewPost(":id/:db/zadd", rs.ZAdd).RequiredPermission(saveDataP), } + + req.BatchSetGroup(redis, reqs[:]) + } diff --git a/server/internal/sys/api/account.go b/server/internal/sys/api/account.go index ddd6ca43..8ab85b58 100644 --- a/server/internal/sys/api/account.go +++ b/server/internal/sys/api/account.go @@ -283,11 +283,7 @@ func (a *Account) AccountInfo(rc *req.Ctx) { // 更新个人账号信息 func (a *Account) UpdateAccount(rc *req.Ctx) { - updateForm := &form.AccountUpdateForm{} - ginx.BindJsonAndValid(rc.GinCtx, updateForm) - - updateAccount := new(entity.Account) - utils.Copy(updateAccount, updateForm) + updateAccount := ginx.BindJsonAndCopyTo[*entity.Account](rc.GinCtx, new(form.AccountUpdateForm), new(entity.Account)) // 账号id为登录者账号 updateAccount.Id = rc.LoginAccount.Id @@ -310,11 +306,10 @@ func (a *Account) Accounts(rc *req.Ctx) { // @router /accounts func (a *Account) SaveAccount(rc *req.Ctx) { form := &form.AccountCreateForm{} - ginx.BindJsonAndValid(rc.GinCtx, form) - rc.ReqParam = form + account := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.Account)) - account := &entity.Account{} - utils.Copy(account, form) + form.Password = "*****" + rc.ReqParam = form account.SetBaseInfo(rc.LoginAccount) if account.Id == 0 { diff --git a/server/internal/sys/api/config.go b/server/internal/sys/api/config.go index 248f0427..2d59d450 100644 --- a/server/internal/sys/api/config.go +++ b/server/internal/sys/api/config.go @@ -7,7 +7,6 @@ import ( "mayfly-go/pkg/biz" "mayfly-go/pkg/ginx" "mayfly-go/pkg/req" - "mayfly-go/pkg/utils" ) type Config struct { @@ -27,13 +26,9 @@ func (c *Config) GetConfigValueByKey(rc *req.Ctx) { } func (c *Config) SaveConfig(rc *req.Ctx) { - g := rc.GinCtx form := &form.ConfigForm{} - ginx.BindJsonAndValid(g, form) + config := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.Config)) rc.ReqParam = form - - config := new(entity.Config) - utils.Copy(config, form) config.SetBaseInfo(rc.LoginAccount) c.ConfigApp.Save(config) } diff --git a/server/internal/sys/api/resource.go b/server/internal/sys/api/resource.go index 97c5c0ce..04e469f1 100644 --- a/server/internal/sys/api/resource.go +++ b/server/internal/sys/api/resource.go @@ -9,7 +9,6 @@ import ( "mayfly-go/internal/sys/domain/entity" "mayfly-go/pkg/ginx" "mayfly-go/pkg/req" - "mayfly-go/pkg/utils" ) type Resource struct { @@ -29,11 +28,10 @@ func (r *Resource) GetById(rc *req.Ctx) { func (r *Resource) SaveResource(rc *req.Ctx) { g := rc.GinCtx form := new(form.ResourceForm) - ginx.BindJsonAndValid(g, form) + entity := ginx.BindJsonAndCopyTo(g, form, new(entity.Resource)) + rc.ReqParam = form - entity := new(entity.Resource) - utils.Copy(entity, form) // 将meta转为json字符串存储 bytes, _ := json.Marshal(form.Meta) entity.Meta = string(bytes) diff --git a/server/internal/sys/api/role.go b/server/internal/sys/api/role.go index acc40faf..44e3946e 100644 --- a/server/internal/sys/api/role.go +++ b/server/internal/sys/api/role.go @@ -27,13 +27,9 @@ func (r *Role) Roles(rc *req.Ctx) { // 保存角色信息 func (r *Role) SaveRole(rc *req.Ctx) { - g := rc.GinCtx form := &form.RoleForm{} - ginx.BindJsonAndValid(g, form) + role := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.Role)) rc.ReqParam = form - - role := new(entity.Role) - utils.Copy(role, form) role.SetBaseInfo(rc.LoginAccount) r.RoleApp.SaveRole(role) diff --git a/server/internal/sys/api/syslog.go b/server/internal/sys/api/syslog.go index 4317f740..1bade1c7 100644 --- a/server/internal/sys/api/syslog.go +++ b/server/internal/sys/api/syslog.go @@ -12,11 +12,6 @@ type Syslog struct { } func (r *Syslog) Syslogs(rc *req.Ctx) { - g := rc.GinCtx - condition := &entity.Syslog{ - Type: int8(ginx.QueryInt(g, "type", 0)), - CreatorId: uint64(ginx.QueryInt(g, "creatorId", 0)), - Description: ginx.Query(g, "description", ""), - } - rc.ResData = r.SyslogApp.GetPageList(condition, ginx.GetPageParam(g), new([]entity.Syslog), "create_time DESC") + queryCond, page := ginx.BindQueryAndPage[*entity.SysLogQuery](rc.GinCtx, new(entity.SysLogQuery)) + rc.ResData = r.SyslogApp.GetPageList(queryCond, page, new([]entity.SysLog), "create_time DESC") } diff --git a/server/internal/sys/application/syslog.go b/server/internal/sys/application/syslog.go index 81419ac1..4913c939 100644 --- a/server/internal/sys/application/syslog.go +++ b/server/internal/sys/application/syslog.go @@ -13,7 +13,7 @@ import ( ) type Syslog interface { - GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] + GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] // 从请求上下文的参数保存系统日志 SaveFromReq(req *req.Ctx) @@ -29,7 +29,7 @@ type syslogAppImpl struct { syslogRepo repository.Syslog } -func (m *syslogAppImpl) GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { +func (m *syslogAppImpl) GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { return m.syslogRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } @@ -38,13 +38,13 @@ func (m *syslogAppImpl) SaveFromReq(req *req.Ctx) { if lg == nil { lg = &model.LoginAccount{Id: 0, Username: "-"} } - syslog := new(entity.Syslog) + syslog := new(entity.SysLog) syslog.CreateTime = time.Now() syslog.Creator = lg.Username syslog.CreatorId = lg.Id - syslog.Description = req.LogInfo.Description + syslog.Description = req.GetLogInfo().Description - if req.LogInfo.LogResp { + if req.GetLogInfo().LogResp { respB, _ := json.Marshal(req.ResData) syslog.Resp = string(respB) } diff --git a/server/internal/sys/domain/entity/query.go b/server/internal/sys/domain/entity/query.go new file mode 100644 index 00000000..ddb58b9d --- /dev/null +++ b/server/internal/sys/domain/entity/query.go @@ -0,0 +1,7 @@ +package entity + +type SysLogQuery struct { + CreatorId uint64 `json:"creatorId" form:"creatorId"` + Type int8 `json:"type" form:"type"` + Description string `json:"description" form:"description"` +} diff --git a/server/internal/sys/domain/entity/syslog.go b/server/internal/sys/domain/entity/syslog.go index 19d55508..9a851b97 100644 --- a/server/internal/sys/domain/entity/syslog.go +++ b/server/internal/sys/domain/entity/syslog.go @@ -3,7 +3,7 @@ package entity import "time" // 系统操作日志 -type Syslog struct { +type SysLog struct { Id uint64 `json:"id"` CreateTime time.Time `json:"createTime"` CreatorId uint64 `json:"creatorId"` @@ -15,7 +15,7 @@ type Syslog struct { Resp string `json:"resp"` // 响应结构 } -func (a *Syslog) TableName() string { +func (a *SysLog) TableName() string { return "t_sys_log" } diff --git a/server/internal/sys/domain/repository/syslog.go b/server/internal/sys/domain/repository/syslog.go index 15d99e7f..5f770668 100644 --- a/server/internal/sys/domain/repository/syslog.go +++ b/server/internal/sys/domain/repository/syslog.go @@ -6,7 +6,7 @@ import ( ) type Syslog interface { - GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] + GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] - Insert(log *entity.Syslog) + Insert(log *entity.SysLog) } diff --git a/server/internal/sys/infrastructure/persistence/syslog.go b/server/internal/sys/infrastructure/persistence/syslog.go index 1d877af4..089331fe 100644 --- a/server/internal/sys/infrastructure/persistence/syslog.go +++ b/server/internal/sys/infrastructure/persistence/syslog.go @@ -13,12 +13,12 @@ func newSyslogRepo() repository.Syslog { return new(syslogRepoImpl) } -func (m *syslogRepoImpl) GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { - qd := gormx.NewQuery(condition).Like("description", condition.Description). +func (m *syslogRepoImpl) GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) *model.PageResult[any] { + qd := gormx.NewQuery(new(entity.SysLog)).Like("description", condition.Description). Eq("creator_id", condition.CreatorId).Eq("type", condition.Type).WithOrderBy(orderBy...) return gormx.PageQuery(qd, pageParam, toEntity) } -func (m *syslogRepoImpl) Insert(syslog *entity.Syslog) { +func (m *syslogRepoImpl) Insert(syslog *entity.SysLog) { gormx.Insert(syslog) } diff --git a/server/internal/sys/router/account.go b/server/internal/sys/router/account.go index 28162be7..eb7b4ce4 100644 --- a/server/internal/sys/router/account.go +++ b/server/internal/sys/router/account.go @@ -18,107 +18,52 @@ func InitAccountRouter(router *gin.RouterGroup) { MsgApp: msgapp.GetMsgApp(), ConfigApp: application.GetConfigApp(), } - { - // 用户登录 - loginLog := req.NewLogInfo("用户登录").WithSave(true) - account.POST("login", func(g *gin.Context) { - req.NewCtxWithGin(g). - DontNeedToken(). - WithLog(loginLog). - Handle(a.Login) - }) - account.POST("otp-verify", func(g *gin.Context) { - req.NewCtxWithGin(g). - DontNeedToken(). - Handle(a.OtpVerify) - }) + addAccountPermission := req.NewPermission("account:add") + + reqs := [...]*req.Conf{ + // 用户登录 + req.NewPost("/login", a.Login).Log(req.NewLogSave("用户登录")).DontNeedToken(), + + // otp双因素校验 + req.NewPost("/otp-verify", a.OtpVerify).DontNeedToken(), // 获取个人账号的权限资源信息 - account.GET("/permissions", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.GetPermissions) - }) + req.NewGet("/permissions", a.GetPermissions), - changePwdLog := req.NewLogInfo("用户修改密码").WithSave(true) - account.POST("change-pwd", func(g *gin.Context) { - req.NewCtxWithGin(g). - DontNeedToken(). - WithLog(changePwdLog). - Handle(a.ChangePassword) - }) + req.NewPost("/change-pwd", a.ChangePassword).DontNeedToken().Log(req.NewLogSave("用户修改密码")), // 获取个人账号信息 - account.GET("/self", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.AccountInfo) - }) + req.NewGet("/self", a.AccountInfo), // 更新个人账号信息 - account.PUT("/self", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.UpdateAccount) - }) + req.NewPut("/self", a.UpdateAccount), /** 后台管理接口 **/ // 获取所有用户列表 - account.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.Accounts) - }) + req.NewGet("", a.Accounts), - createAccount := req.NewLogInfo("保存账号信息").WithSave(true) - addAccountPermission := req.NewPermission("account:add") - account.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(addAccountPermission). - WithLog(createAccount). - Handle(a.SaveAccount) - }) + req.NewPost("", a.SaveAccount).Log(req.NewLogSave("保存账号信息")).RequiredPermission(addAccountPermission), - changeStatus := req.NewLogInfo("修改账号状态").WithSave(true) - account.PUT("change-status/:id/:status", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(changeStatus). - Handle(a.ChangeStatus) - }) + req.NewPut("change-status/:id/:status", a.ChangeStatus).Log(req.NewLogSave("修改账号状态")).RequiredPermission(addAccountPermission), - resetOtpSecret := req.NewLogInfo("重置OTP密钥").WithSave(true) - account.PUT(":id/reset-otp", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(addAccountPermission). - WithLog(resetOtpSecret). - Handle(a.ResetOtpSecret) - }) + req.NewPut(":id/reset-otp", a.ResetOtpSecret).Log(req.NewLogSave("重置OTP密钥")).RequiredPermission(addAccountPermission), - delAccount := req.NewLogInfo("删除账号").WithSave(true) - delAccountPermission := req.NewPermission("account:del") - account.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithRequiredPermission(delAccountPermission). - WithLog(delAccount). - Handle(a.DeleteAccount) - }) + req.NewDelete(":id", a.DeleteAccount).Log(req.NewLogSave("删除账号")).RequiredPermissionCode("account:del"), // 获取所有用户角色id列表 - account.GET(":id/roleIds", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.AccountRoleIds) - }) + req.NewGet(":id/roleIds", a.AccountRoleIds), // 保存用户角色 - saveAccountRole := req.NewLogInfo("保存用户角色").WithSave(true) - sarPermission := req.NewPermission("account:saveRoles") - account.POST("/roles", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveAccountRole). - WithRequiredPermission(sarPermission). - Handle(a.SaveRoles) - }) + req.NewPost("/roles", a.SaveRoles).Log(req.NewLogSave("保存用户角色")).RequiredPermissionCode("account:saveRoles"), // 获取用户角色 - account.GET(":id/roles", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.AccountRoles) - }) + req.NewGet(":id/roles", a.AccountRoles), // 获取用户资源列表 - account.GET(":id/resources", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(a.AccountResources) - }) + req.NewGet(":id/resources", a.AccountResources), } + + req.BatchSetGroup(account, reqs[:]) } diff --git a/server/internal/sys/router/captcha.go b/server/internal/sys/router/captcha.go index a32f3799..3e244414 100644 --- a/server/internal/sys/router/captcha.go +++ b/server/internal/sys/router/captcha.go @@ -10,8 +10,6 @@ import ( func InitCaptchaRouter(router *gin.RouterGroup) { captcha := router.Group("sys/captcha") { - captcha.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).DontNeedToken().Handle(api.GenerateCaptcha) - }) + req.NewGet("", api.GenerateCaptcha).DontNeedToken().Group(captcha) } } diff --git a/server/internal/sys/router/config.go b/server/internal/sys/router/config.go index d360e64d..8839427f 100644 --- a/server/internal/sys/router/config.go +++ b/server/internal/sys/router/config.go @@ -10,24 +10,18 @@ import ( func InitSysConfigRouter(router *gin.RouterGroup) { r := &api.Config{ConfigApp: application.GetConfigApp()} - db := router.Group("sys/configs") - { - baseP := req.NewPermission("config:base") - db.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).WithRequiredPermission(baseP).Handle(r.Configs) - }) + configG := router.Group("sys/configs") - db.GET("/value", func(c *gin.Context) { - req.NewCtxWithGin(c).DontNeedToken().Handle(r.GetConfigValueByKey) - }) + baseP := req.NewPermission("config:base") - saveConfig := req.NewLogInfo("保存系统配置信息").WithSave(true) - saveConfigP := req.NewPermission("config:save") - db.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveConfig). - WithRequiredPermission(saveConfigP). - Handle(r.SaveConfig) - }) + reqs := [...]*req.Conf{ + req.NewGet("", r.Configs).RequiredPermission(baseP), + + // 获取指定配置key对应的值 + req.NewGet("/value", r.GetConfigValueByKey).DontNeedToken(), + + req.NewPost("", r.SaveConfig).Log(req.NewLogSave("保存系统配置信息")).RequiredPermissionCode("config:save"), } + + req.BatchSetGroup(configG, reqs[:]) } diff --git a/server/internal/sys/router/resource.go b/server/internal/sys/router/resource.go index 890f5c75..4f2ba00c 100644 --- a/server/internal/sys/router/resource.go +++ b/server/internal/sys/router/resource.go @@ -10,48 +10,21 @@ import ( func InitResourceRouter(router *gin.RouterGroup) { r := &api.Resource{ResourceApp: application.GetResourceApp()} - db := router.Group("sys/resources") - { - db.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(r.GetAllResourceTree) - }) + rg := router.Group("sys/resources") - db.GET(":id", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(r.GetById) - }) + reqs := [...]*req.Conf{ + req.NewGet("", r.GetAllResourceTree), - saveResource := req.NewLogInfo("保存资源").WithSave(true) - srPermission := req.NewPermission("resource:add") - db.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveResource). - WithRequiredPermission(srPermission). - Handle(r.SaveResource) - }) + req.NewGet(":id", r.GetById), - changeStatus := req.NewLogInfo("修改资源状态").WithSave(true) - csPermission := req.NewPermission("resource:changeStatus") - db.PUT(":id/:status", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(changeStatus). - WithRequiredPermission(csPermission). - Handle(r.ChangeStatus) - }) + req.NewPost("", r.SaveResource).Log(req.NewLogSave("保存资源")).RequiredPermissionCode("resource:add"), - sort := req.NewLogInfo("资源排序").WithSave(true) - db.POST("sort", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(sort). - Handle(r.Sort) - }) + req.NewPut(":id/:status", r.ChangeStatus).Log(req.NewLogSave("修改资源状态")).RequiredPermissionCode("resource:changeStatus"), - delResource := req.NewLogInfo("删除资源").WithSave(true) - dePermission := req.NewPermission("resource:delete") - db.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(delResource). - WithRequiredPermission(dePermission). - Handle(r.DelResource) - }) + req.NewPost("sort", r.Sort).Log(req.NewLogSave("资源排序")), + + req.NewDelete(":id", r.DelResource).Log(req.NewLogSave("删除资源")).RequiredPermissionCode("resource:delete"), } + + req.BatchSetGroup(rg, reqs[:]) } diff --git a/server/internal/sys/router/role.go b/server/internal/sys/router/role.go index 267f46d6..5b624135 100644 --- a/server/internal/sys/router/role.go +++ b/server/internal/sys/router/role.go @@ -13,43 +13,21 @@ func InitRoleRouter(router *gin.RouterGroup) { RoleApp: application.GetRoleApp(), ResourceApp: application.GetResourceApp(), } - db := router.Group("sys/roles") - { + rg := router.Group("sys/roles") - db.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(r.Roles) - }) + reqs := [...]*req.Conf{ + req.NewGet("", r.Roles), - saveRole := req.NewLogInfo("保存角色").WithSave(true) - sPermission := req.NewPermission("role:add") - db.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveRole). - WithRequiredPermission(sPermission). - Handle(r.SaveRole) - }) + req.NewPost("", r.SaveRole).Log(req.NewLogSave("保存角色")).RequiredPermissionCode("role:add"), - delRole := req.NewLogInfo("删除角色").WithSave(true) - drPermission := req.NewPermission("role:del") - db.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(delRole). - WithRequiredPermission(drPermission). - Handle(r.DelRole) - }) + req.NewDelete(":id", r.DelRole).Log(req.NewLogSave("删除角色")).RequiredPermissionCode("role:del"), - db.GET(":id/resourceIds", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(r.RoleResourceIds) - }) + req.NewGet(":id/resourceIds", r.RoleResourceIds), - db.GET(":id/resources", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(r.RoleResource) - }) + req.NewGet(":id/resources", r.RoleResource), - saveResource := req.NewLogInfo("保存角色资源").WithSave(true) - srPermission := req.NewPermission("role:saveResources") - db.POST(":id/resources", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveResource). - WithRequiredPermission(srPermission). - Handle(r.SaveResource) - }) + req.NewPost(":id/resources", r.SaveResource).Log(req.NewLogSave("保存角色资源")).RequiredPermissionCode("role:saveResources"), } + + req.BatchSetGroup(rg, reqs[:]) } diff --git a/server/internal/sys/router/syslog.go b/server/internal/sys/router/syslog.go index aa8a05bc..4c3bd543 100644 --- a/server/internal/sys/router/syslog.go +++ b/server/internal/sys/router/syslog.go @@ -12,10 +12,7 @@ func InitSyslogRouter(router *gin.RouterGroup) { s := &api.Syslog{ SyslogApp: application.GetSyslogApp(), } - sys := router.Group("syslogs") - { - sys.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(s.Syslogs) - }) - } + sysG := router.Group("syslogs") + + req.NewGet("", s.Syslogs).Group(sysG) } diff --git a/server/internal/tag/application/tag_tree.go b/server/internal/tag/application/tag_tree.go index ef88bf83..b50a8f96 100644 --- a/server/internal/tag/application/tag_tree.go +++ b/server/internal/tag/application/tag_tree.go @@ -140,10 +140,11 @@ func (p *tagTreeAppImpl) CanAccess(accountId uint64, tagPath string) error { } func (p *tagTreeAppImpl) Delete(id uint64) { - biz.IsTrue(p.machineApp.Count(&machineentity.MachineQuery{TagId: id}) == 0, "请先删除该项目关联的机器信息") - biz.IsTrue(p.redisApp.Count(&redisentity.RedisQuery{TagId: id}) == 0, "请先删除该项目关联的redis信息") - biz.IsTrue(p.dbApp.Count(&dbentity.DbQuery{TagId: id}) == 0, "请先删除该项目关联的数据库信息") - biz.IsTrue(p.mongoApp.Count(&mongoentity.MongoQuery{TagId: id}) == 0, "请先删除该项目关联的Mongo信息") + tagIds := [1]uint64{id} + biz.IsTrue(p.machineApp.Count(&machineentity.MachineQuery{TagIds: tagIds[:]}) == 0, "请先删除该项目关联的机器信息") + biz.IsTrue(p.redisApp.Count(&redisentity.RedisQuery{TagIds: tagIds[:]}) == 0, "请先删除该项目关联的redis信息") + biz.IsTrue(p.dbApp.Count(&dbentity.DbQuery{TagIds: tagIds[:]}) == 0, "请先删除该项目关联的数据库信息") + biz.IsTrue(p.mongoApp.Count(&mongoentity.MongoQuery{TagIds: tagIds[:]}) == 0, "请先删除该项目关联的Mongo信息") p.tagTreeRepo.Delete(id) // 删除该标签关联的团队信息 p.tagTreeTeamRepo.DeleteBy(&entity.TagTreeTeam{TagId: id}) diff --git a/server/internal/tag/router/tag_tree.go b/server/internal/tag/router/tag_tree.go index cae62ccb..78f7a59a 100644 --- a/server/internal/tag/router/tag_tree.go +++ b/server/internal/tag/router/tag_tree.go @@ -15,37 +15,21 @@ func InitTagTreeRouter(router *gin.RouterGroup) { tagTree := router.Group("/tag-trees") { - // 获取标签树列表 - tagTree.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.GetTagTree) - }) + reqs := [...]*req.Conf{ + // 获取标签树列表 + req.NewGet("", m.GetTagTree), - // 根据条件获取标签 - tagTree.GET("query", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.ListByQuery) - }) + // 根据条件获取标签 + req.NewGet("query", m.ListByQuery), - // 获取登录账号拥有的标签信息 - tagTree.GET("account-has", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.GetAccountTags) - }) + // 获取登录账号拥有的标签信息 + req.NewGet("account-has", m.GetAccountTags), - saveTagTreeLog := req.NewLogInfo("标签树-保存信息").WithSave(true) - savePP := req.NewPermission("tag:save") - // 保存项目树下的环境信息 - tagTree.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveTagTreeLog). - WithRequiredPermission(savePP). - Handle(m.SaveTagTree) - }) + req.NewPost("", m.SaveTagTree).Log(req.NewLogSave("标签树-保存信息")).RequiredPermissionCode("tag:save"), - delTagLog := req.NewLogInfo("标签树-删除信息").WithSave(true) - delPP := req.NewPermission("tag:del") - // 删除标签 - tagTree.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(delTagLog). - WithRequiredPermission(delPP). - Handle(m.DelTagTree) - }) + req.NewDelete(":id", m.DelTagTree).Log(req.NewLogSave("标签树-删除信息")).RequiredPermissionCode("tag:del"), + } + + req.BatchSetGroup(tagTree, reqs[:]) } } diff --git a/server/internal/tag/router/team.go b/server/internal/tag/router/team.go index bdd5c871..cdc27e14 100644 --- a/server/internal/tag/router/team.go +++ b/server/internal/tag/router/team.go @@ -18,64 +18,27 @@ func InitTeamRouter(router *gin.RouterGroup) { team := router.Group("/teams") { - // 获取团队列表 - team.GET("", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.GetTeams) - }) + reqs := [...]*req.Conf{ + // 获取团队列表 + req.NewGet("", m.GetTeams), - saveTeamLog := req.NewLogInfo("团队-保存信息").WithSave(true) - savePP := req.NewPermission("team:save") - // 保存项目团队信息 - team.POST("", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveTeamLog). - WithRequiredPermission(savePP). - Handle(m.SaveTeam) - }) + req.NewPost("", m.SaveTeam).Log(req.NewLogSave("团队-保存信息")).RequiredPermissionCode("team:save"), - delTeamLog := req.NewLogInfo("团队-删除信息").WithSave(true) - delPP := req.NewPermission("team:del") - team.DELETE(":id", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(delTeamLog). - WithRequiredPermission(delPP). - Handle(m.DelTeam) - }) + req.NewDelete(":id", m.DelTeam).Log(req.NewLogSave("团队-删除信息")).RequiredPermissionCode("team:del"), - // 获取团队的成员信息列表 - team.GET("/:id/members", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.GetTeamMembers) - }) + // 获取团队的成员信息列表 + req.NewGet("/:id/members", m.GetTeamMembers), - // 保存团队成员 - saveTeamMemLog := req.NewLogInfo("团队-新增成员").WithSave(true) - savePmP := req.NewPermission("team:member:save") - team.POST("/:id/members", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(saveTeamMemLog). - WithRequiredPermission(savePmP). - Handle(m.SaveTeamMember) - }) + req.NewPost("/:id/members", m.SaveTeamMember).Log(req.NewLogSave("团队-新增成员")).RequiredPermissionCode("team:member:save"), - // 删除团队成员 - delTeamMemLog := req.NewLogInfo("团队-删除成员").WithSave(true) - savePmdP := req.NewPermission("team:member:del") - team.DELETE("/:id/members/:accountId", func(c *gin.Context) { - req.NewCtxWithGin(c).WithLog(delTeamMemLog). - WithRequiredPermission(savePmdP). - Handle(m.DelTeamMember) - }) + req.NewDelete("/:id/members/:accountId", m.DelTeamMember).Log(req.NewLogSave("团队-删除成员")).RequiredPermissionCode("team:member:del"), - // 获取团队关联的标签id列表 - team.GET("/:id/tags", func(c *gin.Context) { - req.NewCtxWithGin(c).Handle(m.GetTagIds) - }) + // 获取团队关联的标签id列表 + req.NewGet("/:id/tags", m.GetTagIds), - // 保存团队标签关联信息 - saveTeamTagLog := req.NewLogInfo("团队-保存标签关联信息").WithSave(true) - saveTeamTagP := req.NewPermission("team:tag:save") - team.POST("/:id/tags", func(c *gin.Context) { - req.NewCtxWithGin(c). - WithLog(saveTeamTagLog). - WithRequiredPermission(saveTeamTagP). - Handle(m.SaveTags) - }) + req.NewPost("/:id/tags", m.SaveTags).Log(req.NewLogSave("团队-保存标签关联信息")).RequiredPermissionCode("team:tag:save"), + } + + req.BatchSetGroup(team, reqs[:]) } } diff --git a/server/pkg/ginx/ginx.go b/server/pkg/ginx/ginx.go index 92f76483..8ccb67f8 100644 --- a/server/pkg/ginx/ginx.go +++ b/server/pkg/ginx/ginx.go @@ -5,6 +5,7 @@ import ( "mayfly-go/pkg/biz" "mayfly-go/pkg/global" "mayfly-go/pkg/model" + "mayfly-go/pkg/utils" "net/http" "runtime/debug" "strconv" @@ -13,16 +14,36 @@ import ( ) // 绑定并校验请求结构体参数 -func BindJsonAndValid(g *gin.Context, data any) { +func BindJsonAndValid[T any](g *gin.Context, data T) T { if err := g.ShouldBindJSON(data); err != nil { panic(biz.NewBizErr(err.Error())) + } else { + return data } } -// 绑定查询字符串到 -func BindQuery(g *gin.Context, data any) { - if err := g.ShouldBindQuery(data); err != nil { +// 绑定请求体中的json至form结构体,并拷贝至另一结构体 +func BindJsonAndCopyTo[T any](g *gin.Context, form any, toStruct T) T { + BindJsonAndValid(g, form) + utils.Copy(toStruct, form) + return toStruct +} + +// 绑定查询字符串到指定结构体 +func BindQuery[T any](g *gin.Context, data T) T { + if err := g.BindQuery(data); err != nil { panic(biz.NewBizErr(err.Error())) + } else { + return data + } +} + +// 绑定查询字符串到指定结构体,并将分页信息也返回 +func BindQueryAndPage[T any](g *gin.Context, data T) (T, *model.PageParam) { + if err := g.BindQuery(data); err != nil { + panic(biz.NewBizErr(err.Error())) + } else { + return data, GetPageParam(g) } } diff --git a/server/pkg/req/conf.go b/server/pkg/req/conf.go new file mode 100644 index 00000000..e9021b1d --- /dev/null +++ b/server/pkg/req/conf.go @@ -0,0 +1,85 @@ +package req + +import ( + "github.com/gin-gonic/gin" +) + +// 请求配置,如是否需要权限,日志信息等配置 +type Conf struct { + method string + path string + handler HandlerFunc // 请求处理函数 + + requiredPermission *Permission // 需要的权限信息,默认为nil,需要校验token + logInfo *LogInfo // 日志相关信息 + noRes bool // 无需返回结果,即文件下载等 +} + +func New(method, path string, handler HandlerFunc) *Conf { + return &Conf{method: method, path: path, handler: handler, noRes: false} +} + +func NewPost(path string, handler HandlerFunc) *Conf { + return New("POST", path, handler) +} + +func NewGet(path string, handler HandlerFunc) *Conf { + return New("GET", path, handler) +} + +func NewPut(path string, handler HandlerFunc) *Conf { + return New("PUT", path, handler) +} + +func NewDelete(path string, handler HandlerFunc) *Conf { + return New("DELETE", path, handler) +} + +func (r *Conf) ToGinHFunc() gin.HandlerFunc { + return func(c *gin.Context) { + NewCtxWithGin(c).WithConf(r).Handle(r.handler) + } +} + +// 调用该方法设置请求描述,则默认记录日志,并不记录响应结果 +func (r *Conf) Log(li *LogInfo) *Conf { + r.logInfo = li + return r +} + +// 设置请求上下文需要的权限信息 +func (r *Conf) RequiredPermission(permission *Permission) *Conf { + r.requiredPermission = permission + return r +} + +// 设置请求上下文需要的权限信息 +func (r *Conf) RequiredPermissionCode(code string) *Conf { + r.RequiredPermission(NewPermission(code)) + return r +} + +// 不需要token校验 +func (r *Conf) DontNeedToken() *Conf { + r.requiredPermission = &Permission{NeedToken: false} + return r +} + +// 没有响应结果,即文件下载等 +func (r *Conf) NoRes() *Conf { + r.noRes = true + return r +} + +// 注册至group +func (r *Conf) Group(gr *gin.RouterGroup) *Conf { + gr.Handle(r.method, r.path, r.ToGinHFunc()) + return r +} + +// 批量注册至group +func BatchSetGroup(gr *gin.RouterGroup, reqs []*Conf) { + for _, req := range reqs { + req.Group(gr) + } +} diff --git a/server/pkg/req/log_handler.go b/server/pkg/req/log_handler.go index 0ce39284..bc78f6a3 100644 --- a/server/pkg/req/log_handler.go +++ b/server/pkg/req/log_handler.go @@ -19,34 +19,35 @@ func SetSaveLogFunc(sl SaveLogFunc) { } type LogInfo struct { - LogResp bool // 是否记录返回结果 Description string // 请求描述 - Save bool // 是否保存日志 + + LogResp bool // 是否记录返回结果 + save bool // 是否保存日志 } -// 新建日志信息 -func NewLogInfo(description string) *LogInfo { - return &LogInfo{Description: description, LogResp: false} +// 新建日志信息,默认不保存该日志 +func NewLog(description string) *LogInfo { + return &LogInfo{Description: description, LogResp: false, save: false} } -// 是否记录返回结果 -func (i *LogInfo) WithLogResp(logResp bool) *LogInfo { - i.LogResp = logResp - return i +// 新建日志信息,并且需要保存该日志信息 +func NewLogSave(description string) *LogInfo { + return &LogInfo{Description: description, LogResp: false, save: true} } -// 是否保存日志 -func (i *LogInfo) WithSave(saveLog bool) *LogInfo { - i.Save = saveLog +// 记录返回结果 +func (i *LogInfo) WithLogResp() *LogInfo { + i.LogResp = true return i } func LogHandler(rc *Ctx) error { - li := rc.LogInfo - if li == nil { + if rc.Conf == nil || rc.Conf.logInfo == nil { return nil } + li := rc.Conf.logInfo + lfs := logrus.Fields{} if la := rc.LoginAccount; la != nil { lfs["uid"] = la.Id @@ -57,7 +58,7 @@ func LogHandler(rc *Ctx) error { lfs[req.Method] = req.URL.Path // 如果需要保存日志,并且保存日志处理函数存在则执行保存日志函数 - if li.Save && saveLog != nil { + if li.save && saveLog != nil { go saveLog(rc) } if err := rc.Err; err != nil { @@ -69,20 +70,21 @@ func LogHandler(rc *Ctx) error { } func getLogMsg(rc *Ctx) string { - msg := rc.LogInfo.Description + fmt.Sprintf(" ->%dms", rc.timed) + logInfo := rc.Conf.logInfo + msg := logInfo.Description + fmt.Sprintf(" ->%dms", rc.timed) if !utils.IsBlank(rc.ReqParam) { msg = msg + fmt.Sprintf("\n--> %s", utils.ToString(rc.ReqParam)) } // 返回结果不为空,则记录返回结果 - if rc.LogInfo.LogResp && !utils.IsBlank(rc.ResData) { + if logInfo.LogResp && !utils.IsBlank(rc.ResData) { msg = msg + fmt.Sprintf("\n<-- %s", utils.ToString(rc.ResData)) } return msg } func getErrMsg(rc *Ctx, err any) string { - msg := rc.LogInfo.Description + msg := rc.Conf.logInfo.Description if !utils.IsBlank(rc.ReqParam) { msg = msg + fmt.Sprintf("\n--> %s", utils.ToString(rc.ReqParam)) } diff --git a/server/pkg/req/permission_handler.go b/server/pkg/req/permission_handler.go index 998595b9..7e30bbc1 100644 --- a/server/pkg/req/permission_handler.go +++ b/server/pkg/req/permission_handler.go @@ -33,7 +33,10 @@ func PermissionHandler(rc *Ctx) error { } } - permission := rc.RequiredPermission + var permission *Permission + if rc.Conf != nil { + permission = rc.Conf.requiredPermission + } // 如果需要的权限信息不为空,并且不需要token,则不返回错误,继续后续逻辑 if permission != nil && !permission.NeedToken { return nil diff --git a/server/pkg/req/req_ctx.go b/server/pkg/req/req_ctx.go index 9c94a0d0..e5c23f30 100644 --- a/server/pkg/req/req_ctx.go +++ b/server/pkg/req/req_ctx.go @@ -14,18 +14,14 @@ import ( type HandlerFunc func(*Ctx) type Ctx struct { - GinCtx *gin.Context // gin context + Conf *Conf // 请求配置 - RequiredPermission *Permission // 需要的权限信息,默认为nil,需要校验token - LoginAccount *model.LoginAccount // 登录账号信息,只有校验token后才会有值 - - LogInfo *LogInfo // 日志相关信息 - ReqParam any // 请求参数,主要用于记录日志 - ResData any // 响应结果 - Err any // 请求错误 - - timed int64 // 执行时间 - NoRes bool // 无需返回结果,即文件下载等 + GinCtx *gin.Context // gin context + LoginAccount *model.LoginAccount // 登录账号信息,只有校验token后才会有值 + ReqParam any // 请求参数,主要用于记录日志 + ResData any // 响应结果 + Err any // 请求错误 + timed int64 // 执行时间 } func (rc *Ctx) Handle(handler HandlerFunc) { @@ -54,38 +50,46 @@ func (rc *Ctx) Handle(handler HandlerFunc) { begin := time.Now() handler(rc) rc.timed = time.Since(begin).Milliseconds() - if !rc.NoRes { + if rc.Conf == nil || !rc.Conf.noRes { ginx.SuccessRes(ginCtx, rc.ResData) } } func (rc *Ctx) Download(reader io.Reader, filename string) { - rc.NoRes = true ginx.Download(rc.GinCtx, reader, filename) } +func (rc *Ctx) WithConf(conf *Conf) *Ctx { + rc.Conf = conf + return rc +} + +// 设置请求上下文需要的权限信息 +func (rc *Ctx) WithRequiredPermission(permission *Permission) *Ctx { + if rc.Conf == nil { + rc.Conf = new(Conf) + } + rc.Conf.requiredPermission = permission + return rc +} + +// 设置请求日志信息 +func (rc *Ctx) WithLog(logInfo *LogInfo) *Ctx { + if rc.Conf == nil { + rc.Conf = new(Conf) + } + rc.Conf.logInfo = logInfo + return rc +} + +func (rc *Ctx) GetLogInfo() *LogInfo { + return rc.Conf.logInfo +} + func NewCtxWithGin(g *gin.Context) *Ctx { return &Ctx{GinCtx: g} } -// 调用该方法设置请求描述,则默认记录日志,并不记录响应结果 -func (r *Ctx) WithLog(li *LogInfo) *Ctx { - r.LogInfo = li - return r -} - -// 设置请求上下文需要的权限信息 -func (r *Ctx) WithRequiredPermission(permission *Permission) *Ctx { - r.RequiredPermission = permission - return r -} - -// 不需要token校验 -func (r *Ctx) DontNeedToken() *Ctx { - r.RequiredPermission = &Permission{NeedToken: false} - return r -} - // 处理器拦截器函数 type HandlerInterceptorFunc func(*Ctx) error type HandlerInterceptors []HandlerInterceptorFunc