From 26f46f1eb620d9eacc15f201ecfbf48df605c68a Mon Sep 17 00:00:00 2001 From: tianjun Date: Wed, 18 Jan 2023 17:46:25 +0800 Subject: [PATCH] import cycle not allowed --- main.go | 4 +- modules/core/api/v1/user_api.go | 9 +- modules/core/dao/config_dao.go | 21 +-- modules/core/dao/cron_job_dao.go | 16 +-- modules/core/dao/dept_dao.go | 18 +-- modules/core/dao/dict_data_dao.go | 15 ++- modules/core/dao/dict_type_dao.go | 16 +-- modules/core/dao/log_dao.go | 6 +- modules/core/dao/login_info_dao.go | 6 +- modules/core/dao/menu_dao.go | 22 ++-- modules/core/dao/notice_dao.go | 12 +- modules/core/dao/post_dao.go | 18 +-- modules/core/dao/role_dao.go | 26 ++-- modules/core/dao/role_menu_dao.go | 6 +- modules/core/dao/user_dao.go | 26 ++-- modules/core/dao/user_post_dao.go | 8 +- modules/core/dao/user_role_dao.go | 10 +- modules/core/service/login_service.go | 6 +- modules/demo/dao/student_dao.go | 18 +++ pkg/cache/index.go | 13 +- pkg/common/index.go | 166 ------------------------ pkg/config/index.go | 117 ++++++++++++++++- pkg/cronjob/index.go | 20 +-- pkg/gin/index.go | 5 +- pkg/{common/log.go => logging/index.go} | 2 +- pkg/middleware/logger/logger.go | 9 +- pkg/middleware/recover.go | 4 +- pkg/page/page.go | 4 +- pkg/redispool/index.go | 11 +- pkg/util/my_util.go | 43 ++++++ pkg/util/struct_util.go | 4 +- pkg/util/token_util.go | 6 +- pkg/websocket/index.go | 12 +- refs/database.go | 10 +- refs/redis.go | 7 +- 35 files changed, 355 insertions(+), 341 deletions(-) create mode 100644 modules/demo/dao/student_dao.go delete mode 100644 pkg/common/index.go rename pkg/{common/log.go => logging/index.go} (97%) diff --git a/main.go b/main.go index 0e95ccd..f36a3f6 100644 --- a/main.go +++ b/main.go @@ -2,10 +2,10 @@ package main // init函数执行顺序自上而下, 最后执行main包里面的init函数 import ( - "cutego/pkg/common" "cutego/pkg/config" _ "cutego/pkg/cronjob" _ "cutego/pkg/gin" + "cutego/pkg/logging" "cutego/pkg/util" "cutego/refs" "fmt" @@ -17,7 +17,7 @@ func main() { gin.SetMode(util.IF(config.AppEnvConfig.Server.RunMode == "", "debug", config.AppEnvConfig.Server.RunMode).(string)) err := refs.CoolGin.Run(fmt.Sprintf(":%d", config.AppEnvConfig.Server.Port)) if err != nil { - common.FatalfLog("Start server: %+v", err) + logging.FatalfLog("Start server: %+v", err) } } diff --git a/modules/core/api/v1/user_api.go b/modules/core/api/v1/user_api.go index 8e2592a..731aa17 100644 --- a/modules/core/api/v1/user_api.go +++ b/modules/core/api/v1/user_api.go @@ -7,6 +7,7 @@ import ( "cutego/modules/core/service" "cutego/pkg/common" "cutego/pkg/excels" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/pkg/resp" "cutego/pkg/util" @@ -92,7 +93,7 @@ func (a UserApi) AuthRole(c *gin.Context) { userId := c.Param("userId") parseInt, err := strconv.ParseInt(userId, 10, 64) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) c.JSON(http.StatusInternalServerError, resp.ErrorResp(err)) } user := a.userService.GetUserById(parseInt) @@ -173,7 +174,7 @@ func (a UserApi) Remove(c *gin.Context) { param := c.Param("userId") userId, err := strconv.ParseInt(param, 10, 64) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) c.JSON(http.StatusInternalServerError, resp.ErrorResp("参数错误")) return } @@ -293,13 +294,13 @@ func (a UserApi) Avatar(c *gin.Context) { fileAppend, err := gotool.FileUtils.OpenFileAppend(filePath) defer fileAppend.Close() if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) resp.Error(c) return } _, err = io.Copy(fileAppend, file) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) resp.Error(c) return } diff --git a/modules/core/dao/config_dao.go b/modules/core/dao/config_dao.go index 6ca1d77..3d80530 100644 --- a/modules/core/dao/config_dao.go +++ b/modules/core/dao/config_dao.go @@ -5,6 +5,7 @@ import ( "cutego/modules/core/dataobject" "cutego/pkg/common" "cutego/pkg/constant" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -23,7 +24,7 @@ func (d ConfigDao) SelectByConfigKey(configKey string) *dataobject.SysConfig { config := dataobject.SysConfig{} _, err := d.sql(refs.SqlDB.NewSession()).Where("config_key = ?", configKey).Get(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &config @@ -51,7 +52,7 @@ func (d ConfigDao) SelectPage(query request.ConfigQuery) (*[]dataobject.SysConfi total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return &configs, total @@ -65,7 +66,7 @@ func (d ConfigDao) CheckConfigKeyUnique(config dataobject.SysConfig) int64 { } count, err := session.And("config_key = ?", config.ConfigKey).Cols("config_id").Count() if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } return count @@ -77,7 +78,7 @@ func (d ConfigDao) Insert(config dataobject.SysConfig) int64 { session.Begin() insert, err := session.Insert(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -91,7 +92,7 @@ func (d ConfigDao) SelectById(id int64) *dataobject.SysConfig { session := d.sql(refs.SqlDB.NewSession()) _, err := session.Where("config_id = ?", id).Get(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &config @@ -103,7 +104,7 @@ func (d ConfigDao) Update(config dataobject.SysConfig) int64 { session.Begin() update, err := session.Where("config_id = ?", config.ConfigId).Update(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -116,7 +117,7 @@ func (d ConfigDao) CheckConfigByIds(list []int64) *[]dataobject.SysConfig { configs := make([]dataobject.SysConfig, 0) err := d.sql(refs.SqlDB.NewSession()).In("config_id", list).Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &configs @@ -128,7 +129,7 @@ func (d ConfigDao) Delete(list []int64) bool { session.Begin() _, err := session.In("config_id", list).Delete(&dataobject.SysConfig{}) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return false } @@ -142,7 +143,7 @@ func (d ConfigDao) SelectAll() *[]dataobject.SysConfig { session := refs.SqlDB.NewSession() err := session.Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &configs @@ -155,7 +156,7 @@ func init() { configs := make([]*dataobject.SysConfig, 0) err := configSession.Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return } for _, sysConfig := range configs { diff --git a/modules/core/dao/cron_job_dao.go b/modules/core/dao/cron_job_dao.go index afdf510..94ddecb 100644 --- a/modules/core/dao/cron_job_dao.go +++ b/modules/core/dao/cron_job_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -30,7 +30,7 @@ func (d CronJobDao) SelectPage(query request.CronJobQuery) ([]dataobject.SysCron total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return configs, total @@ -42,7 +42,7 @@ func (d CronJobDao) Insert(config dataobject.SysCronJob) int64 { session.Begin() insert, err := session.Insert(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -56,7 +56,7 @@ func (d CronJobDao) SelectById(id int64) *dataobject.SysCronJob { session := d.sql(refs.SqlDB.NewSession()) _, err := session.Where("job_id = ?", id).Get(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &config @@ -68,7 +68,7 @@ func (d CronJobDao) Update(config dataobject.SysCronJob) int64 { session.Begin() update, err := session.Where("job_id = ?", config.JobId).Update(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -82,7 +82,7 @@ func (d CronJobDao) Delete(list []int64) bool { session.Begin() _, err := session.In("job_id", list).Delete(&dataobject.SysCronJob{}) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return false } @@ -96,7 +96,7 @@ func (d CronJobDao) SelectByFuncAlias(funcAlias string) *dataobject.SysCronJob { session := d.sql(refs.SqlDB.NewSession()) _, err := session.Where("func_alias = ?", funcAlias).Get(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &config @@ -108,7 +108,7 @@ func (d CronJobDao) SelectAll() ([]dataobject.SysCronJob, int) { session := d.sql(refs.SqlDB.NewSession()) err := session.Where("status = ?", 1).Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return configs, len(configs) diff --git a/modules/core/dao/dept_dao.go b/modules/core/dao/dept_dao.go index 5882ead..af0a37a 100644 --- a/modules/core/dao/dept_dao.go +++ b/modules/core/dao/dept_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/refs" "github.com/druidcaesa/gotool" ) @@ -26,7 +26,7 @@ func (d DeptDao) SelectTree(query request.DeptQuery) *[]dataobject.SysDept { } err := session.OrderBy("parent_id").OrderBy("order_num").Find(&depts) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &depts @@ -43,7 +43,7 @@ func (d DeptDao) SelectDeptListByRoleId(id int64, strictly bool) *[]int64 { } err := session.OrderBy("d.parent_id").OrderBy("d.order_num").Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &list @@ -65,7 +65,7 @@ func (d DeptDao) GetList(query request.DeptQuery) *[]dataobject.SysDept { } err := session.Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &list @@ -76,7 +76,7 @@ func (d DeptDao) SelectDeptById(id int) *dataobject.SysDept { dept := dataobject.SysDept{} _, err := refs.SqlDB.NewSession().Where("dept_id = ?", id).Get(&dept) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &dept @@ -88,7 +88,7 @@ func (d DeptDao) Insert(dept dataobject.SysDept) int64 { session.Begin() insert, err := session.Insert(&dept) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -101,7 +101,7 @@ func (d DeptDao) CheckDeptNameUnique(dept dataobject.SysDept) int64 { session := refs.SqlDB.NewSession() count, err := session.Table("sys_dept").Cols("dept_id").Where("dept_name=?", dept.DeptName).And("parent_id = ?", dept.ParentId).Limit(1).Count() if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return 1 } return count @@ -132,7 +132,7 @@ func (d DeptDao) Delete(id int) int64 { i, err := session.Where("dept_id = ?", id).Delete(&dept) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -146,7 +146,7 @@ func (d DeptDao) Update(dept dataobject.SysDept) int64 { update, err := session.Where("dept_id = ?", dept.DeptId).Update(&dept) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() diff --git a/modules/core/dao/dict_data_dao.go b/modules/core/dao/dict_data_dao.go index e2f6c10..1c66369 100644 --- a/modules/core/dao/dict_data_dao.go +++ b/modules/core/dao/dict_data_dao.go @@ -5,6 +5,7 @@ import ( "cutego/modules/core/dataobject" "cutego/pkg/common" "cutego/pkg/constant" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -27,7 +28,7 @@ func (d *DictDataDao) SelectByDictType(dictType string) []dataobject.SysDictData err := session.Where("status = '0' ").And("dict_type = ?", dictType).OrderBy("dict_sort").Asc("dict_sort"). Find(&data) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return data @@ -41,7 +42,7 @@ func (d DictDataDao) GetDiceDataAll() *[]dataobject.SysDictData { err := session.Where("status = '0' ").OrderBy("dict_sort").Asc("dict_sort"). Find(&data) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &data @@ -66,7 +67,7 @@ func (d *DictDataDao) SelectPage(query request.DiceDataQuery) (*[]dataobject.Sys total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return &list, total @@ -80,7 +81,7 @@ func (d *DictDataDao) SelectByDictCode(dictCode int64) *dataobject.SysDictData { session := refs.SqlDB.NewSession() _, err := session.Where("dict_code = ?", dictCode).Get(&data) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &data @@ -95,7 +96,7 @@ func (d *DictDataDao) Insert(data dataobject.SysDictData) int64 { insert, err := session.Insert(&data) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -108,7 +109,7 @@ func (d *DictDataDao) Delete(codes []int64) bool { session.Begin() _, err := session.In("dict_code", codes).Delete(&dataobject.SysDictData{}) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return false } @@ -123,7 +124,7 @@ func (d *DictDataDao) Update(data dataobject.SysDictData) bool { _, err := session.Where("dict_code = ?", data.DictCode).Update(&data) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return false } session.Commit() diff --git a/modules/core/dao/dict_type_dao.go b/modules/core/dao/dict_type_dao.go index b25145d..5f2e0df 100644 --- a/modules/core/dao/dict_type_dao.go +++ b/modules/core/dao/dict_type_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -22,7 +22,7 @@ func (d DictTypeDao) SelectAll() []*dataobject.SysDictType { types := make([]*dataobject.SysDictType, 0) err := d.sql(refs.SqlDB.NewSession()).Where("status = '0'").Find(&types) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return types @@ -50,7 +50,7 @@ func (d DictTypeDao) SelectPage(query request.DictTypeQuery) (*[]dataobject.SysD total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return &list, total @@ -61,7 +61,7 @@ func (d DictTypeDao) SelectById(id int64) *dataobject.SysDictType { dictType := dataobject.SysDictType{} _, err := refs.SqlDB.NewSession().Where("dict_id = ?", id).Get(&dictType) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &dictType @@ -75,7 +75,7 @@ func (d DictTypeDao) CheckDictTypeUnique(dictType dataobject.SysDictType) int64 } count, err := session.Where("dict_type = ?", dictType.DictType).Cols("dict_id").Count() if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } return count @@ -87,7 +87,7 @@ func (d DictTypeDao) Update(dictType dataobject.SysDictType) bool { session.Begin() _, err := session.Where("dict_id = ?", dictType.DictId).Update(&dictType) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return false } @@ -101,7 +101,7 @@ func (d DictTypeDao) Insert(dictType dataobject.SysDictType) int64 { session.Begin() insert, err := session.Insert(&dictType) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -116,7 +116,7 @@ func (d DictTypeDao) Delete(ids []int64) bool { _, err := session.In("dict_id", ids).Delete(dataobject.SysDictType{}) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return false } session.Commit() diff --git a/modules/core/dao/log_dao.go b/modules/core/dao/log_dao.go index dede4a3..b3f15a4 100644 --- a/modules/core/dao/log_dao.go +++ b/modules/core/dao/log_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -30,7 +30,7 @@ func (d LogDao) SelectPage(query request.LogQuery) ([]dataobject.SysLog, int64) total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&configs) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return configs, total @@ -42,7 +42,7 @@ func (d LogDao) Insert(config dataobject.SysLog) int64 { session.Begin() insert, err := session.Insert(&config) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } diff --git a/modules/core/dao/login_info_dao.go b/modules/core/dao/login_info_dao.go index 3b99d3b..d9bab70 100644 --- a/modules/core/dao/login_info_dao.go +++ b/modules/core/dao/login_info_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/go-xorm/xorm" @@ -25,7 +25,7 @@ func (d LoginInfoDao) SelectPage(query request.LoginInfoQuery) (*[]dataobject.Sy total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&loginInfos) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return &loginInfos, total @@ -37,7 +37,7 @@ func (d LoginInfoDao) Insert(body dataobject.SysLoginInfo) *dataobject.SysLoginI session.Begin() _, err := session.Table("sys_login_info").Insert(&body) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() diff --git a/modules/core/dao/menu_dao.go b/modules/core/dao/menu_dao.go index cf42c53..51985b3 100644 --- a/modules/core/dao/menu_dao.go +++ b/modules/core/dao/menu_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/refs" "github.com/druidcaesa/gotool" ) @@ -21,7 +21,7 @@ func (d MenuDao) GetMenuPermission(id int64) *[]string { Join("LEFT", []string{"sys_role", "r"}, "r.role_id = ur.role_id"). Where("m.status = '0'").And("r.status = '0'").And("ur.user_id = ?", id).Find(&perms) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &perms @@ -34,7 +34,7 @@ func (d MenuDao) GetMenuAll() *[]dataobject.SysMenu { err := session.Distinct("m.menu_id").Cols("m.parent_id", "m.menu_name", "m.path", "m.component", "m.visible", "m.status", "m.perms", "m.is_frame", "m.is_cache", "m.menu_type", "m.icon", "m.order_num", "m.create_time"). Where("m.menu_type in ('M', 'C')").And("m.status = 0").OrderBy("m.parent_id").OrderBy("m.order_num").Find(&menus) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &menus @@ -51,7 +51,7 @@ func (d MenuDao) GetMenuByUserId(id int64) *[]dataobject.SysMenu { Join("LEFT", []string{"sys_user", "u"}, "ur.user_id = u.user_id").Where("u.user_id = ?", id). And("m.menu_type in ('M', 'C')").And("m.status = 0").OrderBy("m.parent_id").OrderBy("m.order_num").Find(&menus) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &menus @@ -68,7 +68,7 @@ func (d MenuDao) SelectMenuByRoleId(id int64, strictly bool) *[]int64 { } err := session.OrderBy("m.parent_id").OrderBy("m.order_num").Cols("m.menu_id").Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &list @@ -89,7 +89,7 @@ func (d MenuDao) SelectMenuList(query request.MenuQuery) *[]dataobject.SysMenu { } err := session.Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &list @@ -115,7 +115,7 @@ func (d MenuDao) SelectMenuListByUserId(query request.MenuQuery) *[]dataobject.S } err := session.Find(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &list @@ -128,7 +128,7 @@ func (d MenuDao) SelectMenuByMenuId(id int) *dataobject.SysMenu { } _, err := refs.SqlDB.NewSession().Where("menu_id = ?", menu.MenuId).Get(&menu) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &menu @@ -140,7 +140,7 @@ func (d MenuDao) Insert(menu dataobject.SysMenu) int64 { session.Begin() insert, err := session.Insert(&menu) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -154,7 +154,7 @@ func (d MenuDao) Update(menu dataobject.SysMenu) int64 { session.Begin() update, err := session.Where("menu_id = ?", menu.MenuId).Update(&menu) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -171,7 +171,7 @@ func (d MenuDao) Delete(id int) int64 { session.Begin() i, err := session.Delete(&menu) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } diff --git a/modules/core/dao/notice_dao.go b/modules/core/dao/notice_dao.go index cf12080..4876b09 100644 --- a/modules/core/dao/notice_dao.go +++ b/modules/core/dao/notice_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -28,7 +28,7 @@ func (d NoticeDao) SelectPage(query request.NoticeQuery) (*[]dataobject.SysNotic total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(¬ices) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return ¬ices, total @@ -41,7 +41,7 @@ func (d NoticeDao) Insert(notice dataobject.SysNotice) int64 { insert, err := session.Insert(¬ice) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -55,7 +55,7 @@ func (d NoticeDao) Delete(list []int64) int64 { i, err := session.In("notice_id", list).Delete(&dataobject.SysNotice{}) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -67,7 +67,7 @@ func (d NoticeDao) SelectById(id int64) *dataobject.SysNotice { notice := dataobject.SysNotice{} _, err := refs.SqlDB.NewSession().Where("notice_id = ?", id).Get(¬ice) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return ¬ice @@ -80,7 +80,7 @@ func (d NoticeDao) Update(notice dataobject.SysNotice) int64 { update, err := session.Where("notice_id = ?", notice.NoticeId).Update(¬ice) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() diff --git a/modules/core/dao/post_dao.go b/modules/core/dao/post_dao.go index 716d29e..6ba9380 100644 --- a/modules/core/dao/post_dao.go +++ b/modules/core/dao/post_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -25,7 +25,7 @@ func (d PostDao) SelectAll() []*dataobject.SysPost { posts := make([]*dataobject.SysPost, 0) err := session.Find(&posts) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return posts @@ -37,7 +37,7 @@ func (d PostDao) SelectPostListByUserId(userId int64) *[]int64 { selectSql := d.sqlSelectJoin(refs.SqlDB.NewSession()) err := selectSql.Where("u.user_id = ?", userId).Cols("p.post_id").Find(&ids) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &ids @@ -59,7 +59,7 @@ func (d PostDao) SelectPage(query request.PostQuery) (*[]dataobject.SysPost, int total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&posts) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return &posts, total @@ -94,7 +94,7 @@ func (d PostDao) Insert(post dataobject.SysPost) int64 { insert, err := session.Insert(&post) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -105,7 +105,7 @@ func (d PostDao) Insert(post dataobject.SysPost) int64 { func (d PostDao) GetPostById(post dataobject.SysPost) *dataobject.SysPost { _, err := refs.SqlDB.NewSession().Where("post_id = ?", post.PostId).Get(&post) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &post @@ -119,7 +119,7 @@ func (d PostDao) Delete(posts []int64) int64 { i, err := session.In("post_id", posts).Delete(&dataobject.SysPost{}) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -133,7 +133,7 @@ func (d PostDao) Update(post dataobject.SysPost) bool { _, err := session.Where("post_id = ?", post.PostId).Update(&post) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return false } session.Commit() @@ -147,7 +147,7 @@ func (d PostDao) SelectPostByUserName(name string) *[]dataobject.SysPost { Join("LEFT", []string{"sys_user_post", "up"}, "up.post_id = p.post_id"). Join("LEFT", []string{"sys_user", "u"}, "u.user_id = up.user_id").Where("u.user_name = ?", name).Find(&posts) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &posts diff --git a/modules/core/dao/role_dao.go b/modules/core/dao/role_dao.go index 17e4eaf..d59498e 100644 --- a/modules/core/dao/role_dao.go +++ b/modules/core/dao/role_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -61,7 +61,7 @@ func (d RoleDao) SelectAll() []*dataobject.SysRole { roles := make([]*dataobject.SysRole, 0) err := sql.Find(&roles) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return roles @@ -73,7 +73,7 @@ func (d RoleDao) SelectRoleListByUserId(userId int64) *[]int64 { var roleIds []int64 err := sqlSelectRoleAndUser.Cols("r.role_id").Where("u.user_id = ?", userId).Find(&roleIds) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &roleIds @@ -84,7 +84,7 @@ func (d RoleDao) SelectRolePermissionByUserId(id int64) *[]string { var roleKeys []string err := d.sqlSelectJoin().Cols("r.role_key").Where("r.del_flag = '0'").And("ur.user_id = ?", id).Find(&roleKeys) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &roleKeys @@ -95,7 +95,7 @@ func (d RoleDao) GetRoleListByUserId(id int64) *[]dataobject.SysRole { roles := make([]dataobject.SysRole, 0) err := d.sqlSelectJoin().Where("r.del_flag = '0'").And("ur.user_id = ?", id).Find(&roles) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &roles @@ -106,7 +106,7 @@ func (d RoleDao) SelectRoleByRoleId(id int64) *dataobject.SysRole { role := dataobject.SysRole{} _, err := d.sqlSelectJoin().Where("r.role_id = ?", id).Get(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &role @@ -120,7 +120,7 @@ func (d RoleDao) CheckRoleNameUnique(role dataobject.SysRole) int64 { } count, err := session.Count(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } return count } @@ -133,7 +133,7 @@ func (d RoleDao) CheckRoleKeyUnique(role dataobject.SysRole) int64 { } count, err := session.Count(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } return count } @@ -144,7 +144,7 @@ func (d RoleDao) Insert(role dataobject.SysRole) dataobject.SysRole { session.Begin() _, err := session.Insert(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() @@ -157,7 +157,7 @@ func (d RoleDao) Update(role dataobject.SysRole) int64 { session.Begin() update, err := session.Where("role_id = ?", role.RoleId).Update(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -171,7 +171,7 @@ func (d RoleDao) Delete(role dataobject.SysRole) int64 { session.Begin() i, err := session.Delete(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -185,7 +185,7 @@ func (d RoleDao) UpdateRoleStatus(role *dataobject.SysRole) int64 { session.Begin() update, err := session.Where("role_id = ?", role.RoleId).Cols("status", "update_by", "update_time").Update(role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -199,7 +199,7 @@ func (d RoleDao) SelectRolesByUserName(name string) *[]dataobject.SysRole { session := d.sqlSelectJoin() err := session.Where("r.del_flag = '0'").And("u.user_name = ?", name).Find(&roles) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } return &roles diff --git a/modules/core/dao/role_menu_dao.go b/modules/core/dao/role_menu_dao.go index f9978db..8b7d20e 100644 --- a/modules/core/dao/role_menu_dao.go +++ b/modules/core/dao/role_menu_dao.go @@ -2,7 +2,7 @@ package dao import ( "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/refs" ) @@ -15,7 +15,7 @@ func (d RoleMenuDao) Insert(list []dataobject.SysRoleMenu) int64 { session.Begin() insert, err := session.Insert(&list) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() @@ -31,7 +31,7 @@ func (d RoleMenuDao) Delete(role dataobject.SysRole) { session.Begin() _, err := session.Delete(&menu) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() diff --git a/modules/core/dao/user_dao.go b/modules/core/dao/user_dao.go index 3c0b654..fcc9203 100644 --- a/modules/core/dao/user_dao.go +++ b/modules/core/dao/user_dao.go @@ -4,7 +4,7 @@ import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/api/v1/response" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/pkg/page" "cutego/refs" "github.com/druidcaesa/gotool" @@ -48,7 +48,7 @@ func (d UserDao) SelectPage(query request.UserQuery) ([]*response.UserResponse, total, _ := page.GetTotal(sql.Clone()) err := sql.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&resp) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return resp, total @@ -59,7 +59,7 @@ func (d UserDao) GetUserById(userId int64) *response.UserResponse { var resp response.UserResponse get, err := d.sqlSelectJoin().Where("u.user_id = ?", userId).Get(&resp) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } if !get { return nil @@ -71,7 +71,7 @@ func (d UserDao) GetUserById(userId int64) *response.UserResponse { func (d UserDao) GetUserByUserName(user dataobject.SysUser) *dataobject.SysUser { i, err := refs.SqlDB.Get(&user) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil } if i { @@ -118,7 +118,7 @@ func (d UserDao) Insert(body request.UserBody) *request.UserBody { session.Begin() _, err := session.Table("sys_user").Insert(&body) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() @@ -132,7 +132,7 @@ func (d UserDao) Update(body request.UserBody) int64 { _, err := session.Where("user_id = ?", body.UserId).Update(&body) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -148,7 +148,7 @@ func (d UserDao) Delete(id int64) int64 { session.Begin() i, err := session.Delete(&user) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() @@ -165,7 +165,7 @@ func (d UserDao) ResetPwd(body request.UserBody) int64 { session.Begin() _, err := session.Where("user_id = ?", user.UserId).Cols("password").Update(&user) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -190,7 +190,7 @@ func (d UserDao) GetAllocatedList(query request.UserQuery) ([]*response.UserResp total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&resp) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return resp, total @@ -214,7 +214,7 @@ func (d UserDao) GetUnallocatedList(query request.UserQuery) ([]*response.UserRe total, _ := page.GetTotal(session.Clone()) err := session.Limit(query.PageSize, page.StartSize(query.PageNum, query.PageSize)).Find(&resp) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return nil, 0 } return resp, total @@ -229,7 +229,7 @@ func (d UserDao) UpdatePwd(id int64, hash string) int64 { session.Begin() update, err := session.Cols("password").Where("user_id = ?", id).Update(&user) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -250,7 +250,7 @@ func (d UserDao) UpdateAvatar(info *response.UserResponse) int64 { update, err := session.Cols("avatar", "update_by", "update_time").Where("user_id = ?", user.UserId).Update(&user) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() @@ -269,7 +269,7 @@ func (d UserDao) UpdateStatus(info request.UserBody) int64 { update, err := session.Cols("status", "update_by", "update_time").Where("user_id = ?", user.UserId).Update(&user) if err != nil { session.Rollback() - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } session.Commit() diff --git a/modules/core/dao/user_post_dao.go b/modules/core/dao/user_post_dao.go index 680b96b..f4de5eb 100644 --- a/modules/core/dao/user_post_dao.go +++ b/modules/core/dao/user_post_dao.go @@ -2,7 +2,7 @@ package dao import ( "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/refs" ) @@ -15,7 +15,7 @@ func (d UserPostDao) BatchInsert(posts []dataobject.SysUserPost) { session.Begin() _, err := session.Table(dataobject.SysUserPost{}.TableName()).Insert(&posts) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return } @@ -31,7 +31,7 @@ func (d UserPostDao) Delete(id int64) { session.Begin() _, err := session.Delete(&post) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() } session.Commit() @@ -41,7 +41,7 @@ func (d UserPostDao) Delete(id int64) { func (d UserPostDao) CountById(id int64) int64 { count, err := refs.SqlDB.NewSession().Table("sys_user_post").Cols("post_id").Where("post_id = ?", id).Count() if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return 0 } return count diff --git a/modules/core/dao/user_role_dao.go b/modules/core/dao/user_role_dao.go index b8231fa..44d60ef 100644 --- a/modules/core/dao/user_role_dao.go +++ b/modules/core/dao/user_role_dao.go @@ -3,7 +3,7 @@ package dao import ( "cutego/modules/core/api/v1/request" "cutego/modules/core/dataobject" - "cutego/pkg/common" + "cutego/pkg/logging" "cutego/refs" ) @@ -16,7 +16,7 @@ func (d UserRoleDao) BatchInsert(roles []dataobject.SysUserRole) { session.Begin() _, err := session.Table(dataobject.SysUserRole{}.TableName()).Insert(&roles) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return } @@ -32,7 +32,7 @@ func (d UserRoleDao) Delete(id int64) { session.Begin() _, err := session.Delete(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return } @@ -45,7 +45,7 @@ func (d UserRoleDao) DeleteAuthUser(role dataobject.SysUserRole) int64 { session.Begin() i, err := session.Delete(&role) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } @@ -68,7 +68,7 @@ func (d UserRoleDao) InsertAuthUsers(body request.UserRoleBody) int64 { session.Begin() insert, err := session.Insert(&roles) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) session.Rollback() return 0 } diff --git a/modules/core/service/login_service.go b/modules/core/service/login_service.go index ce19c21..3561cb5 100644 --- a/modules/core/service/login_service.go +++ b/modules/core/service/login_service.go @@ -2,8 +2,8 @@ package service import ( "cutego/modules/core/api/v1/response" - "cutego/pkg/common" "cutego/pkg/jwt" + "cutego/pkg/logging" "github.com/druidcaesa/gotool" "github.com/gin-gonic/gin" "strings" @@ -25,7 +25,7 @@ func (s LoginService) Login(name string, password string) (bool, string) { // 生成token token, err := jwt.CreateUserToken(s.userService.GetUserById(user.UserId)) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return false, "" } // 数据存储到redis中 @@ -39,7 +39,7 @@ func (s LoginService) GetCurrentUser(c *gin.Context) *response.UserResponse { // parseToken 解析token包含的信息 claims, err := jwt.ParseToken(str[1]) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } info := claims.UserInfo return &info diff --git a/modules/demo/dao/student_dao.go b/modules/demo/dao/student_dao.go new file mode 100644 index 0000000..82d05d4 --- /dev/null +++ b/modules/demo/dao/student_dao.go @@ -0,0 +1,18 @@ +package dao + +import "cutego/modules/demo/dataobject" + +type StudentDao struct { +} + +// Insert 增加 +func (d StudentDao) Insert(record dataobject.Student) { + +} + +// 修改 +// 删除 +// 批量删除 +// 分页查询 +// 通过id查询 +// 通过属性查询 diff --git a/pkg/cache/index.go b/pkg/cache/index.go index f1afff1..1bcdb12 100644 --- a/pkg/cache/index.go +++ b/pkg/cache/index.go @@ -1,8 +1,9 @@ package cache import ( - "cutego/pkg/common" "cutego/pkg/constant" + "cutego/pkg/logging" + "cutego/pkg/util" "cutego/refs" ) @@ -18,7 +19,7 @@ func RemoveList(list []string) { func RemoveCache(key string) int { del, err := refs.RedisDB.DEL(key) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } return del } @@ -29,7 +30,7 @@ func RemoveCache(key string) int { func GetCache(key string) string { val, err := refs.RedisDB.GET(key) if err != nil { - common.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error()) + logging.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error()) return "" } return val @@ -40,9 +41,9 @@ func GetCache(key string) string { // @Param value 值 // @Return 新增的行数 func SetCache(key string, value interface{}) int { - n, err := refs.RedisDB.SET(key, common.StructToJson(value)) + n, err := refs.RedisDB.SET(key, util.StructToJson(value)) if err != nil { - common.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error()) + logging.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error()) return 0 } return int(n) @@ -54,5 +55,5 @@ func SetCache(key string, value interface{}) int { // @Param sec 过期时间(单位: 秒) // @Return 新增的行数 func SetCacheTTL(key string, value interface{}, sec int) { - refs.RedisDB.SETEX(key, sec, common.StructToJson(value)) + refs.RedisDB.SETEX(key, sec, util.StructToJson(value)) } diff --git a/pkg/common/index.go b/pkg/common/index.go deleted file mode 100644 index 83547fe..0000000 --- a/pkg/common/index.go +++ /dev/null @@ -1,166 +0,0 @@ -package common - -import ( - "cutego/pkg/config" - "encoding/json" - "fmt" - "os" - "runtime" - "strconv" -) - -// IntToString int转string -func IntToString(n int) string { - return strconv.Itoa(n) -} - -// StringToInt string转int -func StringToInt(s string) int { - i, err := strconv.Atoi(s) - if err != nil { - panic(err) - } - return i -} - -// StringToInt64 string转int64 -func StringToInt64(s string) int64 { - i, err := strconv.ParseInt(s, 10, 64) - if err != nil { - panic(err) - } - return i -} - -// Int64ToString int64转string -func Int64ToString(n int64) string { - return strconv.FormatInt(n, 10) -} - -func mapToBytes(data map[string]interface{}) []byte { - bytes, _ := json.Marshal(data) - return bytes -} - -// MapToStruct map转struct -func MapToStruct(data map[string]interface{}, v interface{}) { - _ = json.Unmarshal(mapToBytes(data), v) -} - -// GetDirPath 获取目录路径 -func GetDirPath(resType string) string { - sysType := runtime.GOOS - switch sysType { - case "linux": - if resType == "log" { - return config.AppCoreConfig.CuteGoConfig.File.Linux.Logs - } else if resType == "avatar" { - return config.AppCoreConfig.CuteGoConfig.File.Linux.Avatar - } else if resType == "file" { - return config.AppCoreConfig.CuteGoConfig.File.Linux.Path - } - break - case "windows": - if resType == "log" { - return config.AppCoreConfig.CuteGoConfig.File.Windows.Logs - } else if resType == "avatar" { - return config.AppCoreConfig.CuteGoConfig.File.Windows.Avatar - } else if resType == "file" { - return config.AppCoreConfig.CuteGoConfig.File.Windows.Path - } - break - case "mac": - if resType == "log" { - return config.AppCoreConfig.CuteGoConfig.File.Mac.Logs - } else if resType == "avatar" { - return config.AppCoreConfig.CuteGoConfig.File.Mac.Avatar - } else if resType == "file" { - return config.AppCoreConfig.CuteGoConfig.File.Mac.Path - } - break - case "darwin": - if resType == "log" { - return config.AppCoreConfig.CuteGoConfig.File.Mac.Logs - } else if resType == "avatar" { - return config.AppCoreConfig.CuteGoConfig.File.Mac.Avatar - } else if resType == "file" { - return config.AppCoreConfig.CuteGoConfig.File.Mac.Path - } - } - return config.AppCoreConfig.CuteGoConfig.File.Linux.Logs -} - -// CreateAllDir 递归创建文件夹 -func CreateAllDir(filePath string) error { - if !IsFileOrDirExist(filePath) { - err := os.MkdirAll(filePath, os.ModePerm) - if err != nil { - fmt.Println("创建文件夹失败, error info:", err) - return err - } - return err - } - return nil -} - -// IsFileOrDirExist 判断所给路径文件/文件夹是否存在(返回true是存在) -func IsFileOrDirExist(path string) bool { - // os.Stat获取文件信息 - _, err := os.Stat(path) - if err != nil { - if os.IsExist(err) { - return true - } - return false - } - return true -} - -// 类三元表达式 -// condition 成立条件 -// trueVal 当条件为true时返回 -// false 当条件为false时返回 -func If(condition bool, trueVal, falseVal interface{}) interface{} { - if condition { - return trueVal - } - return falseVal -} - -// 结构体、Map等转Json字符串 -// @Param v interface{} -// @Return Json字符串 -func StructToJson(v interface{}) string { - jsonBytes, err := json.Marshal(&v) - if err != nil { - ErrorLog(err) - return "" - } - s := string(jsonBytes) - //DebugLogf("StructToJson, json=%s", s) - return s -} - -// Json字符串转结构体、Map等 -// -// 单个对象 -// s := new(models2.SysConfig) -// return common.JsonToStruct(get, s).(*models2.SysConfig) -// -// 切片(interface{}.(期望类型)) -// s := make([]interface {}, 0) -// target := common.JsonToStruct(get, s) -// target.([]dataobject.SysDictData) -// -// @Param data Json字符串 -// @Param s 容器(结构体、Map等) -// @Return interface{} -func JsonToStruct(data string, s interface{}) interface{} { - err := json.Unmarshal([]byte(data), &s) - if err != nil { - ErrorLog(err) - return nil - } - DebugLogf("JsonToStruct, obj=%v", s) - return s -} diff --git a/pkg/config/index.go b/pkg/config/index.go index e3a9331..6e8b9f2 100644 --- a/pkg/config/index.go +++ b/pkg/config/index.go @@ -2,10 +2,14 @@ package config import ( config "cutego/pkg/config/models" + "cutego/pkg/logging" + "encoding/json" "fmt" "gopkg.in/yaml.v2" "io/ioutil" "os" + "runtime" + "strconv" ) var ( @@ -80,16 +84,117 @@ func readAppYmlFile(resourcePath string) { LoadYamlFile(applicationEnvFilePath, AppEnvConfig) } -// ExecuteTip 执行日志 -func ExecuteTip(message string) { - fmt.Println(fmt.Sprintf("-------------------- %s --------------------", message)) +// IntToString int转string +func IntToString(n int) string { + return strconv.Itoa(n) +} + +// StringToInt string转int +func StringToInt(s string) int { + i, err := strconv.Atoi(s) + if err != nil { + panic(err) + } + return i +} + +// StringToInt64 string转int64 +func StringToInt64(s string) int64 { + i, err := strconv.ParseInt(s, 10, 64) + if err != nil { + panic(err) + } + return i +} + +// Int64ToString int64转string +func Int64ToString(n int64) string { + return strconv.FormatInt(n, 10) +} + +func mapToBytes(data map[string]interface{}) []byte { + bytes, _ := json.Marshal(data) + return bytes +} + +// MapToStruct map转struct +func MapToStruct(data map[string]interface{}, v interface{}) { + _ = json.Unmarshal(mapToBytes(data), v) +} + +// GetDirPath 获取目录路径 +func GetDirPath(resType string) string { + sysType := runtime.GOOS + switch sysType { + case "linux": + if resType == "logging" { + return AppCoreConfig.CuteGoConfig.File.Linux.Logs + } else if resType == "avatar" { + return AppCoreConfig.CuteGoConfig.File.Linux.Avatar + } else if resType == "file" { + return AppCoreConfig.CuteGoConfig.File.Linux.Path + } + break + case "windows": + if resType == "logging" { + return AppCoreConfig.CuteGoConfig.File.Windows.Logs + } else if resType == "avatar" { + return AppCoreConfig.CuteGoConfig.File.Windows.Avatar + } else if resType == "file" { + return AppCoreConfig.CuteGoConfig.File.Windows.Path + } + break + case "mac": + if resType == "logging" { + return AppCoreConfig.CuteGoConfig.File.Mac.Logs + } else if resType == "avatar" { + return AppCoreConfig.CuteGoConfig.File.Mac.Avatar + } else if resType == "file" { + return AppCoreConfig.CuteGoConfig.File.Mac.Path + } + break + case "darwin": + if resType == "logging" { + return AppCoreConfig.CuteGoConfig.File.Mac.Logs + } else if resType == "avatar" { + return AppCoreConfig.CuteGoConfig.File.Mac.Avatar + } else if resType == "file" { + return AppCoreConfig.CuteGoConfig.File.Mac.Path + } + } + return AppCoreConfig.CuteGoConfig.File.Linux.Logs +} + +// CreateAllDir 递归创建文件夹 +func CreateAllDir(filePath string) error { + if !IsFileOrDirExist(filePath) { + err := os.MkdirAll(filePath, os.ModePerm) + if err != nil { + fmt.Println("创建文件夹失败, error info:", err) + return err + } + return err + } + return nil +} + +// IsFileOrDirExist 判断所给路径文件/文件夹是否存在(返回true是存在) +func IsFileOrDirExist(path string) bool { + // os.Stat获取文件信息 + _, err := os.Stat(path) + if err != nil { + if os.IsExist(err) { + return true + } + return false + } + return true } func init() { // 资源文件所在的路径 resourcePath := GetRootPath() - ExecuteTip("初始化应用配置 start") + logging.InfoLog("application init start...") readAppYmlFile(resourcePath) - ExecuteTip("初始化应用配置 end") - return + logging.InfoLog("application init start...") } diff --git a/pkg/cronjob/index.go b/pkg/cronjob/index.go index d4f1b27..7f15a56 100644 --- a/pkg/cronjob/index.go +++ b/pkg/cronjob/index.go @@ -3,7 +3,7 @@ package cronjob import ( "cutego/modules/core/job" "cutego/modules/core/service" - "cutego/pkg/common" + "cutego/pkg/logging" "github.com/robfig/cron" ) @@ -23,24 +23,24 @@ var aliasCronMap = make(map[string]*cron.Cron) // StopCronFunc 停止任务, 不会停止已开始的任务 func StopCronFunc(aliasName string) { - common.InfoLogf("停止任务 %s ---> Start", aliasName) + logging.InfoLogf("停止任务 %s ---> Start", aliasName) go aliasCronMap[aliasName].Stop() - common.InfoLogf("停止任务 %s ---> Finish", aliasName) + logging.InfoLogf("停止任务 %s ---> Finish", aliasName) } // StartCronFunc 开始任务 func StartCronFunc(aliasName string) { - common.InfoLogf("唤起任务 %s ---> Start", aliasName) + logging.InfoLogf("唤起任务 %s ---> Start", aliasName) go aliasCronMap[aliasName].Start() - common.InfoLogf("唤起任务 %s ---> Finish", aliasName) + logging.InfoLogf("唤起任务 %s ---> Finish", aliasName) } // RemoveCronFunc 移除任务 func RemoveCronFunc(aliasName string) { - common.InfoLogf("移除任务 %s ---> Start", aliasName) + logging.InfoLogf("移除任务 %s ---> Start", aliasName) go StopCronFunc(aliasName) delete(aliasCronMap, aliasName) - common.InfoLogf("移除任务 %s ---> Finish", aliasName) + logging.InfoLogf("移除任务 %s ---> Finish", aliasName) } // AppendCronFunc 新增任务 @@ -49,7 +49,7 @@ func AppendCronFunc(jobCron string, aliasName string, status string) { aliasCronMap[aliasName].Stop() aliasCronMap[aliasName] = nil } - common.InfoLogf("新增任务 %s ---> Start", aliasName) + logging.InfoLogf("新增任务 %s ---> Start", aliasName) c := cron.New() err := c.AddFunc(jobCron, job.AliasFuncMap[aliasName]) if err != nil { @@ -59,10 +59,10 @@ func AppendCronFunc(jobCron string, aliasName string, status string) { go func() { c.Start() aliasCronMap[aliasName] = c - common.InfoLogf("调度定时任务 --- %s ---> Success", aliasName) + logging.InfoLogf("调度定时任务 --- %s ---> Success", aliasName) }() } - common.InfoLogf("新增任务 %s ---> Finish", aliasName) + logging.InfoLogf("新增任务 %s ---> Finish", aliasName) } func init() { diff --git a/pkg/gin/index.go b/pkg/gin/index.go index 45557b9..bedf4dd 100644 --- a/pkg/gin/index.go +++ b/pkg/gin/index.go @@ -4,16 +4,16 @@ import ( "cutego/modules/core/router" "cutego/pkg/filter" "cutego/pkg/jwt" + "cutego/pkg/logging" "cutego/pkg/middleware" "cutego/pkg/middleware/logger" "cutego/pkg/websocket" "cutego/refs" - "fmt" "github.com/gin-gonic/gin" ) func init() { - fmt.Println("CoolGin init...") + logging.InfoLog("CoolGin init start...") refs.CoolGin = gin.New() refs.CoolGin.Use(gin.Logger()) refs.CoolGin.Use(gin.Recovery()) @@ -27,4 +27,5 @@ func init() { v1Router := refs.CoolGin.Group("/api/v1") // 加载: 模块路由 router.LoadCoreRouter(v1Router) + logging.InfoLog("CoolGin init end...") } diff --git a/pkg/common/log.go b/pkg/logging/index.go similarity index 97% rename from pkg/common/log.go rename to pkg/logging/index.go index cf4ad40..81b82e9 100644 --- a/pkg/common/log.go +++ b/pkg/logging/index.go @@ -1,4 +1,4 @@ -package common +package logging import "github.com/druidcaesa/gotool" diff --git a/pkg/middleware/logger/logger.go b/pkg/middleware/logger/logger.go index de0c31c..5a495a7 100644 --- a/pkg/middleware/logger/logger.go +++ b/pkg/middleware/logger/logger.go @@ -3,6 +3,7 @@ package logger import ( "cutego/pkg/common" "cutego/pkg/config" + "cutego/pkg/logging" "fmt" "github.com/druidcaesa/gotool" "github.com/gin-gonic/gin" @@ -16,18 +17,18 @@ import ( // LoggerToFile 日志记录到文件 func LoggerToFile() gin.HandlerFunc { - dirPath := common.GetDirPath("log") - fileName := path.Join(dirPath, "application.log") + dirPath := common.GetDirPath("logging") + fileName := path.Join(dirPath, "application.logging") if !common.IsFileOrDirExist(dirPath) { err := common.CreateAllDir(dirPath) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } } if !gotool.FileUtils.Exists(fileName) { create, err := os.Create(fileName) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } defer create.Close() } diff --git a/pkg/middleware/recover.go b/pkg/middleware/recover.go index 38ce0a1..75e273e 100644 --- a/pkg/middleware/recover.go +++ b/pkg/middleware/recover.go @@ -1,7 +1,7 @@ package middleware import ( - "cutego/pkg/common" + "cutego/pkg/logging" "github.com/gin-gonic/gin" "net/http" "runtime/debug" @@ -10,7 +10,7 @@ import ( func Recover(c *gin.Context) { defer func() { if r := recover(); r != nil { - common.ErrorLog("panic: %v\n", r) + logging.ErrorLog("panic: %v\n", r) debug.PrintStack() c.JSON(http.StatusOK, gin.H{ "code": http.StatusInternalServerError, diff --git a/pkg/page/page.go b/pkg/page/page.go index 88f6667..54ce37b 100644 --- a/pkg/page/page.go +++ b/pkg/page/page.go @@ -1,7 +1,7 @@ package page import ( - "cutego/pkg/common" + "cutego/pkg/logging" "github.com/go-xorm/xorm" ) @@ -34,7 +34,7 @@ func GetTotal(engine *xorm.Session, args ...interface{}) (int64, error) { } count, err := engine.Count() if err != nil { - common.ErrorLog(err.Error()) + logging.ErrorLog(err.Error()) return 0, err } return count, nil diff --git a/pkg/redispool/index.go b/pkg/redispool/index.go index 5904e21..240e9ba 100644 --- a/pkg/redispool/index.go +++ b/pkg/redispool/index.go @@ -3,6 +3,7 @@ package redispool import ( "cutego/pkg/common" "cutego/pkg/config" + "cutego/pkg/logging" "fmt" "github.com/druidcaesa/gotool" "github.com/gomodule/redigo/redis" @@ -41,19 +42,19 @@ func newPool() *redis.Pool { Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", config.AppEnvConfig.Redis.Host, config.AppEnvConfig.Redis.Port)) if err != nil { - common.FatalfLog("Redis.Dial: %v", err) + logging.FatalfLog("Redis.Dial: %v", err) return nil, err } if gotool.StrUtils.HasNotEmpty(config.AppEnvConfig.Redis.Password) { if _, err := c.Do("AUTH", config.AppEnvConfig.Redis.Password); err != nil { c.Close() - common.FatalfLog("Redis.AUTH: %v", err) + logging.FatalfLog("Redis.AUTH: %v", err) return nil, err } } if _, err := c.Do("SELECT", config.AppEnvConfig.Redis.Database); err != nil { c.Close() - common.FatalfLog("Redis.SELECT: %v", err) + logging.FatalfLog("Redis.SELECT: %v", err) return nil, err } return c, nil @@ -91,11 +92,11 @@ func (r *RedisClient) loopRead() { if len(it.Key) > 0 { if len(it.Field) > 0 { if _, err := r.HSET(it.Key, it.Field, it.Value); err != nil { - common.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error()) + logging.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error()) } } else { if _, err := r.SET(it.Key, it.Value); err != nil { - common.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error()) + logging.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error()) } } if it.Expire > 0 { diff --git a/pkg/util/my_util.go b/pkg/util/my_util.go index b31a5d1..dc4a044 100644 --- a/pkg/util/my_util.go +++ b/pkg/util/my_util.go @@ -1,5 +1,10 @@ package util +import ( + "cutego/pkg/logging" + "encoding/json" +) + // IF 三元表达式 func IF(condition bool, trueValue interface{}, falseValue interface{}) interface{} { if condition { @@ -7,3 +12,41 @@ func IF(condition bool, trueValue interface{}, falseValue interface{}) interface } return falseValue } + +// 结构体、Map等转Json字符串 +// @Param v interface{} +// @Return Json字符串 +func StructToJson(v interface{}) string { + jsonBytes, err := json.Marshal(&v) + if err != nil { + logging.ErrorLog(err) + return "" + } + s := string(jsonBytes) + //DebugLogf("StructToJson, json=%s", s) + return s +} + +// Json字符串转结构体、Map等 +// +// 单个对象 +// s := new(models2.SysConfig) +// return common.JsonToStruct(get, s).(*models2.SysConfig) +// +// 切片(interface{}.(期望类型)) +// s := make([]interface {}, 0) +// target := common.JsonToStruct(get, s) +// target.([]dataobject.SysDictData) +// +// @Param data Json字符串 +// @Param s 容器(结构体、Map等) +// @Return interface{} +func JsonToStruct(data string, s interface{}) interface{} { + err := json.Unmarshal([]byte(data), &s) + if err != nil { + logging.ErrorLog(err) + return nil + } + //common.DebugLogf("JsonToStruct, obj=%v", s) + return s +} diff --git a/pkg/util/struct_util.go b/pkg/util/struct_util.go index 580bf01..2e8bb15 100644 --- a/pkg/util/struct_util.go +++ b/pkg/util/struct_util.go @@ -2,7 +2,7 @@ package util import ( "bytes" - "cutego/pkg/common" + "cutego/pkg/logging" "encoding/gob" ) @@ -21,7 +21,7 @@ func DeepCopy(src, dst interface{}) interface{} { } err := gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst) if err != nil { - common.ErrorLogf("src(%v)---> dst(%v), error", src, dst) + logging.ErrorLogf("src(%v)---> dst(%v), error", src, dst) } return dst } diff --git a/pkg/util/token_util.go b/pkg/util/token_util.go index 8a01346..4bd4218 100644 --- a/pkg/util/token_util.go +++ b/pkg/util/token_util.go @@ -3,9 +3,9 @@ package util import ( "cutego/modules/core/api/v1/response" "cutego/modules/core/dataobject" - "cutego/pkg/common" "cutego/pkg/config" "cutego/pkg/jwt" + "cutego/pkg/logging" "cutego/refs" "github.com/gin-gonic/gin" "strings" @@ -21,7 +21,7 @@ func GetUserInfo(c *gin.Context) *response.UserResponse { // parseToken 解析token包含的信息 claims, err := jwt.ParseToken(s[1]) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) } info := claims.UserInfo return &info @@ -34,7 +34,7 @@ func CheckLockToken(c *gin.Context) bool { info := GetUserInfo(c) get, err := refs.RedisDB.GET(info.UserName) if err != nil { - common.ErrorLog(err) + logging.ErrorLog(err) return false } token := c.Request.Header.Get(config.AppEnvConfig.Jwt.Header) diff --git a/pkg/websocket/index.go b/pkg/websocket/index.go index a7f6b11..06c83c7 100644 --- a/pkg/websocket/index.go +++ b/pkg/websocket/index.go @@ -1,7 +1,7 @@ package websocket import ( - "cutego/pkg/common" + "cutego/pkg/logging" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "net/http" @@ -12,16 +12,16 @@ import ( // var ws = new WebSocket("ws://127.0.0.1:21366/websocket?user=admin&code=notice"); // // 连接打开时触发 // ws.onopen = function(evt) { -// console.log("Connection open ..."); +// console.logging("Connection open ..."); // ws.send("Hello WebSockets!"); // }; // // 接收到消息时触发 // ws.onmessage = function(evt) { -// console.log("Received Message: " + evt.data); +// console.logging("Received Message: " + evt.data); // }; // // 连接关闭时触发 // ws.onclose = function(evt) { -// console.log("Connection closed."); +// console.logging("Connection closed."); // }; // @@ -69,8 +69,8 @@ func HandleWebSocketMessage(c *gin.Context) { // 回调函数的具体实现 func HandleAdminNotice(messageType int, content []byte) error { - common.InfoLog("messageType=%d\n", messageType) - common.InfoLog("content=%s\n", string(content)) + logging.InfoLog("messageType=%d\n", messageType) + logging.InfoLog("content=%s\n", string(content)) return nil } diff --git a/refs/database.go b/refs/database.go index 71f6d68..f936c60 100644 --- a/refs/database.go +++ b/refs/database.go @@ -1,8 +1,8 @@ package refs import ( - "cutego/pkg/common" "cutego/pkg/config" + "cutego/pkg/logging" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" @@ -11,6 +11,7 @@ import ( // 配置数据库 func init() { + logging.InfoLog("database init start...") var err error // 配置mysql数据库 ds := config.AppEnvConfig.DataSource @@ -23,11 +24,11 @@ func init() { ds.Charset) SqlDB, err = xorm.NewEngine(ds.DbType, jdbc) if err != nil { - common.FatalfLog("db error: %#v\n", err.Error()) + logging.FatalfLog("db error: %#v\n", err.Error()) } err = SqlDB.Ping() if err != nil { - common.FatalfLog("db connect error: %#v\n", err.Error()) + logging.FatalfLog("db connect error: %#v\n", err.Error()) } SqlDB.SetMaxIdleConns(ds.MaxIdleSize) SqlDB.SetMaxOpenConns(ds.MaxOpenSize) @@ -36,11 +37,12 @@ func init() { for _ = range timer.C { err = x.Ping() if err != nil { - common.FatalfLog("db connect error: %#v\n", err.Error()) + logging.FatalfLog("db connect error: %#v\n", err.Error()) } } }(SqlDB) SqlDB.ShowSQL(true) // 开启缓存 SqlDB.SetDefaultCacher(xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)) + logging.InfoLog("database init end...") } diff --git a/refs/redis.go b/refs/redis.go index 95a9620..ab4d47a 100644 --- a/refs/redis.go +++ b/refs/redis.go @@ -1,8 +1,13 @@ package refs -import redisTool "cutego/pkg/redispool" +import ( + "cutego/pkg/logging" + redisTool "cutego/pkg/redispool" +) // 配置redis数据库 func init() { + logging.InfoLog("redis init start...") RedisDB = redisTool.NewRedis() + logging.InfoLog("redis init end...") }