feat 优化不规范的代码

This commit is contained in:
microrain
2025-05-14 13:56:42 +08:00
parent fffe13fee3
commit 0fddb743fb
36 changed files with 276 additions and 196 deletions

View File

@@ -28,6 +28,9 @@ func (c *cDictData) GetDictData(ctx context.Context, req *common.GetDictReq) (re
return
}
}
if data == nil {
data = new(model.GetDictRes)
}
res = &common.GetDictRes{
Data: data.Data,
Values: data.Values,

View File

@@ -30,6 +30,12 @@ type cProduct struct{}
func (c *cProduct) Detail(ctx context.Context, req *product.DetailProductReq) (res *product.DetailProductRes, err error) {
p, err := service.DevProduct().Detail(ctx, req.ProductKey)
if err != nil {
return
}
if p == nil {
return nil, gerror.NewCode(gcode.CodeMissingParameter, "产品不存在")
}
// 获取产品的设备数量
totals, err := service.DevDevice().TotalByProductKey(ctx, []string{p.Key})
if err != nil {
@@ -44,6 +50,9 @@ func (c *cProduct) Detail(ctx context.Context, req *product.DetailProductReq) (r
func (c *cProduct) ListForPage(ctx context.Context, req *product.ListForPageReq) (res *product.ListForPageRes, err error) {
out, err := service.DevProduct().ListForPage(ctx, &req.ListForPageInput)
if err != nil {
return
}
res = &product.ListForPageRes{
ListForPageOutput: *out,
}

View File

@@ -76,7 +76,7 @@ func (s *sAlarmRule) Cache(ctx context.Context) (rs map[string][]model.AlarmRule
}
if v.Action != "" {
performActionErr := json.Unmarshal([]byte(v.Action), &v.PerformAction)
if err != nil {
if performActionErr != nil {
return nil, performActionErr
}
}

View File

@@ -2,6 +2,7 @@ package alarm
import (
"context"
"errors"
"github.com/gogf/gf/v2/util/gconv"
"sagooiot/internal/consts"
"sagooiot/internal/model"
@@ -66,7 +67,10 @@ func (s *sAlarmRule) NoticeAction(ctx context.Context, rule model.AlarmRuleOutpu
if i == 9 || i == 15 {
key := consts.DeviceAlarmLogPrefix + rule.ProductKey + deviceKey + expression
alarmLogData, err := cache.Instance().Get(ctx, key)
if alarmLogData == nil {
err = errors.New("获取数据失败")
return
}
var alarmLog model.AlarmLogOutput
err = gconv.Scan(alarmLogData.Val(), &alarmLog)
if err != nil {

View File

@@ -182,7 +182,7 @@ func (s *sAlarmRule) getAlarmRuleList(ctx context.Context, productKey, deviceKey
}
if r.Action != "" {
performActionErr := json.Unmarshal([]byte(r.Action), &r.PerformAction)
if err != nil {
if performActionErr != nil {
return nil, performActionErr
}
}

View File

@@ -30,6 +30,10 @@ func (s *sAnalysisAlarm) GetDeviceAlertCountByYearMonth(ctx context.Context, yea
value, err = s.getAlarmDataCount(ctx, "year", year)
return
}, time.Second*15)
if resData == nil {
err = errors.New("获取数据失败")
return
}
err = gconv.Scan(resData.Val(), &res)
return
}
@@ -43,6 +47,10 @@ func (s *sAnalysisAlarm) GetDeviceAlertCountByMonthDay(ctx context.Context, mont
value, err = s.getAlarmDataCount(ctx, "month", gconv.String(year), month)
return
}, time.Hour)
if resData == nil {
err = errors.New("获取数据失败")
return
}
err = gconv.Scan(resData.Val(), &res)
return
}
@@ -56,7 +64,10 @@ func (s *sAnalysisAlarm) GetDeviceAlertCountByDayHour(ctx context.Context, day s
value, err = s.getAlarmDataCount(ctx, "month", gconv.String(year), gconv.String(month), day)
return
}, time.Second*15)
if resData == nil {
err = errors.New("获取数据失败")
return
}
err = gconv.Scan(resData.Val(), &res)
return
}
@@ -175,6 +186,10 @@ func (s *sAnalysisAlarm) GetAlarmLevelCount(ctx context.Context, dataType, date
}
return
}, time.Second*15)
if resData == nil {
err = errors.New("获取数据失败")
return
}
err = gconv.Scan(resData.Val(), &res)
return
}

View File

@@ -20,9 +20,7 @@ func getDeviceKeys(ctx context.Context, productKey string) (deviceKeys []string)
g.Log().Debug(ctx, err.Error())
return
}
if err != nil {
return
}
for _, device := range deviceList {
deviceKeys = append(deviceKeys, device.Key)
}

View File

@@ -48,6 +48,11 @@ func (s *sAnalysisProduct) GetProductCount(ctx context.Context) (res model.Produ
value, err = s.getTotalData(ctx)
return
}, time.Minute*1)
if resData == nil {
return
}
err = gconv.Struct(resData.Val(), &res)
return
}

