refactor: 简化api层相关调用

This commit is contained in:
meilin.huang
2024-02-25 12:46:18 +08:00
parent b56b0187cf
commit bf75483a3c
32 changed files with 212 additions and 201 deletions

View File

@@ -35,7 +35,7 @@ body,
width: 100%;
height: 100%;
font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
font-weight: 450;
font-weight: 500;
-webkit-font-smoothing: antialiased;
-webkit-tap-highlight-color: transparent;
background-color: var(--bg-main-color);

View File

@@ -97,7 +97,7 @@ func useOtp(account *sysentity.Account, otpIssuer, accessToken string) (*OtpVeri
// 获取ip与归属地信息
func getIpAndRegion(rc *req.Ctx) string {
clientIp := rc.F.ClientIP()
clientIp := rc.ClientIP()
return fmt.Sprintf("%s %s", clientIp, netx.Ip2Region(clientIp))
}

View File

@@ -37,7 +37,7 @@ func (a *Oauth2Login) OAuth2Login(rc *req.Ctx) {
client, _ := a.getOAuthClient()
state := stringx.Rand(32)
cache.SetStr("oauth2:state:"+state, "login", 5*time.Minute)
rc.F.Redirect(http.StatusFound, client.AuthCodeURL(state))
rc.Redirect(http.StatusFound, client.AuthCodeURL(state))
}
func (a *Oauth2Login) OAuth2Bind(rc *req.Ctx) {
@@ -45,16 +45,16 @@ func (a *Oauth2Login) OAuth2Bind(rc *req.Ctx) {
state := stringx.Rand(32)
cache.SetStr("oauth2:state:"+state, "bind:"+strconv.FormatUint(rc.GetLoginAccount().Id, 10),
5*time.Minute)
rc.F.Redirect(http.StatusFound, client.AuthCodeURL(state))
rc.Redirect(http.StatusFound, client.AuthCodeURL(state))
}
func (a *Oauth2Login) OAuth2Callback(rc *req.Ctx) {
client, oauth := a.getOAuthClient()
code := rc.F.Query("code")
code := rc.Query("code")
biz.NotEmpty(code, "code不能为空")
state := rc.F.Query("state")
state := rc.Query("state")
biz.NotEmpty(state, "state不能为空")
stateAction := cache.GetStr("oauth2:state:" + state)
@@ -64,7 +64,7 @@ func (a *Oauth2Login) OAuth2Callback(rc *req.Ctx) {
biz.ErrIsNilAppendErr(err, "获取OAuth2 accessToken失败: %s")
// 获取用户信息
httpCli := client.Client(rc.F.GetRequest().Context(), token)
httpCli := client.Client(rc.GetRequest().Context(), token)
resp, err := httpCli.Get(oauth.ResourceURL)
biz.ErrIsNilAppendErr(err, "获取用户信息失败: %s")
defer resp.Body.Close()

View File

@@ -64,7 +64,7 @@ func (d *Db) Save(rc *req.Ctx) {
}
func (d *Db) DeleteDb(rc *req.Ctx) {
idsStr := rc.F.PathParam("dbId")
idsStr := rc.PathParam("dbId")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -150,7 +150,7 @@ type progressMsg struct {
// 执行sql文件
func (d *Db) ExecSqlFile(rc *req.Ctx) {
multipart, err := rc.F.GetRequest().MultipartReader()
multipart, err := rc.GetRequest().MultipartReader()
biz.ErrIsNilAppendErr(err, "读取sql文件失败: %s")
file, err := multipart.NextPart()
biz.ErrIsNilAppendErr(err, "读取sql文件失败: %s")
@@ -158,7 +158,7 @@ func (d *Db) ExecSqlFile(rc *req.Ctx) {
filename := file.FileName()
dbId := getDbId(rc)
dbName := getDbName(rc)
clientId := rc.F.Query("clientId")
clientId := rc.Query("clientId")
dbConn, err := d.DbApp.GetDbConn(dbId, dbName)
biz.ErrIsNil(err)
@@ -250,10 +250,10 @@ func (d *Db) ExecSqlFile(rc *req.Ctx) {
// 数据库dump
func (d *Db) DumpSql(rc *req.Ctx) {
dbId := getDbId(rc)
dbNamesStr := rc.F.Query("db")
dumpType := rc.F.Query("type")
tablesStr := rc.F.Query("tables")
extName := rc.F.Query("extName")
dbNamesStr := rc.Query("db")
dumpType := rc.Query("type")
tablesStr := rc.Query("tables")
extName := rc.Query("extName")
switch extName {
case ".gz", ".gzip", "gz", "gzip":
extName = ".gz"
@@ -273,10 +273,10 @@ func (d *Db) DumpSql(rc *req.Ctx) {
now := time.Now()
filename := fmt.Sprintf("%s.%s.sql%s", db.Name, now.Format("20060102150405"), extName)
rc.F.Header("Content-Type", "application/octet-stream")
rc.F.Header("Content-Disposition", "attachment; filename="+filename)
rc.Header("Content-Type", "application/octet-stream")
rc.Header("Content-Disposition", "attachment; filename="+filename)
if extName != ".gz" {
rc.F.Header("Content-Encoding", "gzip")
rc.Header("Content-Encoding", "gzip")
}
var dbNames, tables []string
@@ -287,7 +287,7 @@ func (d *Db) DumpSql(rc *req.Ctx) {
tables = strings.Split(tablesStr, ",")
}
writer := newGzipWriter(rc.F.GetWriter())
writer := newGzipWriter(rc.GetWriter())
defer func() {
msg := anyx.ToString(recover())
if len(msg) > 0 {
@@ -379,7 +379,7 @@ func (d *Db) TableInfos(rc *req.Ctx) {
}
func (d *Db) TableIndex(rc *req.Ctx) {
tn := rc.F.Query("tableName")
tn := rc.Query("tableName")
biz.NotEmpty(tn, "tableName不能为空")
res, err := d.getDbConn(rc).GetDialect().GetTableIndex(tn)
biz.ErrIsNilAppendErr(err, "获取表索引信息失败: %s")
@@ -388,7 +388,7 @@ func (d *Db) TableIndex(rc *req.Ctx) {
// @router /api/db/:dbId/c-metadata [get]
func (d *Db) ColumnMA(rc *req.Ctx) {
tn := rc.F.Query("tableName")
tn := rc.Query("tableName")
biz.NotEmpty(tn, "tableName不能为空")
dbi := d.getDbConn(rc)
@@ -440,7 +440,7 @@ func (d *Db) HintTables(rc *req.Ctx) {
}
func (d *Db) GetTableDDL(rc *req.Ctx) {
tn := rc.F.Query("tableName")
tn := rc.Query("tableName")
biz.NotEmpty(tn, "tableName不能为空")
res, err := d.getDbConn(rc).GetDialect().GetTableDDL(tn)
biz.ErrIsNilAppendErr(err, "获取表ddl失败: %s")
@@ -468,13 +468,13 @@ func (d *Db) CopyTable(rc *req.Ctx) {
}
func getDbId(rc *req.Ctx) uint64 {
dbId := rc.F.PathParamInt("dbId")
dbId := rc.PathParamInt("dbId")
biz.IsTrue(dbId > 0, "dbId错误")
return uint64(dbId)
}
func getDbName(rc *req.Ctx) string {
db := rc.F.Query("db")
db := rc.Query("db")
biz.NotEmpty(db, "db不能为空")
return db
}

View File

@@ -25,7 +25,7 @@ type DbBackup struct {
// GetPageList 获取数据库备份任务
// @router /api/dbs/:dbId/backups [GET]
func (d *DbBackup) GetPageList(rc *req.Ctx) {
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
biz.IsTrue(dbId > 0, "无效的 dbId: %v", dbId)
db, err := d.dbApp.GetById(new(entity.Db), dbId, "db_instance_id", "database")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
@@ -47,7 +47,7 @@ func (d *DbBackup) Create(rc *req.Ctx) {
dbNames := strings.Fields(backupForm.DbNames)
biz.IsTrue(len(dbNames) > 0, "解析数据库备份任务失败:数据库名称未定义")
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
biz.IsTrue(dbId > 0, "无效的 dbId: %v", dbId)
db, err := d.dbApp.GetById(new(entity.Db), dbId, "instanceId")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
@@ -84,7 +84,7 @@ func (d *DbBackup) Update(rc *req.Ctx) {
}
func (d *DbBackup) walk(rc *req.Ctx, paramName string, fn func(ctx context.Context, id uint64) error) error {
idsStr := rc.F.PathParam(paramName)
idsStr := rc.PathParam(paramName)
biz.NotEmpty(idsStr, paramName+" 为空")
rc.ReqParam = idsStr
ids := strings.Fields(idsStr)
@@ -133,7 +133,7 @@ func (d *DbBackup) Start(rc *req.Ctx) {
// GetDbNamesWithoutBackup 获取未配置定时备份的数据库名称
// @router /api/dbs/:dbId/db-names-without-backup [GET]
func (d *DbBackup) GetDbNamesWithoutBackup(rc *req.Ctx) {
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
db, err := d.dbApp.GetById(new(entity.Db), dbId, "instance_id", "database")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
dbNames := strings.Fields(db.Database)
@@ -145,7 +145,7 @@ func (d *DbBackup) GetDbNamesWithoutBackup(rc *req.Ctx) {
// GetHistoryPageList 获取数据库备份历史
// @router /api/dbs/:dbId/backups/:backupId/histories [GET]
func (d *DbBackup) GetHistoryPageList(rc *req.Ctx) {
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
biz.IsTrue(dbId > 0, "无效的 dbId: %v", dbId)
db, err := d.dbApp.GetById(new(entity.Db), dbId, "db_instance_id", "database")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
@@ -180,7 +180,7 @@ func (d *DbBackup) GetHistoryPageList(rc *req.Ctx) {
// RestoreHistories 从数据库备份历史中恢复数据库
// @router /api/dbs/:dbId/backup-histories/:backupHistoryId/restore [POST]
func (d *DbBackup) RestoreHistories(rc *req.Ctx) {
pm := rc.F.PathParam("backupHistoryId")
pm := rc.PathParam("backupHistoryId")
biz.NotEmpty(pm, "backupHistoryId 为空")
idsStr := strings.Fields(pm)
ids := make([]uint64, 0, len(idsStr))

View File

@@ -47,7 +47,7 @@ func (d *DataSyncTask) SaveTask(rc *req.Ctx) {
}
func (d *DataSyncTask) DeleteTask(rc *req.Ctx) {
taskId := rc.F.PathParam("taskId")
taskId := rc.PathParam("taskId")
rc.ReqParam = taskId
ids := strings.Split(taskId, ",")
@@ -97,7 +97,7 @@ func (d *DataSyncTask) GetTask(rc *req.Ctx) {
}
func getTaskId(rc *req.Ctx) uint64 {
instanceId := rc.F.PathParamInt("taskId")
instanceId := rc.PathParamInt("taskId")
biz.IsTrue(instanceId > 0, "instanceId 错误")
return uint64(instanceId)
}

View File

@@ -78,7 +78,7 @@ func (d *Instance) GetInstancePwd(rc *req.Ctx) {
// DeleteInstance 删除数据库实例信息
// @router /api/instances/:instance [DELETE]
func (d *Instance) DeleteInstance(rc *req.Ctx) {
idsStr := rc.F.PathParam("instanceId")
idsStr := rc.PathParam("instanceId")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -113,7 +113,7 @@ func (d *Instance) GetDbServer(rc *req.Ctx) {
}
func getInstanceId(rc *req.Ctx) uint64 {
instanceId := rc.F.PathParamInt("instanceId")
instanceId := rc.PathParamInt("instanceId")
biz.IsTrue(instanceId > 0, "instanceId 错误")
return uint64(instanceId)
}

View File

@@ -20,7 +20,7 @@ type DbRestore struct {
// GetPageList 获取数据库恢复任务
// @router /api/dbs/:dbId/restores [GET]
func (d *DbRestore) GetPageList(rc *req.Ctx) {
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
biz.IsTrue(dbId > 0, "无效的 dbId: %v", dbId)
db, err := d.dbApp.GetById(new(entity.Db), dbId, "db_instance_id", "database")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
@@ -41,7 +41,7 @@ func (d *DbRestore) Create(rc *req.Ctx) {
req.BindJsonAndValid(rc, restoreForm)
rc.ReqParam = restoreForm
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
biz.IsTrue(dbId > 0, "无效的 dbId: %v", dbId)
db, err := d.dbApp.GetById(new(entity.Db), dbId, "instanceId")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
@@ -80,7 +80,7 @@ func (d *DbRestore) Update(rc *req.Ctx) {
}
func (d *DbRestore) walk(rc *req.Ctx, fn func(ctx context.Context, restoreId uint64) error) error {
idsStr := rc.F.PathParam("restoreId")
idsStr := rc.PathParam("restoreId")
biz.NotEmpty(idsStr, "restoreId 为空")
rc.ReqParam = idsStr
ids := strings.Fields(idsStr)
@@ -122,7 +122,7 @@ func (d *DbRestore) Disable(rc *req.Ctx) {
// GetDbNamesWithoutRestore 获取未配置定时恢复的数据库名称
// @router /api/dbs/:dbId/db-names-without-backup [GET]
func (d *DbRestore) GetDbNamesWithoutRestore(rc *req.Ctx) {
dbId := uint64(rc.F.PathParamInt("dbId"))
dbId := uint64(rc.PathParamInt("dbId"))
db, err := d.dbApp.GetById(new(entity.Db), dbId, "instance_id", "database")
biz.ErrIsNilAppendErr(err, "获取数据库信息失败: %v")
dbNames := strings.Fields(db.Database)
@@ -135,9 +135,9 @@ func (d *DbRestore) GetDbNamesWithoutRestore(rc *req.Ctx) {
// @router /api/dbs/:dbId/restores/:restoreId/histories [GET]
func (d *DbRestore) GetHistoryPageList(rc *req.Ctx) {
queryCond := &entity.DbRestoreHistoryQuery{
DbRestoreId: uint64(rc.F.PathParamInt("restoreId")),
DbRestoreId: uint64(rc.PathParamInt("restoreId")),
}
res, err := d.restoreApp.GetHistoryPageList(queryCond, rc.F.GetPageParam(), new([]vo.DbRestoreHistory))
res, err := d.restoreApp.GetHistoryPageList(queryCond, rc.GetPageParam(), new([]vo.DbRestoreHistory))
biz.ErrIsNilAppendErr(err, "获取数据库备份历史失败: %v")
rc.ResData = res
}

View File

@@ -52,8 +52,8 @@ func (d *DbSql) GetSqlNames(rc *req.Ctx) {
func (d *DbSql) DeleteSql(rc *req.Ctx) {
dbSql := &entity.DbSql{Type: 1, DbId: getDbId(rc)}
dbSql.CreatorId = rc.GetLoginAccount().Id
dbSql.Name = rc.F.Query("name")
dbSql.Db = rc.F.Query("db")
dbSql.Name = rc.Query("name")
dbSql.Db = rc.Query("db")
biz.ErrIsNil(d.DbSqlApp.DeleteByCond(rc.MetaCtx, dbSql))
}
@@ -65,7 +65,7 @@ func (d *DbSql) GetSql(rc *req.Ctx) {
// 根据创建者id 数据库id以及sql模板名称查询保存的sql信息
dbSql := &entity.DbSql{Type: 1, DbId: dbId, Db: dbName}
dbSql.CreatorId = rc.GetLoginAccount().Id
dbSql.Name = rc.F.Query("name")
dbSql.Name = rc.Query("name")
e := d.DbSqlApp.GetBy(dbSql)
if e != nil {

View File

@@ -47,7 +47,7 @@ func (c *AuthCert) SaveAuthCert(rc *req.Ctx) {
}
func (c *AuthCert) Delete(rc *req.Ctx) {
idsStr := rc.F.PathParam("id")
idsStr := rc.PathParam("id")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")

View File

@@ -87,14 +87,14 @@ func (m *Machine) TestConn(rc *req.Ctx) {
}
func (m *Machine) ChangeStatus(rc *req.Ctx) {
id := uint64(rc.F.PathParamInt("machineId"))
status := int8(rc.F.PathParamInt("status"))
id := uint64(rc.PathParamInt("machineId"))
status := int8(rc.PathParamInt("status"))
rc.ReqParam = collx.Kvs("id", id, "status", status)
biz.ErrIsNil(m.MachineApp.ChangeStatus(rc.MetaCtx, id, status))
}
func (m *Machine) DeleteMachine(rc *req.Ctx) {
idsStr := rc.F.PathParam("machineId")
idsStr := rc.PathParam("machineId")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -108,19 +108,19 @@ func (m *Machine) DeleteMachine(rc *req.Ctx) {
// 获取进程列表信息
func (m *Machine) GetProcess(rc *req.Ctx) {
cmd := "ps -aux "
sortType := rc.F.Query("sortType")
sortType := rc.Query("sortType")
if sortType == "2" {
cmd += "--sort -pmem "
} else {
cmd += "--sort -pcpu "
}
pname := rc.F.Query("name")
pname := rc.Query("name")
if pname != "" {
cmd += fmt.Sprintf("| grep %s ", pname)
}
count := rc.F.QueryIntDefault("count", 10)
count := rc.QueryIntDefault("count", 10)
cmd += "| head -n " + fmt.Sprintf("%d", count)
cli, err := m.MachineApp.GetCli(GetMachineId(rc))
@@ -134,7 +134,7 @@ func (m *Machine) GetProcess(rc *req.Ctx) {
// 终止进程
func (m *Machine) KillProcess(rc *req.Ctx) {
pid := rc.F.Query("pid")
pid := rc.Query("pid")
biz.NotEmpty(pid, "进程id不能为空")
cli, err := m.MachineApp.GetCli(GetMachineId(rc))
@@ -169,8 +169,8 @@ func (m *Machine) WsSSH(g *gin.Context) {
defer cli.Close()
biz.ErrIsNilAppendErr(m.TagApp.CanAccess(rc.GetLoginAccount().Id, cli.Info.TagPath...), "%s")
cols := rc.F.QueryIntDefault("cols", 80)
rows := rc.F.QueryIntDefault("rows", 32)
cols := rc.QueryIntDefault("cols", 80)
rows := rc.QueryIntDefault("rows", 32)
// 记录系统操作日志
rc.WithLog(req.NewLogSave("机器-终端操作"))
@@ -183,13 +183,13 @@ func (m *Machine) WsSSH(g *gin.Context) {
func (m *Machine) MachineTermOpRecords(rc *req.Ctx) {
mid := GetMachineId(rc)
res, err := m.MachineTermOpApp.GetPageList(&entity.MachineTermOp{MachineId: mid}, rc.F.GetPageParam(), new([]entity.MachineTermOp))
res, err := m.MachineTermOpApp.GetPageList(&entity.MachineTermOp{MachineId: mid}, rc.GetPageParam(), new([]entity.MachineTermOp))
biz.ErrIsNil(err)
rc.ResData = res
}
func (m *Machine) MachineTermOpRecord(rc *req.Ctx) {
termOp, err := m.MachineTermOpApp.GetById(new(entity.MachineTermOp), uint64(rc.F.PathParamInt("recId")))
termOp, err := m.MachineTermOpApp.GetById(new(entity.MachineTermOp), uint64(rc.PathParamInt("recId")))
biz.ErrIsNil(err)
bytes, err := os.ReadFile(path.Join(config.GetMachine().TerminalRecPath, termOp.RecordFilePath))
@@ -198,7 +198,7 @@ func (m *Machine) MachineTermOpRecord(rc *req.Ctx) {
}
func GetMachineId(rc *req.Ctx) uint64 {
machineId, _ := strconv.Atoi(rc.F.PathParam("machineId"))
machineId, _ := strconv.Atoi(rc.PathParam("machineId"))
biz.IsTrue(machineId != 0, "machineId错误")
return uint64(machineId)
}

View File

@@ -43,7 +43,7 @@ func (m *MachineCronJob) Save(rc *req.Ctx) {
}
func (m *MachineCronJob) Delete(rc *req.Ctx) {
idsStr := rc.F.PathParam("ids")
idsStr := rc.PathParam("ids")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -55,15 +55,15 @@ func (m *MachineCronJob) Delete(rc *req.Ctx) {
}
func (m *MachineCronJob) GetRelateMachineIds(rc *req.Ctx) {
rc.ResData = m.MachineCronJobApp.GetRelateMachineIds(uint64(rc.F.QueryIntDefault("cronJobId", -1)))
rc.ResData = m.MachineCronJobApp.GetRelateMachineIds(uint64(rc.QueryIntDefault("cronJobId", -1)))
}
func (m *MachineCronJob) GetRelateCronJobIds(rc *req.Ctx) {
rc.ResData = m.MachineCronJobApp.GetRelateMachineIds(uint64(rc.F.QueryIntDefault("machineId", -1)))
rc.ResData = m.MachineCronJobApp.GetRelateMachineIds(uint64(rc.QueryIntDefault("machineId", -1)))
}
func (m *MachineCronJob) RunCronJob(rc *req.Ctx) {
cronJobKey := rc.F.PathParam("key")
cronJobKey := rc.PathParam("key")
biz.NotEmpty(cronJobKey, "cronJob key不能为空")
m.MachineCronJobApp.RunCronJob(cronJobKey)
}

View File

@@ -40,7 +40,7 @@ const (
func (m *MachineFile) MachineFiles(rc *req.Ctx) {
condition := &entity.MachineFile{MachineId: GetMachineId(rc)}
res, err := m.MachineFileApp.GetPageList(condition, rc.F.GetPageParam(), new([]vo.MachineFileVO))
res, err := m.MachineFileApp.GetPageList(condition, rc.GetPageParam(), new([]vo.MachineFileVO))
biz.ErrIsNil(err)
rc.ResData = res
}
@@ -82,7 +82,7 @@ func (m *MachineFile) CreateFile(rc *req.Ctx) {
func (m *MachineFile) ReadFileContent(rc *req.Ctx) {
fid := GetMachineFileId(rc)
readPath := rc.F.Query("path")
readPath := rc.Query("path")
sftpFile, mi, err := m.MachineFileApp.ReadFile(fid, readPath)
rc.ReqParam = collx.Kvs("machine", mi, "path", readPath)
@@ -101,7 +101,7 @@ func (m *MachineFile) ReadFileContent(rc *req.Ctx) {
func (m *MachineFile) DownloadFile(rc *req.Ctx) {
fid := GetMachineFileId(rc)
readPath := rc.F.Query("path")
readPath := rc.Query("path")
sftpFile, mi, err := m.MachineFileApp.ReadFile(fid, readPath)
rc.ReqParam = collx.Kvs("machine", mi, "path", readPath)
@@ -110,12 +110,12 @@ func (m *MachineFile) DownloadFile(rc *req.Ctx) {
// 截取文件名,如/usr/local/test.java -》 test.java
path := strings.Split(readPath, "/")
rc.F.Download(sftpFile, path[len(path)-1])
rc.Download(sftpFile, path[len(path)-1])
}
func (m *MachineFile) GetDirEntry(rc *req.Ctx) {
fid := GetMachineFileId(rc)
readPath := rc.F.Query("path")
readPath := rc.Query("path")
rc.ReqParam = fmt.Sprintf("path: %s", readPath)
if !strings.HasSuffix(readPath, "/") {
@@ -142,7 +142,7 @@ func (m *MachineFile) GetDirEntry(rc *req.Ctx) {
func (m *MachineFile) GetDirSize(rc *req.Ctx) {
fid := GetMachineFileId(rc)
readPath := rc.F.Query("path")
readPath := rc.Query("path")
size, err := m.MachineFileApp.GetDirSize(fid, readPath)
biz.ErrIsNil(err)
@@ -151,7 +151,7 @@ func (m *MachineFile) GetDirSize(rc *req.Ctx) {
func (m *MachineFile) GetFileStat(rc *req.Ctx) {
fid := GetMachineFileId(rc)
readPath := rc.F.Query("path")
readPath := rc.Query("path")
res, err := m.MachineFileApp.FileStat(fid, readPath)
biz.ErrIsNil(err, res)
@@ -171,9 +171,9 @@ func (m *MachineFile) WriteFileContent(rc *req.Ctx) {
func (m *MachineFile) UploadFile(rc *req.Ctx) {
fid := GetMachineFileId(rc)
path := rc.F.PostForm("path")
path := rc.PostForm("path")
fileheader, err := rc.F.FormFile("file")
fileheader, err := rc.FormFile("file")
biz.ErrIsNilAppendErr(err, "读取文件失败: %s")
maxUploadFileSize := config.GetMachine().UploadMaxFileSize
@@ -205,7 +205,7 @@ type FolderFile struct {
func (m *MachineFile) UploadFolder(rc *req.Ctx) {
fid := GetMachineFileId(rc)
mf, err := rc.F.MultipartForm()
mf, err := rc.MultipartForm()
biz.ErrIsNilAppendErr(err, "获取表单信息失败: %s")
basePath := mf.Value["basePath"][0]
biz.NotEmpty(basePath, "基础路径不能为空")
@@ -342,7 +342,7 @@ func getFileType(fm fs.FileMode) string {
}
func GetMachineFileId(rc *req.Ctx) uint64 {
fileId := rc.F.PathParamInt("fileId")
fileId := rc.PathParamInt("fileId")
biz.IsTrue(fileId != 0, "fileId错误")
return uint64(fileId)
}

View File

@@ -23,7 +23,7 @@ type MachineScript struct {
func (m *MachineScript) MachineScripts(rc *req.Ctx) {
condition := &entity.MachineScript{MachineId: GetMachineId(rc)}
res, err := m.MachineScriptApp.GetPageList(condition, rc.F.GetPageParam(), new([]vo.MachineScriptVO))
res, err := m.MachineScriptApp.GetPageList(condition, rc.GetPageParam(), new([]vo.MachineScriptVO))
biz.ErrIsNil(err)
rc.ResData = res
}
@@ -37,7 +37,7 @@ func (m *MachineScript) SaveMachineScript(rc *req.Ctx) {
}
func (m *MachineScript) DeleteMachineScript(rc *req.Ctx) {
idsStr := rc.F.PathParam("scriptId")
idsStr := rc.PathParam("scriptId")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -57,7 +57,7 @@ func (m *MachineScript) RunMachineScript(rc *req.Ctx) {
script := ms.Script
// 如果有脚本参数,则用脚本参数替换脚本中的模板占位符参数
if params := rc.F.Query("params"); params != "" {
if params := rc.Query("params"); params != "" {
script, err = stringx.TemplateParse(ms.Script, jsonx.ToMap(params))
biz.ErrIsNilAppendErr(err, "脚本模板参数解析失败: %s")
}
@@ -75,7 +75,7 @@ func (m *MachineScript) RunMachineScript(rc *req.Ctx) {
}
func GetMachineScriptId(rc *req.Ctx) uint64 {
scriptId := rc.F.PathParamInt("scriptId")
scriptId := rc.PathParamInt("scriptId")
biz.IsTrue(scriptId > 0, "scriptId错误")
return uint64(scriptId)
}

View File

@@ -62,7 +62,7 @@ func (m *Mongo) Save(rc *req.Ctx) {
}
func (m *Mongo) DeleteMongo(rc *req.Ctx) {
idsStr := rc.F.PathParam("id")
idsStr := rc.PathParam("id")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -84,7 +84,7 @@ func (m *Mongo) Databases(rc *req.Ctx) {
func (m *Mongo) Collections(rc *req.Ctx) {
conn, err := m.MongoApp.GetMongoConn(m.GetMongoId(rc))
biz.ErrIsNil(err)
db := rc.F.Query("database")
db := rc.Query("database")
biz.NotEmpty(db, "database不能为空")
ctx := context.TODO()
res, err := conn.Cli.Database(db).ListCollectionNames(ctx, bson.D{})
@@ -215,7 +215,7 @@ func (m *Mongo) InsertOneCommand(rc *req.Ctx) {
// 获取请求路径上的mongo id
func (m *Mongo) GetMongoId(rc *req.Ctx) uint64 {
dbId := rc.F.PathParamInt("id")
dbId := rc.PathParamInt("id")
biz.IsTrue(dbId > 0, "mongoId错误")
return uint64(dbId)
}

View File

@@ -16,7 +16,7 @@ func (m *Msg) GetMsgs(rc *req.Ctx) {
condition := &entity.Msg{
RecipientId: int64(rc.GetLoginAccount().Id),
}
res, err := m.MsgApp.GetPageList(condition, rc.F.GetPageParam(), new([]entity.Msg))
res, err := m.MsgApp.GetPageList(condition, rc.GetPageParam(), new([]entity.Msg))
biz.ErrIsNil(err)
rc.ResData = res
}

View File

@@ -11,9 +11,9 @@ import (
func (r *Redis) Hscan(rc *req.Ctx) {
ri, key := r.checkKeyAndGetRedisConn(rc)
count := rc.F.QueryIntDefault("count", 10)
match := rc.F.Query("match")
cursor := rc.F.QueryIntDefault("cursor", 0)
count := rc.QueryIntDefault("count", 10)
match := rc.Query("match")
cursor := rc.QueryIntDefault("cursor", 0)
contextTodo := context.TODO()
cmdable := ri.GetCmdable()
@@ -31,7 +31,7 @@ func (r *Redis) Hscan(rc *req.Ctx) {
func (r *Redis) Hdel(rc *req.Ctx) {
ri, key := r.checkKeyAndGetRedisConn(rc)
field := rc.F.Query("field")
field := rc.Query("field")
rc.ReqParam = collx.Kvs("redis", ri.Info, "key", key, "field", field)
delRes, err := ri.GetCmdable().HDel(context.TODO(), key, field).Result()
@@ -41,7 +41,7 @@ func (r *Redis) Hdel(rc *req.Ctx) {
func (r *Redis) Hget(rc *req.Ctx) {
ri, key := r.checkKeyAndGetRedisConn(rc)
field := rc.F.Query("field")
field := rc.Query("field")
res, err := ri.GetCmdable().HGet(context.TODO(), key, field).Result()
biz.ErrIsNilAppendErr(err, "hget err: %s")

View File

@@ -16,8 +16,8 @@ func (r *Redis) GetListValue(rc *req.Ctx) {
len, err := cmdable.LLen(ctx, key).Result()
biz.ErrIsNilAppendErr(err, "获取list长度失败: %s")
start := rc.F.QueryIntDefault("start", 0)
stop := rc.F.QueryIntDefault("stop", 10)
start := rc.QueryIntDefault("start", 0)
stop := rc.QueryIntDefault("stop", 10)
res, err := cmdable.LRange(ctx, key, int64(start), int64(stop)).Result()
biz.ErrIsNilAppendErr(err, "获取list值失败: %s")

View File

@@ -72,7 +72,7 @@ func (r *Redis) Save(rc *req.Ctx) {
// 获取redis实例密码由于数据库是加密存储故提供该接口展示原文密码
func (r *Redis) GetRedisPwd(rc *req.Ctx) {
rid := uint64(rc.F.PathParamInt("id"))
rid := uint64(rc.PathParamInt("id"))
re, err := r.RedisApp.GetById(new(entity.Redis), rid, "Password")
biz.ErrIsNil(err, "redis信息不存在")
if err := re.PwdDecrypt(); err != nil {
@@ -82,7 +82,7 @@ func (r *Redis) GetRedisPwd(rc *req.Ctx) {
}
func (r *Redis) DeleteRedis(rc *req.Ctx) {
idsStr := rc.F.PathParam("id")
idsStr := rc.PathParam("id")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -94,10 +94,10 @@ func (r *Redis) DeleteRedis(rc *req.Ctx) {
}
func (r *Redis) RedisInfo(rc *req.Ctx) {
ri, err := r.RedisApp.GetRedisConn(uint64(rc.F.PathParamInt("id")), 0)
ri, err := r.RedisApp.GetRedisConn(uint64(rc.PathParamInt("id")), 0)
biz.ErrIsNil(err)
section := rc.F.Query("section")
section := rc.Query("section")
mode := ri.Info.Mode
ctx := context.Background()
var redisCli *redis.Client
@@ -105,7 +105,7 @@ func (r *Redis) RedisInfo(rc *req.Ctx) {
if mode == "" || mode == rdm.StandaloneMode || mode == rdm.SentinelMode {
redisCli = ri.Cli
} else if mode == rdm.ClusterMode {
host := rc.F.Query("host")
host := rc.Query("host")
biz.NotEmpty(host, "集群模式host信息不能为空")
clusterClient := ri.ClusterCli
// 遍历集群的master节点找到该redis client
@@ -171,7 +171,7 @@ func (r *Redis) RedisInfo(rc *req.Ctx) {
}
func (r *Redis) ClusterInfo(rc *req.Ctx) {
ri, err := r.RedisApp.GetRedisConn(uint64(rc.F.PathParamInt("id")), 0)
ri, err := r.RedisApp.GetRedisConn(uint64(rc.PathParamInt("id")), 0)
biz.ErrIsNil(err)
biz.IsEquals(ri.Info.Mode, rdm.ClusterMode, "非集群模式")
info, _ := ri.ClusterCli.ClusterInfo(context.Background()).Result()
@@ -216,7 +216,7 @@ func (r *Redis) ClusterInfo(rc *req.Ctx) {
// 校验查询参数中的key为必填项并返回redis实例
func (r *Redis) checkKeyAndGetRedisConn(rc *req.Ctx) (*rdm.RedisConn, string) {
key := rc.F.Query("key")
key := rc.Query("key")
biz.NotEmpty(key, "key不能为空")
return r.getRedisConn(rc), key
}
@@ -230,5 +230,5 @@ func (r *Redis) getRedisConn(rc *req.Ctx) *rdm.RedisConn {
// 获取redis id与要操作的库号统一路径
func getIdAndDbNum(rc *req.Ctx) (uint64, int) {
return uint64(rc.F.PathParamInt("id")), rc.F.PathParamInt("db")
return uint64(rc.PathParamInt("id")), rc.PathParamInt("db")
}

View File

@@ -21,9 +21,9 @@ func (r *Redis) ZCard(rc *req.Ctx) {
func (r *Redis) ZScan(rc *req.Ctx) {
ri, key := r.checkKeyAndGetRedisConn(rc)
cursor := uint64(rc.F.QueryIntDefault("cursor", 0))
match := rc.F.QueryDefault("match", "*")
count := rc.F.QueryIntDefault("count", 50)
cursor := uint64(rc.QueryIntDefault("cursor", 0))
match := rc.QueryDefault("match", "*")
count := rc.QueryIntDefault("count", 50)
keys, cursor, err := ri.GetCmdable().ZScan(context.TODO(), key, cursor, match, int64(count)).Result()
biz.ErrIsNilAppendErr(err, "sscan失败: %s")
@@ -35,8 +35,8 @@ func (r *Redis) ZScan(rc *req.Ctx) {
func (r *Redis) ZRevRange(rc *req.Ctx) {
ri, key := r.checkKeyAndGetRedisConn(rc)
start := rc.F.QueryIntDefault("start", 0)
stop := rc.F.QueryIntDefault("stop", 50)
start := rc.QueryIntDefault("start", 0)
stop := rc.QueryIntDefault("stop", 50)
res, err := ri.GetCmdable().ZRevRangeWithScores(context.TODO(), key, int64(start), int64(stop)).Result()
biz.ErrIsNilAppendErr(err, "ZRevRange失败: %s")

View File

@@ -120,8 +120,8 @@ func (a *Account) UpdateAccount(rc *req.Ctx) {
// @router /accounts [get]
func (a *Account) Accounts(rc *req.Ctx) {
condition := &entity.Account{}
condition.Username = rc.F.Query("username")
res, err := a.AccountApp.GetPageList(condition, rc.F.GetPageParam(), new([]vo.AccountManageVO))
condition.Username = rc.Query("username")
res, err := a.AccountApp.GetPageList(condition, rc.GetPageParam(), new([]vo.AccountManageVO))
biz.ErrIsNil(err)
rc.ResData = res
}
@@ -149,9 +149,9 @@ func (a *Account) SaveAccount(rc *req.Ctx) {
func (a *Account) ChangeStatus(rc *req.Ctx) {
account := &entity.Account{}
account.Id = uint64(rc.F.PathParamInt("id"))
account.Id = uint64(rc.PathParamInt("id"))
status := entity.AccountStatus(int8(rc.F.PathParamInt("status")))
status := entity.AccountStatus(int8(rc.PathParamInt("status")))
biz.ErrIsNil(entity.AccountStatusEnum.Valid(status))
account.Status = status
@@ -160,7 +160,7 @@ func (a *Account) ChangeStatus(rc *req.Ctx) {
}
func (a *Account) DeleteAccount(rc *req.Ctx) {
idsStr := rc.F.PathParam("id")
idsStr := rc.PathParam("id")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -173,7 +173,7 @@ func (a *Account) DeleteAccount(rc *req.Ctx) {
// 获取账号角色信息列表
func (a *Account) AccountRoles(rc *req.Ctx) {
rc.ResData = a.getAccountRoles(uint64(rc.F.PathParamInt("id")))
rc.ResData = a.getAccountRoles(uint64(rc.PathParamInt("id")))
}
func (a *Account) getAccountRoles(accountId uint64) []*vo.AccountRoleVO {
@@ -217,7 +217,7 @@ func (a *Account) getAccountRoles(accountId uint64) []*vo.AccountRoleVO {
func (a *Account) AccountResources(rc *req.Ctx) {
var resources vo.ResourceManageVOList
// 获取账号菜单资源
biz.ErrIsNil(a.ResourceApp.GetAccountResources(uint64(rc.F.PathParamInt("id")), &resources))
biz.ErrIsNil(a.ResourceApp.GetAccountResources(uint64(rc.PathParamInt("id")), &resources))
rc.ResData = resources.ToTrees(0)
}
@@ -231,7 +231,7 @@ func (a *Account) RelateRole(rc *req.Ctx) {
// 重置otp秘钥
func (a *Account) ResetOtpSecret(rc *req.Ctx) {
account := &entity.Account{OtpSecret: "-"}
accountId := uint64(rc.F.PathParamInt("id"))
accountId := uint64(rc.PathParamInt("id"))
account.Id = accountId
rc.ReqParam = collx.Kvs("accountId", accountId)
biz.ErrIsNil(a.AccountApp.Update(rc.MetaCtx, account))

View File

@@ -13,15 +13,15 @@ type Config struct {
}
func (c *Config) Configs(rc *req.Ctx) {
condition := &entity.Config{Key: rc.F.Query("key")}
condition := &entity.Config{Key: rc.Query("key")}
condition.Permission = rc.GetLoginAccount().Username
res, err := c.ConfigApp.GetPageList(condition, rc.F.GetPageParam(), new([]entity.Config))
res, err := c.ConfigApp.GetPageList(condition, rc.GetPageParam(), new([]entity.Config))
biz.ErrIsNil(err)
rc.ResData = res
}
func (c *Config) GetConfigValueByKey(rc *req.Ctx) {
key := rc.F.Query("key")
key := rc.Query("key")
biz.NotEmpty(key, "key不能为空")
config := c.ConfigApp.GetConfig(key)

View File

@@ -22,7 +22,7 @@ func (r *Resource) GetAllResourceTree(rc *req.Ctx) {
}
func (r *Resource) GetById(rc *req.Ctx) {
res, err := r.ResourceApp.GetById(new(entity.Resource), uint64(rc.F.PathParamInt("id")))
res, err := r.ResourceApp.GetById(new(entity.Resource), uint64(rc.PathParamInt("id")))
biz.ErrIsNil(err, "该资源不存在")
rc.ResData = res
}
@@ -41,19 +41,19 @@ func (r *Resource) SaveResource(rc *req.Ctx) {
}
func (r *Resource) DelResource(rc *req.Ctx) {
biz.ErrIsNil(r.ResourceApp.Delete(rc.MetaCtx, uint64(rc.F.PathParamInt("id"))))
biz.ErrIsNil(r.ResourceApp.Delete(rc.MetaCtx, uint64(rc.PathParamInt("id"))))
}
func (r *Resource) ChangeStatus(rc *req.Ctx) {
rid := uint64(rc.F.PathParamInt("id"))
status := int8(rc.F.PathParamInt("status"))
rid := uint64(rc.PathParamInt("id"))
status := int8(rc.PathParamInt("status"))
rc.ReqParam = collx.Kvs("id", rid, "status", status)
biz.ErrIsNil(r.ResourceApp.ChangeStatus(rc.MetaCtx, rid, status))
}
func (r *Resource) Sort(rc *req.Ctx) {
var rs []form.ResourceForm
rc.F.BindJSON(&rs)
rc.BindJSON(&rs)
rc.ReqParam = rs
for _, v := range rs {

View File

@@ -21,7 +21,7 @@ type Role struct {
func (r *Role) Roles(rc *req.Ctx) {
cond, pageParam := req.BindQueryAndPage(rc, new(entity.RoleQuery))
notIdsStr := rc.F.Query("notIds")
notIdsStr := rc.Query("notIds")
if notIdsStr != "" {
cond.NotIds = collx.ArrayMap[string, uint64](strings.Split(notIdsStr, ","), func(val string) uint64 {
return uint64(anyx.ConvInt(val))
@@ -44,7 +44,7 @@ func (r *Role) SaveRole(rc *req.Ctx) {
// 删除角色及其资源关联关系
func (r *Role) DelRole(rc *req.Ctx) {
idsStr := rc.F.PathParam("id")
idsStr := rc.PathParam("id")
rc.ReqParam = collx.Kvs("ids", idsStr)
ids := strings.Split(idsStr, ",")
@@ -57,13 +57,13 @@ func (r *Role) DelRole(rc *req.Ctx) {
// 获取角色关联的资源id数组用于分配资源时回显已拥有的资源
func (r *Role) RoleResourceIds(rc *req.Ctx) {
rc.ResData = r.RoleApp.GetRoleResourceIds(uint64(rc.F.PathParamInt("id")))
rc.ResData = r.RoleApp.GetRoleResourceIds(uint64(rc.PathParamInt("id")))
}
// 查看角色关联的资源树信息
func (r *Role) RoleResource(rc *req.Ctx) {
var resources vo.ResourceManageVOList
r.RoleApp.GetRoleResources(uint64(rc.F.PathParamInt("id")), &resources)
r.RoleApp.GetRoleResources(uint64(rc.PathParamInt("id")), &resources)
rc.ResData = resources.ToTrees(0)
}
@@ -85,7 +85,7 @@ func (r *Role) SaveResource(rc *req.Ctx) {
// 查看角色关联的用户
func (r *Role) RoleAccount(rc *req.Ctx) {
cond, pageParam := req.BindQueryAndPage[*entity.RoleAccountQuery](rc, new(entity.RoleAccountQuery))
cond.RoleId = uint64(rc.F.PathParamInt("id"))
cond.RoleId = uint64(rc.PathParamInt("id"))
var accounts []*vo.AccountRoleVO
res, err := r.RoleApp.GetRoleAccountPage(cond, pageParam, &accounts)
biz.ErrIsNil(err)

View File

@@ -60,7 +60,7 @@ func (p *TagTree) GetTagTree(rc *req.Ctx) {
func (p *TagTree) ListByQuery(rc *req.Ctx) {
cond := new(entity.TagTreeQuery)
tagPaths := rc.F.Query("tagPaths")
tagPaths := rc.Query("tagPaths")
cond.CodePaths = strings.Split(tagPaths, ",")
var tagTrees vo.TagTreeVOS
p.TagTreeApp.ListByQuery(cond, &tagTrees)
@@ -77,12 +77,12 @@ func (p *TagTree) SaveTagTree(rc *req.Ctx) {
}
func (p *TagTree) DelTagTree(rc *req.Ctx) {
biz.ErrIsNil(p.TagTreeApp.Delete(rc.MetaCtx, uint64(rc.F.PathParamInt("id"))))
biz.ErrIsNil(p.TagTreeApp.Delete(rc.MetaCtx, uint64(rc.PathParamInt("id"))))
}
// 获取用户可操作的资源标签路径
func (p *TagTree) TagResources(rc *req.Ctx) {
resourceType := int8(rc.F.PathParamInt("rtype"))
resourceType := int8(rc.PathParamInt("rtype"))
tagResources := p.TagTreeApp.GetAccountTagResources(rc.GetLoginAccount().Id, resourceType, "")
tagPath2Resource := collx.ArrayToMap[entity.TagResource, string](tagResources, func(tagResource entity.TagResource) string {
return tagResource.TagPath

View File

@@ -49,7 +49,7 @@ func (p *Team) SaveTeam(rc *req.Ctx) {
}
func (p *Team) DelTeam(rc *req.Ctx) {
idsStr := rc.F.PathParam("id")
idsStr := rc.PathParam("id")
rc.ReqParam = idsStr
ids := strings.Split(idsStr, ",")
@@ -62,10 +62,10 @@ func (p *Team) DelTeam(rc *req.Ctx) {
// 获取团队的成员信息
func (p *Team) GetTeamMembers(rc *req.Ctx) {
condition := &entity.TeamMember{TeamId: uint64(rc.F.PathParamInt("id"))}
condition.Username = rc.F.Query("username")
condition := &entity.TeamMember{TeamId: uint64(rc.PathParamInt("id"))}
condition.Username = rc.Query("username")
res, err := p.TeamApp.GetMemberPage(condition, rc.F.GetPageParam(), &[]vo.TeamMember{})
res, err := p.TeamApp.GetMemberPage(condition, rc.GetPageParam(), &[]vo.TeamMember{})
biz.ErrIsNil(err)
rc.ResData = res
}
@@ -98,8 +98,8 @@ func (p *Team) SaveTeamMember(rc *req.Ctx) {
// 删除团队成员
func (p *Team) DelTeamMember(rc *req.Ctx) {
tid := rc.F.PathParamInt("id")
aid := rc.F.PathParamInt("accountId")
tid := rc.PathParamInt("id")
aid := rc.PathParamInt("accountId")
rc.ReqParam = fmt.Sprintf("teamId: %d, accountId: %d", tid, aid)
p.TeamApp.DeleteMember(rc.MetaCtx, uint64(tid), uint64(aid))
@@ -107,7 +107,7 @@ func (p *Team) DelTeamMember(rc *req.Ctx) {
// 获取团队关联的标签id
func (p *Team) GetTagIds(rc *req.Ctx) {
rc.ResData = p.TeamApp.ListTagIds(uint64(rc.F.PathParamInt("id")))
rc.ResData = p.TeamApp.ListTagIds(uint64(rc.PathParamInt("id")))
}
// 保存团队关联标签信息

View File

@@ -37,18 +37,18 @@ type F interface {
}
// wrapper F提供更多基于F接口方法的封装方法
type WrapperF struct {
F F
type wrapperF struct {
f F
}
func NewWrapperF(f F) *WrapperF {
return &WrapperF{F: f}
func NewWrapperF(f F) *wrapperF {
return &wrapperF{f: f}
}
// Header is an intelligent shortcut for c.Writer.Header().Set(key, value).
// It writes a header in the response.
// If value == "", this method removes the header `c.Writer.Header().Del(key)`
func (wf *WrapperF) Header(key, value string) {
func (wf *wrapperF) Header(key, value string) {
if value == "" {
wf.GetWriter().Header().Del(key)
return
@@ -57,12 +57,12 @@ func (wf *WrapperF) Header(key, value string) {
}
// get request header value
func (wf *WrapperF) GetHeader(key string) string {
func (wf *wrapperF) GetHeader(key string) string {
return wf.GetRequest().Header.Get(key)
}
// 获取查询参数,不存在则返回默认值
func (wf *WrapperF) QueryDefault(qm string, defaultStr string) string {
func (wf *wrapperF) QueryDefault(qm string, defaultStr string) string {
qv := wf.Query(qm)
if qv == "" {
return defaultStr
@@ -71,12 +71,12 @@ func (wf *WrapperF) QueryDefault(qm string, defaultStr string) string {
}
// 获取查询参数中指定参数值并转为int
func (wf *WrapperF) QueryInt(qm string) int {
func (wf *wrapperF) QueryInt(qm string) int {
return wf.QueryIntDefault(qm, 0)
}
// 获取查询参数中指定参数值并转为int 不存在则返回默认值
func (wf *WrapperF) QueryIntDefault(qm string, defaultInt int) int {
func (wf *wrapperF) QueryIntDefault(qm string, defaultInt int) int {
qv := wf.Query(qm)
if qv == "" {
return defaultInt
@@ -87,18 +87,18 @@ func (wf *WrapperF) QueryIntDefault(qm string, defaultInt int) int {
}
// 获取分页参数
func (wf *WrapperF) GetPageParam() *model.PageParam {
func (wf *wrapperF) GetPageParam() *model.PageParam {
return &model.PageParam{PageNum: wf.QueryIntDefault("pageNum", 1), PageSize: wf.QueryIntDefault("pageSize", 10)}
}
// 获取路径参数
func (wf *WrapperF) PathParamInt(pm string) int {
func (wf *wrapperF) PathParamInt(pm string) int {
value, err := strconv.Atoi(wf.PathParam(pm))
biz.ErrIsNilAppendErr(err, "string类型转换int异常: %s")
return value
}
func (wf *WrapperF) Download(reader io.Reader, filename string) {
func (wf *wrapperF) Download(reader io.Reader, filename string) {
wf.Header("Content-Type", "application/octet-stream")
wf.Header("Content-Disposition", "attachment; filename="+filename)
io.Copy(wf.GetWriter(), reader)
@@ -108,50 +108,50 @@ func (wf *WrapperF) Download(reader io.Reader, filename string) {
/************ wrapper F ************/
/************************************/
func (wf *WrapperF) GetRequest() *http.Request {
return wf.F.GetRequest()
func (wf *wrapperF) GetRequest() *http.Request {
return wf.f.GetRequest()
}
func (wf *WrapperF) GetWriter() http.ResponseWriter {
return wf.F.GetWriter()
func (wf *wrapperF) GetWriter() http.ResponseWriter {
return wf.f.GetWriter()
}
func (wf *WrapperF) Redirect(code int, location string) {
wf.F.Redirect(code, location)
func (wf *wrapperF) Redirect(code int, location string) {
wf.f.Redirect(code, location)
}
func (wf *WrapperF) ClientIP() string {
return wf.F.ClientIP()
func (wf *wrapperF) ClientIP() string {
return wf.f.ClientIP()
}
func (wf *WrapperF) BindJSON(data any) error {
return wf.F.BindJSON(data)
func (wf *wrapperF) BindJSON(data any) error {
return wf.f.BindJSON(data)
}
func (wf *WrapperF) BindQuery(data any) error {
return wf.F.BindQuery(data)
func (wf *wrapperF) BindQuery(data any) error {
return wf.f.BindQuery(data)
}
func (wf *WrapperF) Query(qm string) string {
return wf.F.Query(qm)
func (wf *wrapperF) Query(qm string) string {
return wf.f.Query(qm)
}
func (wf *WrapperF) PathParam(pm string) string {
return wf.F.PathParam(pm)
func (wf *wrapperF) PathParam(pm string) string {
return wf.f.PathParam(pm)
}
func (wf *WrapperF) PostForm(key string) string {
return wf.F.PostForm(key)
func (wf *wrapperF) PostForm(key string) string {
return wf.f.PostForm(key)
}
func (wf *WrapperF) FormFile(name string) (*multipart.FileHeader, error) {
return wf.F.FormFile(name)
func (wf *wrapperF) FormFile(name string) (*multipart.FileHeader, error) {
return wf.f.FormFile(name)
}
func (wf *WrapperF) MultipartForm() (*multipart.Form, error) {
return wf.F.MultipartForm()
func (wf *wrapperF) MultipartForm() (*multipart.Form, error) {
return wf.f.MultipartForm()
}
func (wf *WrapperF) JSONRes(code int, data any) {
wf.F.JSONRes(200, data)
func (wf *wrapperF) JSONRes(code int, data any) {
wf.f.JSONRes(code, data)
}

View File

@@ -1,7 +1,6 @@
package req
import (
"mayfly-go/pkg/contextx"
"mime/multipart"
"net/http"
@@ -9,7 +8,7 @@ import (
)
func NewCtxWithGin(g *gin.Context) *Ctx {
return &Ctx{F: NewWrapperF(&GinF{ginCtx: g}), MetaCtx: contextx.WithTraceId(g.Request.Context())}
return NewCtx(&GinF{ginCtx: g})
}
type GinF struct {
@@ -61,5 +60,5 @@ func (gf *GinF) MultipartForm() (*multipart.Form, error) {
}
func (gf *GinF) JSONRes(code int, data any) {
gf.ginCtx.JSON(200, data)
gf.ginCtx.JSON(code, data)
}

View File

@@ -52,7 +52,7 @@ func LogHandler(rc *Ctx) error {
attrMap := make(map[string]any, 0)
req := rc.F.GetRequest()
req := rc.GetRequest()
attrMap[req.Method] = req.URL.Path
if la := contextx.GetLoginAccount(rc.MetaCtx); la != nil {

View File

@@ -44,12 +44,12 @@ func PermissionHandler(rc *Ctx) error {
if permission != nil && !permission.NeedToken {
return nil
}
tokenStr := rc.F.GetHeader("Authorization")
tokenStr := rc.GetHeader("Authorization")
// 删除前缀 Bearer, 以支持 Bearer Token
tokenStr, _ = strings.CutPrefix(tokenStr, "Bearer ")
// header不存在则从查询参数token中获取
if tokenStr == "" {
tokenStr = rc.F.Query("token")
tokenStr = rc.Query("token")
}
if tokenStr == "" {
return errorx.PermissionErr

View File

@@ -4,6 +4,8 @@ import (
"context"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/assert"
"net/http"
@@ -14,8 +16,8 @@ import (
type HandlerFunc func(*Ctx)
type Ctx struct {
Conf *Conf // 请求配置
F *WrapperF // http framework处理接口
*wrapperF // http framework处理接口
Conf *Conf // 请求配置
ReqParam any // 请求参数,主要用于记录日志
ResData any // 响应结果
@@ -25,18 +27,26 @@ type Ctx struct {
MetaCtx context.Context // 元数据上下文信息,如登录账号(只有校验token后才会有值)traceId等
}
func NewCtx(f F) *Ctx {
ctx := &Ctx{MetaCtx: contextx.WithTraceId(f.GetRequest().Context())}
ctx.wrapperF = NewWrapperF(f)
return ctx
}
// 执行指定handler func并输出响应结果
func (rc *Ctx) Handle(handler HandlerFunc) {
begin := time.Now()
defer func() {
rc.timed = time.Since(begin).Milliseconds()
if err := recover(); err != nil {
rc.Error = err
ErrorRes(rc, err)
}
// 应用所有请求后置处理器
ApplyHandlerInterceptor(afterHandlers, rc)
// 输出响应结果
rc.res()
}()
assert.IsTrue(rc.F != nil, "F == nil")
assert.IsTrue(rc.wrapperF != nil, "F == nil")
// 默认为不记录请求参数可在handler回调函数中覆盖赋值
rc.ReqParam = nil
@@ -50,9 +60,6 @@ func (rc *Ctx) Handle(handler HandlerFunc) {
}
handler(rc)
if rc.Conf == nil || !rc.Conf.noRes {
rc.F.JSONRes(http.StatusOK, model.Success(rc.ResData))
}
}
// 获取当前登录账号信息,不存在则会报错。
@@ -91,13 +98,31 @@ func (rc *Ctx) GetLogInfo() *LogInfo {
return rc.Conf.logInfo
}
// 输出响应结果
func (rc *Ctx) res() {
if err := rc.Error; err != nil {
switch t := err.(type) {
case errorx.BizError:
rc.JSONRes(http.StatusOK, model.Error(t))
default:
logx.ErrorTrace("服务器错误", t)
rc.JSONRes(http.StatusOK, model.ServerError())
}
return
}
if rc.Conf == nil || !rc.Conf.noRes {
rc.JSONRes(http.StatusOK, model.Success(rc.ResData))
}
}
/************************************/
/***** GOLANG.ORG/X/NET/CONTEXT -> copy gin.Context *****/
/************************************/
// hasRequestContext returns whether c.Request has Context and fallback.
func (c *Ctx) hasRequestContext() bool {
request := c.F.GetRequest()
request := c.GetRequest()
return request != nil && request.Context() != nil
}
@@ -106,7 +131,7 @@ func (c *Ctx) Deadline() (deadline time.Time, ok bool) {
if !c.hasRequestContext() {
return
}
return c.F.GetRequest().Context().Deadline()
return c.GetRequest().Context().Deadline()
}
// Done returns nil (chan which will wait forever) when c.Request has no Context.
@@ -114,7 +139,7 @@ func (c *Ctx) Done() <-chan struct{} {
if !c.hasRequestContext() {
return nil
}
return c.F.GetRequest().Context().Done()
return c.GetRequest().Context().Done()
}
// Err returns nil when c.Request has no Context.
@@ -122,7 +147,7 @@ func (c *Ctx) Err() error {
if !c.hasRequestContext() {
return nil
}
return c.F.GetRequest().Context().Err()
return c.GetRequest().Context().Err()
}
// Value returns the value associated with this context for key, or nil
@@ -130,12 +155,12 @@ func (c *Ctx) Err() error {
// the same key returns the same result.
func (c *Ctx) Value(key any) any {
if key == 0 {
return c.F.GetRequest()
return c.GetRequest()
}
if !c.hasRequestContext() {
return nil
}
return c.F.GetRequest().Context().Value(key)
return c.GetRequest().Context().Value(key)
}
// 处理器拦截器函数

View File

@@ -2,18 +2,16 @@ package req
import (
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/structx"
"mayfly-go/pkg/validatorx"
"net/http"
"github.com/go-playground/validator/v10"
)
// 绑定并校验请求结构体参数
func BindJsonAndValid[T any](rc *Ctx, data T) T {
if err := rc.F.BindJSON(data); err != nil {
if err := rc.BindJSON(data); err != nil {
panic(ConvBindValidationError(data, err))
} else {
return data
@@ -29,7 +27,7 @@ func BindJsonAndCopyTo[T any](rc *Ctx, form any, toStruct T) T {
// 绑定查询字符串到指定结构体
func BindQuery[T any](rc *Ctx, data T) T {
if err := rc.F.BindQuery(data); err != nil {
if err := rc.BindQuery(data); err != nil {
panic(ConvBindValidationError(data, err))
} else {
return data
@@ -38,21 +36,10 @@ func BindQuery[T any](rc *Ctx, data T) T {
// 绑定查询字符串到指定结构体,并将分页信息也返回
func BindQueryAndPage[T any](rc *Ctx, data T) (T, *model.PageParam) {
if err := rc.F.BindQuery(data); err != nil {
if err := rc.BindQuery(data); err != nil {
panic(ConvBindValidationError(data, err))
} else {
return data, rc.F.GetPageParam()
}
}
// 返回失败结果集
func ErrorRes(rc *Ctx, err any) {
switch t := err.(type) {
case errorx.BizError:
rc.F.JSONRes(http.StatusOK, model.Error(t))
default:
logx.ErrorTrace("服务器错误", t)
rc.F.JSONRes(http.StatusOK, model.ServerError())
return data, rc.GetPageParam()
}
}