View File

@@ -30,6 +30,9 @@ func init() {
// List 系统参数列表
func (s *sConfigData) List(ctx context.Context, input *model.ConfigDoInput) (total int, out []*model.SysConfigOut, err error) {
if input == nil {
input = new(model.ConfigDoInput)
}
m := dao.SysConfig.Ctx(ctx)
if input != nil {
if input.ConfigName != "" {

View File

@@ -71,6 +71,9 @@ func (s *sDictData) GetDictWithDataByType(ctx context.Context, input *model.GetD
// List 获取字典数据
func (s *sDictData) List(ctx context.Context, input *model.SysDictSearchInput) (total int, out []*model.SysDictDataOut, err error) {
if input == nil {
input = new(model.SysDictSearchInput)
}
m := dao.SysDictData.Ctx(ctx)
if input != nil {
if input.DictLabel != "" {

View File

@@ -36,7 +36,8 @@ func (s *sSysInfo) GetSysInfo(ctx context.Context) (out g.Map, err error) {
systemName = cfgSystemName.ConfigValue
}
cfgSystemCopyright, err := service.ConfigData().GetConfigByKey(ctx, consts.SysSystemCopyright)
cfgSystemCopyright, _ := service.ConfigData().GetConfigByKey(ctx, consts.SysSystemCopyright)
systemCopyright := "Sagoo inc."
if cfgSystemName != nil {
systemCopyright = cfgSystemCopyright.ConfigValue
@@ -109,6 +110,15 @@ func (s *sSysInfo) ServerInfoEscalation(ctx context.Context) (err error) {
}
var tmpData *gvar.Var
tmpData, err = cache.Instance().Get(ctx, consts.CacheServerInfo)
if err != nil {
return
}
if tmpData == nil {
err = gerror.New("获取已上报客户端信息失败")
return
}
var serverInfos []map[string]interface{}
if tmpData.Val() != nil {
err = json.Unmarshal([]byte(tmpData.Val().(string)), &serverInfos)

View File

@@ -117,7 +117,7 @@ func (s *sNetworkServer) AddServer(ctx context.Context, in model.NetworkServerAd
if lastIdErr != nil {
return lastIdErr
}
if err == nil && in.Status == consts.ServerStatusOnline {
if in.Status == consts.ServerStatusOnline {
return server.LoadServer(ctx, int(lastId))
}
return

View File

@@ -974,9 +974,6 @@ func (s *sDevDevice) GetProperty(ctx context.Context, in *model.DeviceGetPropert
// GetPropertyList 设备属性详情列表
func (s *sDevDevice) GetPropertyList(ctx context.Context, in *model.DeviceGetPropertyListInput) (out *model.DeviceGetPropertyListOutput, err error) {
resultList, total, currentPage := dcache.GetDeviceDetailDataByPage(ctx, in.DeviceKey, in.PageNum, in.PageSize, consts.MsgTypePropertyReport, consts.MsgTypeGatewayBatch)
if err != nil {
return
}
out = new(model.DeviceGetPropertyListOutput)
out.Total = total
out.CurrentPage = currentPage

View File

@@ -110,6 +110,13 @@ func (s *sLogin) Login(ctx context.Context, verifyKey string, captcha string, us
// CheckPwdErrorNum 验证密码错误次数
func (s *sLogin) CheckPwdErrorNum(ctx context.Context, userName string) (err error) {
tmpData, err := cache.Instance().Get(ctx, consts.CacheSysErrorPrefix+"_"+gconv.String(userName))
if err != nil {
return
}
if tmpData == nil {
return
}
if tmpData.Val() != nil {
//获取密码错误次数和限制登录时间
configKeys := []string{consts.SysPasswordErrorNum, consts.SysAgainLoginDate}

View File

@@ -39,6 +39,17 @@ func (s *sSysApi) GetInfoByIds(ctx context.Context, ids []int) (data []*entity.S
//获取缓存信息
var tmpData *gvar.Var
tmpData, err = cache.Instance().Get(ctx, consts.CacheSysApi)
if err != nil {
return
}
if tmpData == nil {
err = dao.SysApi.Ctx(ctx).Where(g.Map{
dao.SysApi.Columns().IsDeleted: 0,
dao.SysApi.Columns().Status: 1,
}).Scan(&data)
}
var tmpSysApiInfo []*entity.SysApi

View File

@@ -194,6 +194,13 @@ func ApiTree(parentNodeRes []*model.SysApiTreeOut, data []*model.SysApiTreeOut)
func GetMenuInfo(ctx context.Context, menuIds []int) (userMenuTreeOut []*model.UserMenuTreeOut, err error) {
//查看REDIS是否存在
tmpData, err := cache.Instance().Get(ctx, consts.CacheSysMenu)
if err != nil {
return
}
if tmpData == nil {
err = gerror.New("获取菜单失败")
return
}
//将缓存菜单转为struct
var tmpMenuInfo []*entity.SysMenu
if err = json.Unmarshal([]byte(tmpData.Val().(string)), &tmpMenuInfo); err != nil {

View File

@@ -197,11 +197,12 @@ func (s *sSysDept) Edit(ctx context.Context, input *model.EditDeptInput) (err er
var dept1, dept2 *entity.SysDept
//根据ID查看部门是否存在
dept1 = checkDeptId(ctx, input.DeptId, dept1)
dept := dept1.ParentId
deptAnces := dept1.Ancestors
if dept1 == nil {
return gerror.New("部门不存在")
}
dept := dept1.ParentId
deptAnces := dept1.Ancestors
dept2 = checkDeptName(ctx, input.DeptName, dept2, input.DeptId)
if dept2 != nil {
return gerror.New("相同部门已存在,无法修改")

View File

@@ -233,7 +233,13 @@ func (s *sSysMenuButton) Del(ctx context.Context, id int64) (err error) {
func (s *sSysMenuButton) GetInfoByButtonIds(ctx context.Context, ids []int) (data []*entity.SysMenuButton, err error) {
var tmpData *gvar.Var
tmpData, err = cache.Instance().Get(ctx, consts.CacheSysMenuButton)
if err != nil {
return
}
if tmpData == nil {
err = gerror.New("获取菜单按钮信息失败")
return
}
var tmpSysMenuButton []*entity.SysMenuButton
var menuButtonInfo []*entity.SysMenuButton
@@ -269,6 +275,13 @@ func (s *sSysMenuButton) GetInfoByMenuIds(ctx context.Context, menuIds []int) (d
for _, v := range menuIds {
var tmpData *gvar.Var
tmpData, err = cache.Instance().Get(ctx, consts.CacheSysMenuButton+"_"+gconv.String(v))
if err != nil {
return
}
if tmpData == nil {
continue
}
if tmpData.Val() != nil {
var sysMenuButton []*entity.SysMenuButton
err = json.Unmarshal([]byte(tmpData.Val().(string)), &sysMenuButton)

View File

@@ -14,7 +14,6 @@ import (
"sagooiot/internal/consts"
"sagooiot/internal/dao"
"sagooiot/internal/model"
"sagooiot/internal/model/do"
"sagooiot/internal/model/entity"
"sagooiot/internal/service"
"sagooiot/pkg/utility/utils"
@@ -102,117 +101,106 @@ func (s *sSysOperLog) Invoke(ctx context.Context, userId int, url *url.URL, para
// Add 添加操作日志
func (s *sSysOperLog) Add(ctx context.Context, userId int, url *url.URL, param g.Map, method string, clientIp string, res map[string]interface{}, erro error) (err error) {
var operLogInfo = new(entity.SysOperLog)
//根据用户ID查询用户信息
operLogInfo := &entity.SysOperLog{
OperTime: gtime.Now(),
}
// 查询用户信息
var userInfo *entity.SysUser
err = dao.SysUser.Ctx(ctx).Where(g.Map{
dao.SysUser.Columns().Id: userId,
dao.SysUser.Columns().IsDeleted: 0,
dao.SysUser.Columns().Status: 1,
}).Scan(&userInfo)
if err != nil {
return err
}
if userInfo != nil {
//操作人员
operLogInfo.OperName = userInfo.UserName
//获取用户部门信息
// 查询部门信息
var deptInfo *entity.SysDept
err = dao.SysDept.Ctx(ctx).Where(g.Map{
dao.SysDept.Columns().DeptId: userInfo.DeptId,
dao.SysDept.Columns().IsDeleted: 0,
dao.SysDept.Columns().Status: 1,
}).Scan(&deptInfo)
if err != nil {
return err
}
if deptInfo != nil {
//部门名称
operLogInfo.DeptName = deptInfo.DeptName
}
}
//请求地址
// 请求地址和方法
operLogInfo.Method = url.Path
//根据请求地址获取请求信息
apiInfo, _ := service.SysApi().GetInfoByAddress(ctx, url.Path)
if apiInfo != nil {
apiInfo, apiErr := service.SysApi().GetInfoByAddress(ctx, url.Path)
if apiErr == nil && apiInfo != nil {
operLogInfo.Title = apiInfo.Name
}
//请求方法
// 请求方法和业务类型
operLogInfo.RequestMethod = method
//操作类型
operLogInfo.OperatorType = 1
//业务类型
if strings.EqualFold(method, "POST") {
operLogInfo.BusinessType = 1
} else if strings.EqualFold(method, "PUT") {
operLogInfo.BusinessType = 2
} else if strings.EqualFold(method, "DELETE") {
operLogInfo.BusinessType = 3
businessTypeMap := map[string]int{
"POST": 1,
"PUT": 2,
"DELETE": 3,
}
if bt, ok := businessTypeMap[strings.ToUpper(method)]; ok {
operLogInfo.BusinessType = bt
} else {
operLogInfo.BusinessType = 0
}
//请求地址
rawQuery := url.RawQuery
if rawQuery != "" {
rawQuery = "?" + rawQuery
}
operLogInfo.OperUrl = url.Path + rawQuery
//客户端IP
operLogInfo.OperatorType = 1
// 请求URL
operLogInfo.OperUrl = url.Path + func() string {
if url.RawQuery != "" {
return "?" + url.RawQuery
}
return ""
}()
// 客户端IP和位置
operLogInfo.OperIp = clientIp
//操作地址
operLogInfo.OperLocation = utils.GetCityByIp(operLogInfo.OperIp)
//获取当前时间
time, err := gtime.StrToTimeFormat(gtime.Datetime(), "2006-01-02 15:04:05")
if err != nil {
return
}
//请求时间
operLogInfo.OperTime = time
//参数
operLogInfo.OperLocation = utils.GetCityByIp(clientIp)
// 参数
if param != nil {
b, _ := gjson.Encode(param)
if len(b) > 0 {
if b, _ := gjson.Encode(param); len(b) > 0 {
operLogInfo.OperParam = string(b)
}
}
var code gcode.Code = gcode.CodeOK
// 错误码和状态
var code gcode.Code
if erro != nil {
code = gerror.Code(erro)
if code == gcode.CodeNil {
code = gcode.CodeInternalError
}
}
//返回参数
if code.Code() != 0 {
if code != nil && code.Code() != 0 {
operLogInfo.Status = 0
errMsg := erro.Error()
var (
errorMsgMap = map[string]interface{}{
"code": code.Code(),
"message": errMsg,
}
)
errorMsg, _ := gjson.Encode(errorMsgMap)
operLogInfo.ErrorMsg = string(errorMsg)
errorMsgMap := map[string]interface{}{
"code": code.Code(),
"message": errMsg,
}
if b, _ := gjson.Encode(errorMsgMap); len(b) > 0 {
operLogInfo.ErrorMsg = string(b)
}
} else {
operLogInfo.Status = 1
b, _ := gjson.Encode(res)
if len(b) > 0 {
operLogInfo.JsonResult = string(b)
if res != nil {
if b, _ := gjson.Encode(res); len(b) > 0 {
operLogInfo.JsonResult = string(b)
}
}
}
_, err = dao.SysOperLog.Ctx(ctx).Data(do.SysOperLog{
Title: operLogInfo.Title,
BusinessType: operLogInfo.BusinessType,
Method: operLogInfo.Method,
RequestMethod: operLogInfo.RequestMethod,
OperatorType: operLogInfo.OperatorType,
OperName: operLogInfo.OperName,
DeptName: operLogInfo.DeptName,
OperUrl: operLogInfo.OperUrl,
OperIp: operLogInfo.OperIp,
OperLocation: operLogInfo.OperLocation,
OperParam: operLogInfo.OperParam,
JsonResult: operLogInfo.JsonResult,
Status: operLogInfo.Status,
ErrorMsg: operLogInfo.ErrorMsg,
OperTime: operLogInfo.OperTime,
}).Insert()
_, err = dao.SysOperLog.Ctx(ctx).Data(operLogInfo).Insert()
return
}

View File

@@ -213,11 +213,13 @@ func (s *sSysOrganization) Edit(ctx context.Context, input *model.EditOrganizati
var organization1, organization2 *entity.SysOrganization
//根据ID查看组织是否存在
organization1 = checkOrganizationId(ctx, input.Id, organization1)
organization := organization1.ParentId
organizationAnces := organization1.Ancestors
if organization1 == nil {
return gerror.New("区域不存在")
}
organization := organization1.ParentId
organizationAnces := organization1.Ancestors
organization2 = checkOrganizationName(ctx, input.Name, input.Id)
if organization2 != nil {
return gerror.New("相同区域已存在,无法修改")

View File

@@ -108,23 +108,23 @@ func (s *sSysPlugins) AddSysPlugins(ctx context.Context, file *ghttp.UploadFile)
if err != nil {
return err
}
var plugins *entity.SysPlugins
if err = gconv.Scan(result, &plugins); err != nil {
var sysPlugins *entity.SysPlugins
if err = gconv.Scan(result, &sysPlugins); err != nil {
return
}
if plugins.Types == "" {
if sysPlugins.Types == "" {
err = gerror.New("插件类型不能为空")
return
}
if plugins.HandleType == "" {
if sysPlugins.HandleType == "" {
err = gerror.New("处理方式类型不能为空")
return
}
if plugins.Name == "" {
if sysPlugins.Name == "" {
err = gerror.New("名称不能为空")
return
}
if plugins.Title == "" {
if sysPlugins.Title == "" {
err = gerror.New("标题不能为空")
return
}
@@ -136,28 +136,28 @@ func (s *sSysPlugins) AddSysPlugins(ctx context.Context, file *ghttp.UploadFile)
argsArr = append(argsArr, a)
}
plugins.Args = strings.Join(argsArr, ",")
sysPlugins.Args = strings.Join(argsArr, ",")
//对plugins struct赋值
frontend, _ := result["frontend"].(map[string]interface{})
plugins.FrontendUi = 0
sysPlugins.FrontendUi = 0
if gconv.Bool(frontend["ui"]) {
plugins.FrontendUi = 1
sysPlugins.FrontendUi = 1
}
plugins.FrontendUrl = frontend["url"].(string)
sysPlugins.FrontendUrl = frontend["url"].(string)
plugins.FrontendConfiguration = 0
sysPlugins.FrontendConfiguration = 0
if gconv.Bool(frontend["configuration"]) {
plugins.FrontendConfiguration = 1
sysPlugins.FrontendConfiguration = 1
}
//判断名称是否重复
pluginByName, _ := s.GetSysPluginsByName(ctx, plugins.Name)
pluginByName, _ := s.GetSysPluginsByName(ctx, sysPlugins.Name)
if pluginByName != nil {
return gerror.New("插件名称不能重复")
}
//判断标题是否重复
pluginByTitle, _ := s.GetSysPluginsByTitle(ctx, plugins.Title)
pluginByTitle, _ := s.GetSysPluginsByTitle(ctx, sysPlugins.Title)
if pluginByTitle != nil {
return gerror.New("插件标题不能重复")
}
@@ -166,22 +166,22 @@ func (s *sSysPlugins) AddSysPlugins(ctx context.Context, file *ghttp.UploadFile)
//添加插件
_, err = dao.SysPlugins.Ctx(ctx).Data(do.SysPlugins{
DeptId: service.Context().GetUserDeptId(ctx),
Types: plugins.Types,
HandleType: plugins.HandleType,
Name: plugins.Name,
Title: plugins.Title,
Description: plugins.Description,
Version: plugins.Version,
Author: plugins.Author,
Icon: plugins.Icon,
Link: plugins.Link,
Command: plugins.Command,
Args: plugins.Args,
Types: sysPlugins.Types,
HandleType: sysPlugins.HandleType,
Name: sysPlugins.Name,
Title: sysPlugins.Title,
Description: sysPlugins.Description,
Version: sysPlugins.Version,
Author: sysPlugins.Author,
Icon: sysPlugins.Icon,
Link: sysPlugins.Link,
Command: sysPlugins.Command,
Args: sysPlugins.Args,
Status: 0,
FrontendUi: plugins.FrontendUi,
FrontendUrl: plugins.FrontendUrl,
FrontendConfiguration: plugins.FrontendConfiguration,
StartTime: plugins.StartTime,
FrontendUi: sysPlugins.FrontendUi,
FrontendUrl: sysPlugins.FrontendUrl,
FrontendConfiguration: sysPlugins.FrontendConfiguration,
StartTime: sysPlugins.StartTime,
IsDeleted: 0,
CreatedBy: uint(service.Context().GetUserId(ctx)),
CreatedAt: gtime.Now(),

View File

@@ -33,43 +33,42 @@ func (s *sSysPost) GetTree(ctx context.Context, postName string, postCode string
postInfo, err := s.GetData(ctx, postName, postCode, status)
if postInfo != nil {
var parentNodeOut []*model.PostOut
if postInfo != nil {
//获取所有的根节点
for _, v := range postInfo {
var parentNode *model.PostOut
if v.ParentId == -1 {
if err = gconv.Scan(v, &parentNode); err != nil {
return
//获取所有的根节点
for _, v := range postInfo {
var parentNode *model.PostOut
if v.ParentId == -1 {
if err = gconv.Scan(v, &parentNode); err != nil {
return
}
var isExist = false
for _, postOut := range parentNodeOut {
if postOut.PostId == parentNode.PostId {
isExist = true
break
}
var isExist = false
for _, postOut := range parentNodeOut {
if postOut.PostId == parentNode.PostId {
isExist = true
break
}
}
if !isExist {
parentNodeOut = append(parentNodeOut, parentNode)
}
} else {
//查找根节点
parentPost := FindPostParentByChildrenId(ctx, int(v.ParentId))
if err = gconv.Scan(parentPost, &parentNode); err != nil {
return
}
var isExist = false
for _, postOut := range parentNodeOut {
if postOut.PostId == int64(parentPost.PostId) {
isExist = true
break
}
}
if !isExist {
parentNodeOut = append(parentNodeOut, parentNode)
}
if !isExist {
parentNodeOut = append(parentNodeOut, parentNode)
}
} else {
//查找根节点
parentPost := FindPostParentByChildrenId(ctx, int(v.ParentId))
if err = gconv.Scan(parentPost, &parentNode); err != nil {
return
}
var isExist = false
for _, postOut := range parentNodeOut {
if postOut.PostId == int64(parentPost.PostId) {
isExist = true
break
}
}
if !isExist {
parentNodeOut = append(parentNodeOut, parentNode)
}
}
}
//对父节点进行排序
sort.SliceStable(parentNodeOut, func(i, j int) bool {
return parentNodeOut[i].PostSort < parentNodeOut[j].PostSort
@@ -79,9 +78,6 @@ func (s *sSysPost) GetTree(ctx context.Context, postName string, postCode string
if err = gconv.Scan(postInfo, &data); err != nil {
return
}
if err != nil {
return
}
}
}
return

View File

@@ -638,6 +638,13 @@ func (s *sSysUser) CurrentUser(ctx context.Context) (userInfoOut *model.UserInfo
}
tmpUserAuthorize, err := cache.Instance().Get(ctx, consts.CacheUserAuthorize+"_"+gconv.String(loginUserId))
tmpUserInfo, err := cache.Instance().Get(ctx, consts.CacheUserInfo+"_"+gconv.String(loginUserId))
if err != nil {
return
}
if tmpUserAuthorize == nil || tmpUserInfo == nil {
err = gerror.New("无登录用户信息,请先登录!")
}
if tmpUserAuthorize.Val() != nil && tmpUserInfo.Val() != nil {
if err = json.Unmarshal([]byte(tmpUserAuthorize.Val().(string)), &menuTreeOut); err != nil {
return
@@ -843,13 +850,6 @@ func (s *sSysUser) CurrentUser(ctx context.Context) (userInfoOut *model.UserInfo
if menuApiErr != nil {
return
}
/*if menuApiInfo == nil {
err = gerror.New("未配置相关接口访问权限, 请联系系统管理员")
return
}*/
if err != nil {
return
}
var userMenuTreeOut []*model.UserMenuTreeOut

View File

@@ -16,6 +16,10 @@ func StartAction(ctx context.Context, deviceKey string) {
g.Log().Error(ctx, err)
return
}
if deviceRes == nil {
g.Log().Errorf(ctx, "deviceKey:%s not found,ignore", deviceKey)
return
}
deviceDetail := GetDevice(uint64(deviceRes.Id))
if deviceDetail != nil {
err = deviceDetail.Start(ctx)
@@ -23,7 +27,7 @@ func StartAction(ctx context.Context, deviceKey string) {
g.Log().Error(ctx, err)
return
} else {
if deviceRes != nil && deviceRes.Status != consts.DeviceStatueOnline {
if deviceRes.Status != consts.DeviceStatueOnline {
if deviceOnlineErr := baseLogic.Online(ctx, model.DeviceOnlineMessage{
DeviceKey: deviceRes.DevDevice.Key,
ProductKey: deviceRes.Product.Key,
@@ -50,7 +54,7 @@ func OffAction(ctx context.Context, tunnelId int) {
if deviceStopError := GetDevice(uint64(deviceDetail.Id)).Stop(); deviceStopError != nil {
g.Log().Errorf(ctx, "Stop device error:%v ,ignore", deviceStopError)
}
if deviceDetail != nil && deviceDetail.Status == consts.DeviceStatueOnline {
if deviceDetail.Status == consts.DeviceStatueOnline {
if deviceOnlineErr := baseLogic.Offline(ctx, model.DeviceOfflineMessage{
DeviceKey: tunnelInfo.DeviceKey,
ProductKey: deviceDetail.Product.Key,

View File

@@ -33,7 +33,7 @@ func ServerTunnelAction(ctx context.Context, serverId int, deviceKey string) {
if err != nil {
g.Log().Error(ctx, err)
}
if deviceDetail != nil && deviceDetail.Status != consts.DeviceStatueOnline {
if deviceDetail.Status != consts.DeviceStatueOnline {
if dataBusOfflineErr := baseLogic.Online(ctx, model.DeviceOnlineMessage{
DeviceKey: deviceKey,
ProductKey: deviceDetail.Product.Key,

View File

@@ -47,7 +47,7 @@ func TunnelOnlineAction(ctx context.Context, serverId int, tunnelId string, devi
g.Log().Error(ctx, err)
return
} else {
if deviceRes != nil && deviceRes.Status != consts.DeviceStatueOnline {
if deviceRes.Status != consts.DeviceStatueOnline {
if dataBusOfflineErr := baseLogic.Online(ctx, model.DeviceOnlineMessage{
DeviceKey: deviceRes.DevDevice.Key,
ProductKey: deviceRes.Product.Key,
@@ -72,7 +72,7 @@ func TunnelOfflineAction(ctx context.Context, serverId int, tunnelId, deviceKey
if deviceStopError := device.GetDevice(uint64(deviceDetail.Id)).Stop(); deviceStopError != nil {
g.Log().Errorf(ctx, "Stop device error:%v ,ignore", deviceStopError)
}
if deviceDetail != nil && deviceDetail.Status == consts.DeviceStatueOnline {
if deviceDetail.Status == consts.DeviceStatueOnline {
if offlineErr := baseLogic.Offline(ctx, model.DeviceOfflineMessage{
DeviceKey: deviceKey,
ProductKey: deviceDetail.Product.Key,

View File

@@ -112,12 +112,16 @@ func (l *TunnelBase) ReadData(ctx context.Context, deviceKey string, data []byte
g.Log().Errorf(ctx, "get deviceInfo error: %v, deviceKey:%s, message ignored", err, deviceKey)
return
}
if deviceDetail == nil {
g.Log().Errorf(ctx, "deviceKey:%s not found,ignore", deviceKey)
return
}
productDetail, productDetailErr := service.DevProduct().Detail(ctx, deviceDetail.Product.Key)
if productDetailErr != nil || productDetail == nil {
g.Log().Errorf(ctx, "find product info error: %v, productKey:%s, message ignored", productDetailErr, deviceDetail.Product.Key)
return
}
if deviceDetail != nil && deviceDetail.Status != consts.DeviceStatueOnline {
if deviceDetail.Status != consts.DeviceStatueOnline {
if deviceOnlineErr := baseLogic.Online(ctx, networkModel.DeviceOnlineMessage{
DeviceKey: deviceKey,
ProductKey: deviceDetail.Product.Key,

View File

@@ -87,6 +87,10 @@ func (client *TunnelClient) receive(ctx context.Context) {
if tunnelInfoErr != nil {
_ = mqtt.Publish(consts.GetWrapperTopic(consts.DataBusTunnel, consts.ActionError, strconv.Itoa(int(client.tunnelInfo.Id))), []byte(tunnelInfoErr.Error()))
} else {
if tunnelInfo == nil {
return
}
onlineErr := action.TunnelOnlineAction(ctx, 0, strconv.Itoa(int(client.tunnelInfo.Id)), tunnelInfo.DeviceKey)
if onlineErr != nil {
g.Log().Errorf(ctx, "tunnel online error: %v", onlineErr)

View File

@@ -126,8 +126,8 @@ func offline(ctx context.Context, device *model.DeviceOutput) (err error) {
Status: "offline",
CreateTime: gtime.Now().Unix(),
}
if err == nil {
err = service.AlarmRule().Check(ctx, device.ProductKey, device.Key, consts.AlarmTriggerTypeOffline, data)
}
err = service.AlarmRule().Check(ctx, device.ProductKey, device.Key, consts.AlarmTriggerTypeOffline, data)
return
}

View File

@@ -93,13 +93,6 @@ func getRedisManager(options redisOptions) *RedisManager {
time.Sleep(1 * time.Second)
}
// 如果经过重试后仍然失败,处理错误(或退出程序)
if err != nil {
// 这里可以记录错误、返回nil或退出程序
fmt.Printf("Failed to connect to Redis after retries: %v\n", err)
return nil
}
return &RedisManager{
client: client,
recordDuration: recordDuration,

View File

@@ -100,12 +100,14 @@ func ListByPage(ctx context.Context, dataModel *gdb.Model, req *SelectReq, vague
countModel := dataModel
totalData, err := countModel.All()
res.Total = totalData.Len()
if err != nil {
glog.Debug(ctx, err)
err = gerror.New("获取总行数失败")
return
}
res.Total = totalData.Len()
if req.PageNum == 0 {
req.PageNum = 1
}

View File

@@ -158,9 +158,13 @@ func (m *Manager) StartPlugin(id string) (err error) {
Plugins: m.pluginMap(id),
Cmd: exec.Command(path),
})
if err != nil {
g.Log().Error(context.Background(), id, "插件加载出错", err.Error())
if p == nil {
p = &PluginInfo{
ID: id,
Path: path,
}
}
p.Client = client
g.Log().Debugf(context.Background(), "注册插件 type=%s, id=%s, impl=%s", m.Type, id, p.Path)

View File

@@ -20,6 +20,7 @@ func TestDatabaseFactory(t *testing.T) {
if td == nil {
t.Error(errors.New("factory err"))
return
}
td.Close()
t.Log("创建 Tdengine 数据库实例成功")
@@ -33,9 +34,7 @@ func TestDatabaseFactory(t *testing.T) {
}
// 使用工厂函数创建 Influxdb 数据库实例
idb := DatabaseFactory(comm.DBInfluxdb, option2)
if td == nil {
t.Error(errors.New("factory err"))
}
idb.Close()
t.Log("创建 Influxdb 数据库实例成功")
}

View File

@@ -60,9 +60,6 @@ func (nx Nx) tryLock(ctx context.Context) (bool, error) {
cmd := nx.ops.redis.SetNX(ctx, nx.ops.key, 1, time.Duration(nx.ops.expire)*time.Second)
_, err := cmd.Result()
if err != nil {
if err == nil || err.Error() == "redis: nil" {
return false, nil
}
return false, err
}
return true, nil

View File

@@ -222,7 +222,7 @@ func (wk Worker) Once(options ...func(*RunOptions)) (err error) {
_, err = wk.client.Enqueue(t, taskOpts...)
if ops.replace && errors.Is(err, asynq.ErrTaskIDConflict) {
// remove old one if replace = true
ctx := wk.getDefaultTimeoutCtx()
ctx, _ := wk.getDefaultTimeoutCtx()
if ops.ctx != nil {
ctx = ops.ctx
}
@@ -260,7 +260,7 @@ func (wk Worker) Cron(options ...func(*RunOptions)) (err error) {
MaxRetry: ops.maxRetry,
Timeout: ops.timeout,
}
ctx := wk.getDefaultTimeoutCtx()
ctx, _ := wk.getDefaultTimeoutCtx()
res, err := wk.redis.HGet(ctx, wk.ops.redisPeriodKey, ops.uid).Result()
if err == nil {
var oldT periodTask
@@ -315,7 +315,7 @@ func (wk Worker) processed(ctx context.Context, uid string) {
// scan 扫描并处理任务队列
func (wk Worker) scan() {
ctx := wk.getDefaultTimeoutCtx()
ctx, _ := wk.getDefaultTimeoutCtx()
ok := wk.lock.Lock()
if !ok {
return
@@ -372,7 +372,7 @@ func (wk Worker) clearArchived() {
if err != nil {
return
}
ctx := wk.getDefaultTimeoutCtx()
ctx, _ := wk.getDefaultTimeoutCtx()
for _, item := range list {
last := carbon.CreateFromStdTime(item.LastFailedAt)
if !last.IsZero() && item.Retried < item.MaxRetry {
@@ -422,9 +422,15 @@ func (wk Worker) clearArchived() {
}
// getDefaultTimeoutCtx 获取带有默认超时的上下文
func (wk Worker) getDefaultTimeoutCtx() context.Context {
c, _ := context.WithTimeout(context.Background(), time.Duration(wk.ops.timeout)*time.Second)
return c
func (wk Worker) getDefaultTimeoutCtx() (context.Context, context.CancelFunc) {
// 确保 timeout 合法,防止负值或过大值造成意外行为
timeoutSec := wk.ops.timeout
if timeoutSec <= 0 {
timeoutSec = 50 // 可选:使用默认值兜底
}
timeoutDuration := time.Duration(timeoutSec) * time.Second
return context.WithTimeout(context.Background(), timeoutDuration)
}
// getNext 计算下一次执行时间

View File

@@ -58,9 +58,6 @@ func TestProtocolEncode(t *testing.T) {
var reqData = model.DataReq{}
reqData.Data = gconv.Bytes(td)
res := p.Encode(reqData)
if err != nil {
t.Fatal(err.Error())
}
t.Log(res)
}
@@ -74,9 +71,7 @@ func TestProtocol(t *testing.T) {
var dr model.DataReq
dr.Data = data
res := p.Decode(dr)
if err != nil {
t.Fatal(err.Error())
}
t.Log(res)
}