From 25d8364bf46864ab0bc610a982cb6bd53add5619 Mon Sep 17 00:00:00 2001 From: linwenxiang <991154416@qq.com> Date: Tue, 9 Mar 2021 19:12:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=8C=E5=85=BC=E5=AE=B9go?= =?UTF-8?q?-admin=20sdk=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/admin/apis/monitor/server.go | 11 +- app/admin/apis/process/wf_classify.go | 13 +- app/admin/apis/public/file.go | 15 +- .../sys_china_area_data.go | 8 +- app/admin/apis/sys_content/sys_content.go | 4 +- app/admin/apis/sys_file/sys_file_dir.go | 11 +- app/admin/apis/sys_file/sys_file_info.go | 8 +- app/admin/apis/sys_job/sys_job.go | 10 +- app/admin/apis/sys_user/sys_user.go | 34 +- app/admin/apis/system/captcha.go | 9 +- app/admin/apis/system/dict/sys_dict_data.go | 8 +- app/admin/apis/system/dict/sys_dict_type.go | 8 +- .../apis/system/sys_config/sys_config.go | 13 +- app/admin/apis/system/sys_dept/sys_dept.go | 6 +- .../system/sys_login_log/sys_login_log.go | 8 +- app/admin/apis/system/sys_menu/sys_menu.go | 10 +- .../system/sys_opera_log/sys_opera_log.go | 6 +- app/admin/apis/system/sys_post/sys_post.go | 6 +- app/admin/apis/system/sys_role/sys_role.go | 8 +- app/admin/apis/tools/dbcolumns.go | 16 +- app/admin/apis/tools/dbtables.go | 16 +- app/admin/apis/tools/gen.go | 110 +-- app/admin/apis/tools/systables.go | 53 +- app/admin/middleware/auth.go | 4 +- app/admin/middleware/handler/auth.go | 27 +- app/admin/middleware/handler/httpshandler.go | 2 +- app/admin/middleware/logger.go | 21 +- app/admin/models/initdb.go | 4 +- app/admin/models/menu.go | 8 +- app/admin/models/sys_file_dir.go | 2 +- app/admin/models/sys_file_info.go | 4 +- app/admin/models/syscategory.go | 2 +- app/admin/models/syschinaareadata.go | 20 +- app/admin/models/system/datascope.go | 10 +- app/admin/models/system/login.go | 4 +- app/admin/models/system/role_menu.go | 5 +- app/admin/models/system/sys_config.go | 2 +- app/admin/models/system/sys_login_log.go | 2 +- app/admin/models/system/sys_opera_log.go | 2 +- app/admin/models/system/sys_post.go | 10 +- app/admin/models/system/sys_role.go | 12 +- app/admin/models/tools/dbcolumns.go | 6 +- app/admin/models/tools/dbtables.go | 8 +- app/admin/models/wf_classify.go | 14 +- app/admin/router/init_router.go | 14 +- app/admin/router/monitor.go | 6 +- app/admin/router/router.go | 4 +- app/admin/router/sys_category.go | 38 +- app/admin/router/sys_config.go | 6 +- app/admin/router/sys_content.go | 6 +- app/admin/router/sys_dept.go | 6 +- app/admin/router/sys_file_dir.go | 6 +- app/admin/router/sys_file_info.go | 6 +- app/admin/router/sys_job.go | 6 +- app/admin/router/sys_login_log.go | 6 +- app/admin/router/sys_menu.go | 6 +- app/admin/router/sys_opera_log.go | 6 +- app/admin/router/sys_post.go | 7 +- app/admin/router/sys_role.go | 6 +- app/admin/router/sys_router.go | 10 +- app/admin/router/sys_user.go | 8 +- app/admin/router/syschinaareadata.go | 8 +- app/admin/router/wf_classify.go | 6 +- app/admin/service/dto/sys_file_info.go | 2 +- app/admin/service/sys_dept.go | 4 +- app/admin/service/sys_file_dir.go | 2 +- app/admin/service/sys_job.go | 3 +- app/admin/service/sys_menu.go | 6 +- app/jobs/jobbase.go | 10 +- cmd/api/server.go | 34 +- cmd/cobra.go | 8 +- cmd/config/server.go | 2 +- cmd/migrate/migration/version/dictdata.go | 24 +- cmd/migrate/server.go | 16 +- cmd/version/server.go | 5 +- common/actions/create.go | 11 +- common/actions/delete.go | 13 +- common/actions/index.go | 10 +- common/actions/permission.go | 18 +- common/actions/update.go | 13 +- common/actions/view.go | 10 +- common/apis/api.go | 12 +- common/apis/request_logger.go | 12 +- common/database/initialize.go | 23 +- common/dto/search.go | 4 +- common/file_store/initialize.go | 1 - common/file_store/interface.go | 2 +- common/global/adm.go | 12 + common/global/casbin.go | 6 +- common/middleware/db.go | 4 +- common/middleware/log.go | 9 - .../admin => common}/middleware/permission.go | 9 +- common/models/by.go | 2 +- common/models/response.go | 2 +- common/models/user.go | 2 +- common/service/service.go | 2 +- examples/run.go | 10 +- go.mod | 26 +- go.sum | 96 +-- pkg/cache/doc.go | 6 - pkg/cache/memory.go | 15 - pkg/cache/memory_test.go | 46 -- pkg/cache/redis.go | 32 - pkg/cache/redis_test.go | 46 -- pkg/cache/type.go | 29 - pkg/casbin/log.go | 76 -- pkg/casbin/mycasbin.go | 47 -- pkg/cronjob/gadmjob.go | 12 - pkg/http.go | 52 -- pkg/jwtauth/jwtauth.go | 740 ------------------ pkg/logger/logger.go | 73 -- pkg/logger/setup.go | 53 -- pkg/security.go | 67 -- pkg/table/analysis.go | 39 - pkg/utils/file.go | 127 --- pkg/utils/json_time.go | 42 - pkg/utils/response.go | 60 -- pkg/utils/utils.go | 91 --- pkg/ws/ws.go | 336 -------- .../v3/actions/router_check_role.go.template | 2 +- .../no_actions/router_check_role.go.template | 2 +- .../router_no_check_role.go.template | 2 +- .../v4/actions/router_check_role.go.template | 2 +- template/v4/dto.go.template | 2 +- template/v4/no_actions/apis.go.template | 14 +- .../no_actions/router_check_role.go.template | 2 +- .../router_no_check_role.go.template | 2 +- template/v4/no_actions/service.go.template | 4 +- test/api.go.template | 4 +- tools/app/adm.go | 18 - tools/app/model.go | 28 - tools/app/msg/message.go | 11 - tools/app/return.go | 74 -- tools/captcha/captcha.go | 40 - tools/config/application.go | 15 - tools/config/config.go | 103 --- tools/config/database.go | 23 - tools/config/gen.go | 8 - tools/config/jwt.go | 8 - tools/config/logger.go | 11 - tools/config/ssl.go | 10 - tools/env.go | 17 - tools/file.go | 130 --- tools/int.go | 23 - tools/ip.go | 59 -- tools/string.go | 27 - tools/textcolor.go | 72 -- tools/trace/trace.go | 81 -- tools/url.go | 26 - tools/user.go | 65 -- tools/utils.go | 83 -- 151 files changed, 578 insertions(+), 3525 deletions(-) create mode 100644 common/global/adm.go delete mode 100644 common/middleware/log.go rename {app/admin => common}/middleware/permission.go (85%) delete mode 100644 pkg/cache/doc.go delete mode 100644 pkg/cache/memory.go delete mode 100644 pkg/cache/memory_test.go delete mode 100644 pkg/cache/redis.go delete mode 100644 pkg/cache/redis_test.go delete mode 100644 pkg/cache/type.go delete mode 100644 pkg/casbin/log.go delete mode 100644 pkg/casbin/mycasbin.go delete mode 100644 pkg/cronjob/gadmjob.go delete mode 100644 pkg/http.go delete mode 100644 pkg/jwtauth/jwtauth.go delete mode 100644 pkg/logger/logger.go delete mode 100644 pkg/logger/setup.go delete mode 100644 pkg/security.go delete mode 100644 pkg/table/analysis.go delete mode 100644 pkg/utils/file.go delete mode 100644 pkg/utils/json_time.go delete mode 100644 pkg/utils/response.go delete mode 100644 pkg/utils/utils.go delete mode 100644 pkg/ws/ws.go delete mode 100644 tools/app/adm.go delete mode 100644 tools/app/model.go delete mode 100644 tools/app/msg/message.go delete mode 100644 tools/app/return.go delete mode 100644 tools/captcha/captcha.go delete mode 100644 tools/config/application.go delete mode 100644 tools/config/config.go delete mode 100644 tools/config/database.go delete mode 100644 tools/config/gen.go delete mode 100644 tools/config/jwt.go delete mode 100644 tools/config/logger.go delete mode 100644 tools/config/ssl.go delete mode 100644 tools/env.go delete mode 100644 tools/file.go delete mode 100644 tools/int.go delete mode 100644 tools/ip.go delete mode 100644 tools/string.go delete mode 100644 tools/textcolor.go delete mode 100644 tools/trace/trace.go delete mode 100644 tools/url.go delete mode 100644 tools/user.go delete mode 100644 tools/utils.go diff --git a/app/admin/apis/monitor/server.go b/app/admin/apis/monitor/server.go index 48928fe..4436cf6 100644 --- a/app/admin/apis/monitor/server.go +++ b/app/admin/apis/monitor/server.go @@ -4,12 +4,11 @@ import ( "runtime" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/mem" - - "go-admin/tools" - "go-admin/tools/app" ) const ( @@ -33,8 +32,8 @@ func ServerInfo(c *gin.Context) { osDic["compiler"] = runtime.Compiler osDic["version"] = runtime.Version() osDic["numGoroutine"] = runtime.NumGoroutine() - osDic["ip"] = tools.GetLocaHonst() - osDic["projectDir"] = tools.GetCurrentPath() + osDic["ip"] = pkg.GetLocaHonst() + osDic["projectDir"] = pkg.GetCurrentPath() dis, _ := disk.Usage("/") diskTotalGB := int(dis.Total) / GB @@ -57,7 +56,7 @@ func ServerInfo(c *gin.Context) { cpuDic := make(map[string]interface{}, 0) cpuDic["cpuInfo"], _ = cpu.Info() percent, _ := cpu.Percent(0, false) - cpuDic["Percent"] = tools.Round(percent[0], 2) + cpuDic["Percent"] = pkg.Round(percent[0], 2) cpuDic["cpuNum"], _ = cpu.Counts(false) app.Custum(c, gin.H{ diff --git a/app/admin/apis/process/wf_classify.go b/app/admin/apis/process/wf_classify.go index 19e3b21..f6f49e6 100644 --- a/app/admin/apis/process/wf_classify.go +++ b/app/admin/apis/process/wf_classify.go @@ -1,15 +1,16 @@ package process import ( - "github.com/gin-gonic/gin" - "go-admin/app/admin/service" "net/http" + "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "go-admin/app/admin/models" + "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/actions" "go-admin/common/apis" - "go-admin/tools" ) type WfProcessClassify struct { @@ -104,7 +105,7 @@ func (e *WfProcessClassify) InsertWfProcessClassify(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceWfProcessClassify := service.WfProcessClassify{} serviceWfProcessClassify.Orm = db @@ -139,7 +140,7 @@ func (e *WfProcessClassify) UpdateWfProcessClassify(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) //数据权限检查 p := actions.GetPermissionFromContext(c) @@ -174,7 +175,7 @@ func (e *WfProcessClassify) DeleteWfProcessClassify(c *gin.Context) { } // 设置编辑人 - control.SetUpdateBy(tools.GetUserId(c)) + control.SetUpdateBy(user.GetUserId(c)) // 数据权限检查 p := actions.GetPermissionFromContext(c) diff --git a/app/admin/apis/public/file.go b/app/admin/apis/public/file.go index da7285d..650e1d4 100644 --- a/app/admin/apis/public/file.go +++ b/app/admin/apis/public/file.go @@ -4,17 +4,16 @@ import ( "encoding/base64" "errors" "fmt" - "go-admin/common/file_store" "io/ioutil" "strings" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "github.com/go-admin-team/go-admin-core/sdk/pkg/utils" "github.com/google/uuid" - //imgType "github.com/shamsher31/goimgtype" - "go-admin/pkg/utils" - "go-admin/tools" - "go-admin/tools/app" + "go-admin/common/file_store" ) type FileResponse struct { @@ -72,7 +71,7 @@ func baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileRe _ = ioutil.WriteFile(base64File, ddd, 0666) typeStr := strings.Replace(strings.Replace(file2list[0], "data:", "", -1), ";base64", "", -1) fileResponse = FileResponse{ - Size: tools.GetFileSize(base64File), + Size: pkg.GetFileSize(base64File), Path: base64File, FullPath: urlPerfix + base64File, Name: "", @@ -107,7 +106,7 @@ func multipleFile(c *gin.Context, urlPerfix string) []FileResponse { app.Error(c, 200, errors.New(""), "上传第三方失败") } else { fileResponse := FileResponse{ - Size: tools.GetFileSize(multipartFileName), + Size: pkg.GetFileSize(multipartFileName), Path: multipartFileName, FullPath: urlPerfix + multipartFileName, Name: f.Filename, @@ -139,7 +138,7 @@ func singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (Fi _ = c.SaveUploadedFile(files, singleFile) fileType, _ := utils.GetType(singleFile) fileResponse = FileResponse{ - Size: tools.GetFileSize(singleFile), + Size: pkg.GetFileSize(singleFile), Path: singleFile, FullPath: urlPerfix + singleFile, Name: files.Filename, diff --git a/app/admin/apis/sys_china_area_data/sys_china_area_data.go b/app/admin/apis/sys_china_area_data/sys_china_area_data.go index 1647312..6eddf34 100644 --- a/app/admin/apis/sys_china_area_data/sys_china_area_data.go +++ b/app/admin/apis/sys_china_area_data/sys_china_area_data.go @@ -4,13 +4,13 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/actions" "go-admin/common/apis" - "go-admin/tools" ) type SysChinaAreaData struct { @@ -103,7 +103,7 @@ func (e *SysChinaAreaData) InsertSysChinaAreaData(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysChinaAreaData := service.SysChinaAreaData{} serviceSysChinaAreaData.Orm = db @@ -138,7 +138,7 @@ func (e *SysChinaAreaData) UpdateSysChinaAreaData(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) //数据权限检查 p := actions.GetPermissionFromContext(c) @@ -172,7 +172,7 @@ func (e *SysChinaAreaData) DeleteSysChinaAreaData(c *gin.Context) { } // 设置编辑人 - control.SetUpdateBy(tools.GetUserId(c)) + control.SetUpdateBy(user.GetUserId(c)) // 数据权限检查 p := actions.GetPermissionFromContext(c) diff --git a/app/admin/apis/sys_content/sys_content.go b/app/admin/apis/sys_content/sys_content.go index 171e939..4139767 100644 --- a/app/admin/apis/sys_content/sys_content.go +++ b/app/admin/apis/sys_content/sys_content.go @@ -6,8 +6,8 @@ package sys_content // // "go-admin/app/admin/models" // "go-admin/tools" -// "go-admin/tools/app" -// "go-admin/tools/app/msg" +// "github.com/go-admin-team/go-admin-core/sdk/pkg/response" +// "github.com/go-admin-team/go-admin-core/sdk/pkg/response/msg" //) // //func GetSysContentList(c *gin.Context) { diff --git a/app/admin/apis/sys_file/sys_file_dir.go b/app/admin/apis/sys_file/sys_file_dir.go index 70524fb..333205b 100644 --- a/app/admin/apis/sys_file/sys_file_dir.go +++ b/app/admin/apis/sys_file/sys_file_dir.go @@ -4,13 +4,14 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/actions" "go-admin/common/apis" - "go-admin/tools" ) type SysFileDir struct { @@ -99,7 +100,7 @@ func (e *SysFileDir) InsertSysFileDir(c *gin.Context) { return } // 设置创建人 - control.CreateBy = tools.GetUserId(c) + control.CreateBy = user.GetUserId(c) serviceSysFileDir := service.SysFileDir{} serviceSysFileDir.Orm = db @@ -134,7 +135,7 @@ func (e *SysFileDir) UpdateSysFileDir(c *gin.Context) { e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败") } // 设置创建人 - control.UpdateBy = tools.GetUserId(c) + control.UpdateBy = user.GetUserId(c) //数据权限检查 p := actions.GetPermissionFromContext(c) @@ -160,7 +161,7 @@ func (e *SysFileDir) DeleteSysFileDir(c *gin.Context) { return } - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) //删除操作 err = c.ShouldBindUri(control) if err != nil { @@ -174,7 +175,7 @@ func (e *SysFileDir) DeleteSysFileDir(c *gin.Context) { } // 设置编辑人 - control.UpdateBy = tools.GetUserId(c) + control.UpdateBy = user.GetUserId(c) // 数据权限检查 p := actions.GetPermissionFromContext(c) diff --git a/app/admin/apis/sys_file/sys_file_info.go b/app/admin/apis/sys_file/sys_file_info.go index d9be4ed..a45c7c3 100644 --- a/app/admin/apis/sys_file/sys_file_info.go +++ b/app/admin/apis/sys_file/sys_file_info.go @@ -4,13 +4,13 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/actions" "go-admin/common/apis" - "go-admin/tools" ) type SysFileInfo struct { @@ -108,7 +108,7 @@ func (e *SysFileInfo) InsertSysFileInfo(c *gin.Context) { return } // 设置创建人 - control.CreateBy = tools.GetUserId(c) + control.CreateBy = user.GetUserId(c) serviceSysFileInfo := service.SysFileInfo{} serviceSysFileInfo.Orm = db @@ -145,7 +145,7 @@ func (e *SysFileInfo) UpdateSysFileInfo(c *gin.Context) { return } // 设置创建人 - control.UpdateBy = tools.GetUserId(c) + control.UpdateBy = user.GetUserId(c) //数据权限检查 p := actions.GetPermissionFromContext(c) @@ -186,7 +186,7 @@ func (e *SysFileInfo) DeleteSysFileInfo(c *gin.Context) { } // 设置编辑人 - control.UpdateBy = tools.GetUserId(c) + control.UpdateBy = user.GetUserId(c) // 数据权限检查 p := actions.GetPermissionFromContext(c) diff --git a/app/admin/apis/sys_job/sys_job.go b/app/admin/apis/sys_job/sys_job.go index b77e447..0a49f18 100644 --- a/app/admin/apis/sys_job/sys_job.go +++ b/app/admin/apis/sys_job/sys_job.go @@ -1,13 +1,15 @@ package sys_job import ( - "github.com/gin-gonic/gin" "net/http" + "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "go-admin/app/admin/service" "go-admin/common/apis" "go-admin/common/dto" - "go-admin/tools/app" ) type SysJob struct { @@ -32,7 +34,7 @@ func (e *SysJob) RemoveJobForService(c *gin.Context) { s := service.SysJob{} s.Log = log s.Orm = db - s.Cron = app.Runtime.GetCrontabKey(c.Request.Host) + s.Cron = sdk.Runtime.GetCrontabKey(c.Request.Host) err = s.RemoveJob(&v) if err != nil { log.Errorf("RemoveJob error, %s", err.Error()) @@ -60,7 +62,7 @@ func (e *SysJob) StartJobForService(c *gin.Context) { s := service.SysJob{} s.Orm = db s.Log = log - s.Cron = app.Runtime.GetCrontabKey(c.Request.Host) + s.Cron = sdk.Runtime.GetCrontabKey(c.Request.Host) err = s.StartJob(&v) if err != nil { log.Errorf("GetCrontabKey error, %s", err.Error()) diff --git a/app/admin/apis/sys_user/sys_user.go b/app/admin/apis/sys_user/sys_user.go index d2b0dd7..30540db 100644 --- a/app/admin/apis/sys_user/sys_user.go +++ b/app/admin/apis/sys_user/sys_user.go @@ -4,6 +4,7 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "github.com/google/uuid" "go-admin/app/admin/models" @@ -13,7 +14,6 @@ import ( "go-admin/common/actions" "go-admin/common/apis" common "go-admin/common/models" - "go-admin/tools" ) type SysUser struct { @@ -136,7 +136,7 @@ func (e *SysUser) InsertSysUser(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysUser := service.SysUser{} serviceSysUser.Orm = db @@ -183,7 +183,7 @@ func (e *SysUser) UpdateSysUser(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) //数据权限检查 p := actions.GetPermissionFromContext(c) @@ -232,7 +232,7 @@ func (e *SysUser) DeleteSysUser(c *gin.Context) { } // 设置编辑人 - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) // 数据权限检查 p := actions.GetPermissionFromContext(c) @@ -354,7 +354,7 @@ func (e *SysUser) GetSysUserProfile(c *gin.Context) { return } - id := tools.GetUserId(c) + id := user.GetUserId(c) serviceSysUser := service.SysUser{} serviceSysUser.Log = log serviceSysUser.Orm = db @@ -418,7 +418,7 @@ func (e *SysUser) GetInfo(c *gin.Context) { p := actions.GetPermissionFromContext(c) var roles = make([]string, 1) - roles[0] = tools.GetRoleName(c) + roles[0] = user.GetRoleName(c) var permissions = make([]string, 1) permissions[0] = "*:*:*" @@ -427,11 +427,11 @@ func (e *SysUser) GetInfo(c *gin.Context) { buttons[0] = "*:*:*" RoleMenu := models.RoleMenu{} - RoleMenu.RoleId = tools.GetRoleId(c) + RoleMenu.RoleId = user.GetRoleId(c) var mp = make(map[string]interface{}) mp["roles"] = roles - if tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员" { + if user.GetRoleName(c) == "admin" || user.GetRoleName(c) == "系统管理员" { mp["permissions"] = permissions mp["buttons"] = buttons } else { @@ -440,13 +440,13 @@ func (e *SysUser) GetInfo(c *gin.Context) { mp["buttons"] = list } - var user system.SysUser + var sysUser system.SysUser req := new(dto.SysUserById) - req.Id = tools.GetUserId(c) + req.Id = user.GetUserId(c) serviceSysUser := service.SysUser{} serviceSysUser.Log = log serviceSysUser.Orm = db - err = serviceSysUser.GetSysUser(req, p, &user) + err = serviceSysUser.GetSysUser(req, p, &sysUser) if err != nil { e.Error(c, http.StatusUnauthorized, err, "登录失败") return @@ -455,12 +455,12 @@ func (e *SysUser) GetInfo(c *gin.Context) { mp["introduction"] = " am a super administrator" mp["avatar"] = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" - if user.Avatar != "" { - mp["avatar"] = user.Avatar + if sysUser.Avatar != "" { + mp["avatar"] = sysUser.Avatar } - mp["userName"] = user.NickName - mp["userId"] = user.UserId - mp["deptId"] = user.DeptId - mp["name"] = user.NickName + mp["userName"] = sysUser.NickName + mp["userId"] = sysUser.UserId + mp["deptId"] = sysUser.DeptId + mp["name"] = sysUser.NickName e.OK(c, mp, "") } diff --git a/app/admin/apis/system/captcha.go b/app/admin/apis/system/captcha.go index 26439a1..0fb5896 100644 --- a/app/admin/apis/system/captcha.go +++ b/app/admin/apis/system/captcha.go @@ -2,15 +2,14 @@ package system import ( "github.com/gin-gonic/gin" - - "go-admin/tools" - "go-admin/tools/app" - "go-admin/tools/captcha" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/captcha" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" ) func GenerateCaptchaHandler(c *gin.Context) { id, b64s, err := captcha.DriverDigitFunc() - tools.HasError(err, "验证码获取失败", 500) + pkg.HasError(err, "验证码获取失败", 500) app.Custum(c, gin.H{ "code": 200, "data": b64s, diff --git a/app/admin/apis/system/dict/sys_dict_data.go b/app/admin/apis/system/dict/sys_dict_data.go index 7489dc8..57c42d9 100644 --- a/app/admin/apis/system/dict/sys_dict_data.go +++ b/app/admin/apis/system/dict/sys_dict_data.go @@ -4,13 +4,13 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" common "go-admin/common/models" - "go-admin/tools" ) type SysDictData struct { @@ -127,7 +127,7 @@ func (e *SysDictData) InsertSysDictData(c *gin.Context) { } object, _ := req.GenerateM() // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) s := service.SysDictData{} s.Orm = db @@ -169,7 +169,7 @@ func (e *SysDictData) UpdateSysDictData(c *gin.Context) { return } object, _ := req.GenerateM() - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) s := service.SysDictData{} s.Orm = db @@ -215,7 +215,7 @@ func (e *SysDictData) DeleteSysDictData(c *gin.Context) { } // 设置编辑人 - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) s := service.SysDictData{} s.Orm = db diff --git a/app/admin/apis/system/dict/sys_dict_type.go b/app/admin/apis/system/dict/sys_dict_type.go index 37a4a48..734f058 100644 --- a/app/admin/apis/system/dict/sys_dict_type.go +++ b/app/admin/apis/system/dict/sys_dict_type.go @@ -4,13 +4,13 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" common "go-admin/common/models" - "go-admin/tools" ) type SysDictType struct { @@ -122,7 +122,7 @@ func (e *SysDictType) InsertSysDictType(c *gin.Context) { } object, _ := req.GenerateM() // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) s := service.SysDictType{} s.Orm = db @@ -163,7 +163,7 @@ func (e *SysDictType) UpdateSysDictType(c *gin.Context) { return } object, _ := req.GenerateM() - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) s := service.SysDictType{} s.Orm = db @@ -207,7 +207,7 @@ func (e *SysDictType) DeleteSysDictType(c *gin.Context) { } // 设置编辑人 - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) s := service.SysDictType{} s.Orm = db diff --git a/app/admin/apis/system/sys_config/sys_config.go b/app/admin/apis/system/sys_config/sys_config.go index 37b0c31..93976cc 100644 --- a/app/admin/apis/system/sys_config/sys_config.go +++ b/app/admin/apis/system/sys_config/sys_config.go @@ -1,15 +1,16 @@ package sys_config import ( - "github.com/gin-gonic/gin" "net/http" + "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" - "go-admin/tools" - "go-admin/tools/app" ) type SysConfig struct { @@ -104,7 +105,7 @@ func (e *SysConfig) InsertSysConfig(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysLoginLog := service.SysConfig{} serviceSysLoginLog.Orm = db @@ -146,7 +147,7 @@ func (e *SysConfig) UpdateSysConfig(c *gin.Context) { app.Error(c, 500, err, "Orm获取失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysLoginLog := service.SysConfig{} serviceSysLoginLog.Orm = db @@ -188,7 +189,7 @@ func (e *SysConfig) DeleteSysConfig(c *gin.Context) { } // 设置编辑人 - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysLoginLog := service.SysConfig{} serviceSysLoginLog.Orm = db diff --git a/app/admin/apis/system/sys_dept/sys_dept.go b/app/admin/apis/system/sys_dept/sys_dept.go index 2ef1513..27a0dc1 100644 --- a/app/admin/apis/system/sys_dept/sys_dept.go +++ b/app/admin/apis/system/sys_dept/sys_dept.go @@ -4,12 +4,12 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" - "go-admin/tools" ) type SysDept struct { @@ -122,7 +122,7 @@ func (e *SysDept) InsertSysDept(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysDept := service.SysDept{} serviceSysDept.Orm = db @@ -168,7 +168,7 @@ func (e *SysDept) UpdateSysDept(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysDept := service.SysDept{} serviceSysDept.Orm = db diff --git a/app/admin/apis/system/sys_login_log/sys_login_log.go b/app/admin/apis/system/sys_login_log/sys_login_log.go index a60eda4..1940823 100644 --- a/app/admin/apis/system/sys_login_log/sys_login_log.go +++ b/app/admin/apis/system/sys_login_log/sys_login_log.go @@ -4,12 +4,12 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" - "go-admin/tools" ) type SysLoginLog struct { @@ -96,7 +96,7 @@ func (e *SysLoginLog) InsertSysLoginLog(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysLoginLog := service.SysLoginLog{} serviceSysLoginLog.Orm = db @@ -131,7 +131,7 @@ func (e *SysLoginLog) UpdateSysLoginLog(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysLoginLog := service.SysLoginLog{} serviceSysLoginLog.Orm = db @@ -168,7 +168,7 @@ func (e *SysLoginLog) DeleteSysLoginLog(c *gin.Context) { } // 设置编辑人 - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysLoginLog := service.SysLoginLog{} serviceSysLoginLog.Orm = db diff --git a/app/admin/apis/system/sys_menu/sys_menu.go b/app/admin/apis/system/sys_menu/sys_menu.go index b771bd8..c359650 100644 --- a/app/admin/apis/system/sys_menu/sys_menu.go +++ b/app/admin/apis/system/sys_menu/sys_menu.go @@ -4,13 +4,13 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" - "go-admin/tools" ) type SysMenu struct { @@ -131,7 +131,7 @@ func (e *SysMenu) InsertSysMenu(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysMenu := service.SysMenu{} serviceSysMenu.Orm = db @@ -179,7 +179,7 @@ func (e *SysMenu) UpdateSysMenu(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysMenu := service.SysMenu{} serviceSysMenu.Orm = db @@ -249,7 +249,7 @@ func (e *SysMenu) GetMenuRole(c *gin.Context) { serviceSysMenu := service.SysMenu{} serviceSysMenu.Log = log serviceSysMenu.Orm = db - result, err := serviceSysMenu.SetMenuRole(tools.GetRoleName(c)) + result, err := serviceSysMenu.SetMenuRole(user.GetRoleName(c)) if err != nil { e.Error(c, http.StatusInternalServerError, err, "查询失败") @@ -276,7 +276,7 @@ func (e *SysMenu) GetMenuIDS(c *gin.Context) { } var data models.RoleMenu data.RoleName = c.GetString("role") - data.UpdateBy = tools.GetUserIdStr(c) + data.UpdateBy = user.GetUserIdStr(c) result, err := data.GetIDS(db) if err != nil { log.Errorf("GetIDS error, %s", err.Error()) diff --git a/app/admin/apis/system/sys_opera_log/sys_opera_log.go b/app/admin/apis/system/sys_opera_log/sys_opera_log.go index fbf075a..0998ddc 100644 --- a/app/admin/apis/system/sys_opera_log/sys_opera_log.go +++ b/app/admin/apis/system/sys_opera_log/sys_opera_log.go @@ -4,12 +4,12 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" - "go-admin/tools" ) type SysOperaLog struct { @@ -96,7 +96,7 @@ func (e *SysOperaLog) InsertSysOperaLog(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysOperaLog := service.SysOperaLog{} serviceSysOperaLog.Orm = db @@ -131,7 +131,7 @@ func (e *SysOperaLog) UpdateSysOperaLog(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysOperaLog := service.SysOperaLog{} serviceSysOperaLog.Orm = db diff --git a/app/admin/apis/system/sys_post/sys_post.go b/app/admin/apis/system/sys_post/sys_post.go index 3fbb8f1..be5881d 100644 --- a/app/admin/apis/system/sys_post/sys_post.go +++ b/app/admin/apis/system/sys_post/sys_post.go @@ -4,12 +4,12 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" - "go-admin/tools" ) type SysPost struct { @@ -123,7 +123,7 @@ func (e *SysPost) InsertSysPost(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) serviceSysPost := service.SysPost{} serviceSysPost.Orm = db @@ -168,7 +168,7 @@ func (e *SysPost) UpdateSysPost(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) serviceSysPost := service.SysPost{} serviceSysPost.Orm = db diff --git a/app/admin/apis/system/sys_role/sys_role.go b/app/admin/apis/system/sys_role/sys_role.go index 3c614a3..4c35a21 100644 --- a/app/admin/apis/system/sys_role/sys_role.go +++ b/app/admin/apis/system/sys_role/sys_role.go @@ -4,13 +4,13 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" "go-admin/app/admin/models/system" "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/apis" "go-admin/common/global" - "go-admin/tools" ) type SysRole struct { @@ -126,7 +126,7 @@ func (e *SysRole) InsertSysRole(c *gin.Context) { return } // 设置创建人 - object.CreateBy = tools.GetUserId(c) + object.CreateBy = user.GetUserId(c) if object.Status == "" { object.Status = "2" } @@ -178,7 +178,7 @@ func (e *SysRole) UpdateSysRole(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.UpdateBy = tools.GetUserId(c) + object.UpdateBy = user.GetUserId(c) s := service.SysRole{} s.Orm = db @@ -259,7 +259,7 @@ func (e *SysRole) UpdateRoleDataScope(c *gin.Context) { DataScope: control.DataScope, DeptIds: control.DeptIds, } - data.UpdateBy = tools.GetUserId(c) + data.UpdateBy = user.GetUserId(c) s := &service.SysRole{} s.Orm = db s.Log = log diff --git a/app/admin/apis/tools/dbcolumns.go b/app/admin/apis/tools/dbcolumns.go index 25bf5c0..80e95df 100644 --- a/app/admin/apis/tools/dbcolumns.go +++ b/app/admin/apis/tools/dbcolumns.go @@ -1,14 +1,14 @@ package tools import ( - "go-admin/common/apis" "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "go-admin/app/admin/models/tools" - tools2 "go-admin/tools" - "go-admin/tools/app" + "go-admin/common/apis" ) // @Summary 分页列表数据 / page list data @@ -27,14 +27,14 @@ func GetDBColumnList(c *gin.Context) { var pageIndex = 1 if size := c.Request.FormValue("pageSize"); size != "" { - pageSize, err = tools2.StringToInt(size) + pageSize, err = pkg.StringToInt(size) } if index := c.Request.FormValue("pageIndex"); index != "" { - pageIndex, err = tools2.StringToInt(index) + pageIndex, err = pkg.StringToInt(index) } - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -42,9 +42,9 @@ func GetDBColumnList(c *gin.Context) { } data.TableName = c.Request.FormValue("tableName") - tools2.Assert(data.TableName == "", "table name cannot be empty!", 500) + pkg.Assert(data.TableName == "", "table name cannot be empty!", 500) result, count, err := data.GetPage(db, pageSize, pageIndex) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) var mp = make(map[string]interface{}, 3) mp["list"] = result diff --git a/app/admin/apis/tools/dbtables.go b/app/admin/apis/tools/dbtables.go index 7d56fcf..c24d714 100644 --- a/app/admin/apis/tools/dbtables.go +++ b/app/admin/apis/tools/dbtables.go @@ -1,15 +1,15 @@ package tools import ( - "go-admin/common/apis" "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "go-admin/app/admin/models/tools" - tools2 "go-admin/tools" - "go-admin/tools/app" - "go-admin/tools/config" + "go-admin/common/apis" ) // @Summary 分页列表数据 / page list data @@ -34,14 +34,14 @@ func GetDBTableList(c *gin.Context) { } if size := c.Request.FormValue("pageSize"); size != "" { - pageSize, err = tools2.StringToInt(size) + pageSize, err = pkg.StringToInt(size) } if index := c.Request.FormValue("pageIndex"); index != "" { - pageIndex, err = tools2.StringToInt(index) + pageIndex, err = pkg.StringToInt(index) } - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -50,7 +50,7 @@ func GetDBTableList(c *gin.Context) { data.TableName = c.Request.FormValue("tableName") result, count, err := data.GetPage(db, pageSize, pageIndex) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) var mp = make(map[string]interface{}, 3) mp["list"] = result diff --git a/app/admin/apis/tools/gen.go b/app/admin/apis/tools/gen.go index 13980ce..8048429 100644 --- a/app/admin/apis/tools/gen.go +++ b/app/admin/apis/tools/gen.go @@ -2,39 +2,39 @@ package tools import ( "bytes" - "go-admin/common/apis" "net/http" "text/template" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "go-admin/app/admin/models" "go-admin/app/admin/models/tools" - tools2 "go-admin/tools" - "go-admin/tools/app" - "go-admin/tools/config" + "go-admin/common/apis" ) func Preview(c *gin.Context) { log := apis.GetRequestLogger(c) table := tools.SysTables{} - id, err := tools2.StringToInt(c.Param("tableId")) - tools2.HasError(err, "", -1) + id, err := pkg.StringToInt(c.Param("tableId")) + pkg.HasError(err, "", -1) table.TableId = id t1, err := template.ParseFiles("template/v4/model.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t2, err := template.ParseFiles("template/v4/no_actions/apis.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t3, err := template.ParseFiles("template/v4/js.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t4, err := template.ParseFiles("template/v4/vue.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t5, err := template.ParseFiles("template/v4/no_actions/router_check_role.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t6, err := template.ParseFiles("template/v4/dto.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -71,10 +71,10 @@ func Preview(c *gin.Context) { func GenCodeV3(c *gin.Context) { log := apis.GetRequestLogger(c) table := tools.SysTables{} - id, err := tools2.StringToInt(c.Param("tableId")) - tools2.HasError(err, "", -1) + id, err := pkg.StringToInt(c.Param("tableId")) + pkg.HasError(err, "", -1) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -103,26 +103,26 @@ func NOActionsGenV3(tab tools.SysTables) { } t1, err := template.ParseFiles(basePath + "model.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t3, err := template.ParseFiles(routerFile) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t4, err := template.ParseFiles(basePath + "js.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t5, err := template.ParseFiles(basePath + "vue.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t6, err := template.ParseFiles(basePath + "dto.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t7, err := template.ParseFiles(basePath + "no_actions/service.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) - _ = tools2.PathCreate("./app/" + tab.PackageName + "/apis/" + tab.ModuleName) - _ = tools2.PathCreate("./app/" + tab.PackageName + "/models/") - _ = tools2.PathCreate("./app/" + tab.PackageName + "/router/") - _ = tools2.PathCreate("./app/" + tab.PackageName + "/service/dto/") - _ = tools2.PathCreate(config.GenConfig.FrontPath + "/api/") - _ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName) + _ = pkg.PathCreate("./app/" + tab.PackageName + "/apis/" + tab.ModuleName) + _ = pkg.PathCreate("./app/" + tab.PackageName + "/models/") + _ = pkg.PathCreate("./app/" + tab.PackageName + "/router/") + _ = pkg.PathCreate("./app/" + tab.PackageName + "/service/dto/") + _ = pkg.PathCreate(config.GenConfig.FrontPath + "/api/") + _ = pkg.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName) var b1 bytes.Buffer err = t1.Execute(&b1, tab) @@ -138,13 +138,13 @@ func NOActionsGenV3(tab tools.SysTables) { err = t6.Execute(&b6, tab) var b7 bytes.Buffer err = t7.Execute(&b7, tab) - tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go") - tools2.FileCreate(b2, "./app/"+tab.PackageName+"/apis/"+tab.ModuleName+"/"+tab.BusinessName+".go") - tools2.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go") - tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js") - tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue") - tools2.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go") - tools2.FileCreate(b7, "./app/"+tab.PackageName+"/service/"+tab.BusinessName+".go") + pkg.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go") + pkg.FileCreate(b2, "./app/"+tab.PackageName+"/apis/"+tab.ModuleName+"/"+tab.BusinessName+".go") + pkg.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go") + pkg.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js") + pkg.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue") + pkg.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go") + pkg.FileCreate(b7, "./app/"+tab.PackageName+"/service/"+tab.BusinessName+".go") } @@ -157,21 +157,21 @@ func ActionsGenV3(tab tools.SysTables) { } t1, err := template.ParseFiles(basePath + "model.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t3, err := template.ParseFiles(routerFile) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t4, err := template.ParseFiles(basePath + "js.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t5, err := template.ParseFiles(basePath + "vue.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) t6, err := template.ParseFiles(basePath + "dto.go.template") - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) - _ = tools2.PathCreate("./app/" + tab.PackageName + "/models/") - _ = tools2.PathCreate("./app/" + tab.PackageName + "/router/") - _ = tools2.PathCreate("./app/" + tab.PackageName + "/service/dto/") - _ = tools2.PathCreate(config.GenConfig.FrontPath + "/api/") - _ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName) + _ = pkg.PathCreate("./app/" + tab.PackageName + "/models/") + _ = pkg.PathCreate("./app/" + tab.PackageName + "/router/") + _ = pkg.PathCreate("./app/" + tab.PackageName + "/service/dto/") + _ = pkg.PathCreate(config.GenConfig.FrontPath + "/api/") + _ = pkg.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName) var b1 bytes.Buffer err = t1.Execute(&b1, tab) @@ -184,22 +184,22 @@ func ActionsGenV3(tab tools.SysTables) { var b6 bytes.Buffer err = t6.Execute(&b6, tab) - tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go") - tools2.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go") - tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js") - tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue") - tools2.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go") + pkg.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go") + pkg.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go") + pkg.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js") + pkg.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue") + pkg.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go") } func GenMenuAndApi(c *gin.Context) { log := apis.GetRequestLogger(c) table := tools.SysTables{} - timeNow := tools2.GetCurrentTime() - id, err := tools2.StringToInt(c.Param("tableId")) - tools2.HasError(err, "", -1) + timeNow := pkg.GetCurrentTime() + id, err := pkg.StringToInt(c.Param("tableId")) + pkg.HasError(err, "", -1) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") diff --git a/app/admin/apis/tools/systables.go b/app/admin/apis/tools/systables.go index ef51a88..058741d 100644 --- a/app/admin/apis/tools/systables.go +++ b/app/admin/apis/tools/systables.go @@ -1,16 +1,17 @@ package tools import ( - "go-admin/common/apis" - "gorm.io/gorm" "net/http" "strings" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "gorm.io/gorm" "go-admin/app/admin/models/tools" - tools2 "go-admin/tools" - "go-admin/tools/app" + "go-admin/common/apis" ) // @Summary 分页列表数据 @@ -29,14 +30,14 @@ func GetSysTableList(c *gin.Context) { var pageIndex = 1 if size := c.Request.FormValue("pageSize"); size != "" { - pageSize, err = tools2.StringToInt(size) + pageSize, err = pkg.StringToInt(size) } if index := c.Request.FormValue("pageIndex"); index != "" { - pageIndex, err = tools2.StringToInt(index) + pageIndex, err = pkg.StringToInt(index) } - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -46,7 +47,7 @@ func GetSysTableList(c *gin.Context) { data.TBName = c.Request.FormValue("tableName") data.TableComment = c.Request.FormValue("tableComment") result, count, err := data.GetPage(db, pageSize, pageIndex) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) var mp = make(map[string]interface{}, 3) mp["list"] = result @@ -69,7 +70,7 @@ func GetSysTableList(c *gin.Context) { // @Security Bearer func GetSysTables(c *gin.Context) { log := apis.GetRequestLogger(c) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -77,9 +78,9 @@ func GetSysTables(c *gin.Context) { } var data tools.SysTables - data.TableId, _ = tools2.StringToInt(c.Param("tableId")) + data.TableId, _ = pkg.StringToInt(c.Param("tableId")) result, err := data.Get(db) - tools2.HasError(err, "抱歉未找到相关信息", -1) + pkg.HasError(err, "抱歉未找到相关信息", -1) var res app.Response res.Data = result @@ -92,7 +93,7 @@ func GetSysTables(c *gin.Context) { func GetSysTablesInfo(c *gin.Context) { log := apis.GetRequestLogger(c) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -104,7 +105,7 @@ func GetSysTablesInfo(c *gin.Context) { data.TBName = c.Request.FormValue("tableName") } result, err := data.Get(db) - tools2.HasError(err, "抱歉未找到相关信息", -1) + pkg.HasError(err, "抱歉未找到相关信息", -1) var res app.Response res.Data = result @@ -117,7 +118,7 @@ func GetSysTablesInfo(c *gin.Context) { func GetSysTablesTree(c *gin.Context) { log := apis.GetRequestLogger(c) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -126,7 +127,7 @@ func GetSysTablesTree(c *gin.Context) { var data tools.SysTables result, err := data.GetTree(db) - tools2.HasError(err, "抱歉未找到相关信息", -1) + pkg.HasError(err, "抱歉未找到相关信息", -1) var res app.Response res.Data = result @@ -145,7 +146,7 @@ func GetSysTablesTree(c *gin.Context) { // @Security Bearer func InsertSysTable(c *gin.Context) { log := apis.GetRequestLogger(c) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -158,7 +159,7 @@ func InsertSysTable(c *gin.Context) { data, err := genTableInit(db, tablesList, i, c) _, err = data.Create(db) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) } var res app.Response res.Msg = "添加成功!" @@ -171,7 +172,7 @@ func genTableInit(tx *gorm.DB, tablesList []string, i int, c *gin.Context) (tool var dbTable tools.DBTables var dbColumn tools.DBColumns data.TBName = tablesList[i] - data.CreateBy = tools2.GetUserIdStr(c) + data.CreateBy = user.GetUserIdStr(c) dbTable.TableName = data.TBName dbtable, err := dbTable.Get(tx) @@ -190,7 +191,7 @@ func genTableInit(tx *gorm.DB, tablesList []string, i int, c *gin.Context) (tool data.Crud = true dbcolumn, err := dbColumn.GetList(tx) - data.CreateBy = tools2.GetUserIdStr(c) + data.CreateBy = user.GetUserIdStr(c) data.TableComment = dbtable.TableComment if dbtable.TableComment == "" { data.TableComment = data.ClassName @@ -279,19 +280,19 @@ func genTableInit(tx *gorm.DB, tablesList []string, i int, c *gin.Context) (tool func UpdateSysTable(c *gin.Context) { var data tools.SysTables err := c.Bind(&data) - tools2.HasError(err, "数据解析失败", 500) + pkg.HasError(err, "数据解析失败", 500) log := apis.GetRequestLogger(c) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") return } - data.UpdateBy = tools2.GetUserIdStr(c) + data.UpdateBy = user.GetUserIdStr(c) result, err := data.Update(db) - tools2.HasError(err, "", -1) + pkg.HasError(err, "", -1) var res app.Response res.Data = result @@ -308,7 +309,7 @@ func UpdateSysTable(c *gin.Context) { // @Router /api/v1/sys/tables/info/{tableId} [delete] func DeleteSysTables(c *gin.Context) { log := apis.GetRequestLogger(c) - db, err := tools2.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -316,9 +317,9 @@ func DeleteSysTables(c *gin.Context) { } var data tools.SysTables - IDS := tools2.IdsStrToIdsIntGroup("tableId", c) + IDS := pkg.IdsStrToIdsIntGroup("tableId", c) _, err = data.BatchDelete(db, IDS) - tools2.HasError(err, "删除失败", 500) + pkg.HasError(err, "删除失败", 500) var res app.Response res.Msg = "删除成功" c.JSON(http.StatusOK, res.ReturnOK()) diff --git a/app/admin/middleware/auth.go b/app/admin/middleware/auth.go index 69db951..78e09dd 100644 --- a/app/admin/middleware/auth.go +++ b/app/admin/middleware/auth.go @@ -3,9 +3,9 @@ package middleware import ( "time" + "github.com/go-admin-team/go-admin-core/sdk/config" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/middleware/handler" - jwt "go-admin/pkg/jwtauth" - "go-admin/tools/config" ) // AuthInit jwt验证new diff --git a/app/admin/middleware/handler/auth.go b/app/admin/middleware/handler/auth.go index ccb6d79..0dda629 100644 --- a/app/admin/middleware/handler/auth.go +++ b/app/admin/middleware/handler/auth.go @@ -1,19 +1,20 @@ package handler import ( - "go-admin/common/apis" "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "github.com/mojocn/base64Captcha" "github.com/mssola/user_agent" "go-admin/app/admin/models/system" "go-admin/app/admin/service" - jwt "go-admin/pkg/jwtauth" - "go-admin/tools" - "go-admin/tools/app" - "go-admin/tools/config" + "go-admin/common/apis" ) var store = base64Captcha.DefaultMemStore @@ -60,7 +61,7 @@ func IdentityHandler(c *gin.Context) interface{} { // @Router /login [post] func Authenticator(c *gin.Context) (interface{}, error) { log := apis.GetRequestLogger(c) - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -109,16 +110,16 @@ func LoginLogToDB(c *gin.Context, status string, msg string, username string) { log := apis.GetRequestLogger(c) if config.LoggerConfig.EnabledDB { var loginLog system.SysLoginLog - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("获取Orm失败, error:%s", err) } ua := user_agent.New(c.Request.UserAgent()) loginLog.Ipaddr = c.ClientIP() loginLog.Username = username - location := tools.GetLocation(c.ClientIP()) + location := pkg.GetLocation(c.ClientIP()) loginLog.LoginLocation = location - loginLog.LoginTime = tools.GetCurrentTime() + loginLog.LoginTime = pkg.GetCurrentTime() loginLog.Status = status loginLog.Remark = c.Request.UserAgent() browserName, browserVersion := ua.Browser() @@ -146,18 +147,18 @@ func LogOut(c *gin.Context) { var loginLog system.SysLoginLog ua := user_agent.New(c.Request.UserAgent()) loginLog.Ipaddr = c.ClientIP() - location := tools.GetLocation(c.ClientIP()) + location := pkg.GetLocation(c.ClientIP()) loginLog.LoginLocation = location - loginLog.LoginTime = tools.GetCurrentTime() + loginLog.LoginTime = pkg.GetCurrentTime() loginLog.Status = "2" loginLog.Remark = c.Request.UserAgent() browserName, browserVersion := ua.Browser() loginLog.Browser = browserName + " " + browserVersion loginLog.Os = ua.OS() loginLog.Platform = ua.Platform() - loginLog.Username = tools.GetUserName(c) + loginLog.Username = user.GetUserName(c) loginLog.Msg = "退出成功" - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("获取Orm失败, error:%s", err) } diff --git a/app/admin/middleware/handler/httpshandler.go b/app/admin/middleware/handler/httpshandler.go index e812305..e127439 100644 --- a/app/admin/middleware/handler/httpshandler.go +++ b/app/admin/middleware/handler/httpshandler.go @@ -4,7 +4,7 @@ import ( "github.com/gin-gonic/gin" "github.com/unrolled/secure" - "go-admin/tools/config" + "github.com/go-admin-team/go-admin-core/sdk/config" ) func TlsHandler() gin.HandlerFunc { diff --git a/app/admin/middleware/logger.go b/app/admin/middleware/logger.go index 869cdc6..be1c97d 100644 --- a/app/admin/middleware/logger.go +++ b/app/admin/middleware/logger.go @@ -2,19 +2,20 @@ package middleware import ( "fmt" - "go-admin/common/apis" "net/http" "strings" "time" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "go-admin/app/admin/models" "go-admin/app/admin/models/system" "go-admin/app/admin/service" - "go-admin/tools" - "go-admin/tools/app" - "go-admin/tools/config" + "go-admin/common/apis" ) // LoggerToFile 日志记录到文件 @@ -79,7 +80,7 @@ func LoggerToFile() gin.HandlerFunc { // SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用 func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration, body string, result string, status int) { log := apis.GetRequestLogger(c) - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Errorf("get db connection error, %s", err.Error()) app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") @@ -92,9 +93,9 @@ func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string menuList, _ := menu.Get(db) sysOperaLog := system.SysOperaLog{} sysOperaLog.OperIp = clientIP - sysOperaLog.OperLocation = tools.GetLocation(clientIP) - sysOperaLog.Status = tools.IntToString(statusCode) - sysOperaLog.OperName = tools.GetUserName(c) + sysOperaLog.OperLocation = pkg.GetLocation(clientIP) + sysOperaLog.Status = pkg.IntToString(statusCode) + sysOperaLog.OperName = user.GetUserName(c) sysOperaLog.RequestMethod = c.Request.Method sysOperaLog.OperUrl = reqUri sysOperaLog.OperParam = body @@ -120,8 +121,8 @@ func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string if len(menuList) > 0 { sysOperaLog.Title = menuList[0].Title } - sysOperaLog.CreateBy = tools.GetUserId(c) - sysOperaLog.OperTime = tools.GetCurrentTime() + sysOperaLog.CreateBy = user.GetUserId(c) + sysOperaLog.OperTime = pkg.GetCurrentTime() sysOperaLog.LatencyTime = fmt.Sprintf("%v", latencyTime) sysOperaLog.JsonResult = result diff --git a/app/admin/models/initdb.go b/app/admin/models/initdb.go index 097e9ef..9bb37a2 100644 --- a/app/admin/models/initdb.go +++ b/app/admin/models/initdb.go @@ -2,7 +2,7 @@ package models import ( "fmt" - "go-admin/tools/app" + "go-admin/common/global" "gorm.io/gorm" "io/ioutil" "log" @@ -12,7 +12,7 @@ import ( func InitDb(db *gorm.DB) (err error) { filePath := "config/db.sql" err = ExecSql(db, filePath) - if app.Driver == "postgres" { + if global.Driver == "postgres" { filePath = "config/pg.sql" err = ExecSql(db, filePath) } diff --git a/app/admin/models/menu.go b/app/admin/models/menu.go index 5db970a..ac21313 100644 --- a/app/admin/models/menu.go +++ b/app/admin/models/menu.go @@ -2,11 +2,11 @@ package models import ( "errors" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" "go-admin/app/admin/models/system" - "go-admin/tools" ) type Menu struct { @@ -274,7 +274,7 @@ func (e *Menu) GetPage(tx *gorm.DB) (Menus []Menu, err error) { // 数据权限控制 dataPermission := new(system.DataPermission) - dataPermission.UserId, _ = tools.StringToInt(e.DataScope) + dataPermission.UserId, _ = pkg.StringToInt(e.DataScope) table, err = dataPermission.GetDataScope("sys_menu", table) if err != nil { return nil, err @@ -307,9 +307,9 @@ func InitPaths(tx *gorm.DB, menu *Menu) (err error) { err = errors.New("父级paths异常,请尝试对当前节点父级菜单进行更新操作!") return } - menu.Paths = parentMenu.Paths + "/" + tools.IntToString(menu.MenuId) + menu.Paths = parentMenu.Paths + "/" + pkg.IntToString(menu.MenuId) } else { - menu.Paths = "/0/" + tools.IntToString(menu.MenuId) + menu.Paths = "/0/" + pkg.IntToString(menu.MenuId) } tx.Table("sys_menu").Where("menu_id = ?", menu.MenuId).Update("paths", menu.Paths) return diff --git a/app/admin/models/sys_file_dir.go b/app/admin/models/sys_file_dir.go index ca2138b..246b14c 100644 --- a/app/admin/models/sys_file_dir.go +++ b/app/admin/models/sys_file_dir.go @@ -37,4 +37,4 @@ func (e *SysFileDir) Generate() models.ActiveRecord { func (e *SysFileDir) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/sys_file_info.go b/app/admin/models/sys_file_info.go index 5bb3c69..598969e 100644 --- a/app/admin/models/sys_file_info.go +++ b/app/admin/models/sys_file_info.go @@ -9,7 +9,7 @@ type SysFileInfo struct { Type string `json:"type" gorm:"type:varchar(255);comment:类型"` // Name string `json:"name" gorm:"type:varchar(255);comment:名称"` // Size string `json:"size" gorm:"type:int(11);comment:大小"` // - PId int `json:"pId" gorm:"type:int(11);comment:目录"` // + PId int `json:"pId" gorm:"type:int(11);comment:目录"` // Source string `json:"source" gorm:"type:varchar(255);comment:来源"` // Url string `json:"url" gorm:"type:varchar(255);comment:地址"` // FullUrl string `json:"fullUrl" gorm:"type:varchar(255);comment:全地址"` // @@ -28,4 +28,4 @@ func (e *SysFileInfo) Generate() models.ActiveRecord { func (e *SysFileInfo) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/syscategory.go b/app/admin/models/syscategory.go index c04a91e..b04973d 100644 --- a/app/admin/models/syscategory.go +++ b/app/admin/models/syscategory.go @@ -26,4 +26,4 @@ func (e *SysCategory) Generate() models.ActiveRecord { func (e *SysCategory) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/syschinaareadata.go b/app/admin/models/syschinaareadata.go index 69cf306..13d7c8b 100644 --- a/app/admin/models/syschinaareadata.go +++ b/app/admin/models/syschinaareadata.go @@ -6,18 +6,18 @@ import ( ) type SysChinaAreaData struct { - models.Model - models.ControlBy - - PId string `json:"pId" gorm:"type:int(11);comment:上级编码"` - Name string `json:"name" gorm:"type:varchar(128);comment:名称"` - CreateTime time.Time `json:"createTime" gorm:"type:timestamp;comment:CreateTime"` - UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp;comment:UpdateTime"` - DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp;comment:DeleteTime"` + models.Model + models.ControlBy + + PId string `json:"pId" gorm:"type:int(11);comment:上级编码"` + Name string `json:"name" gorm:"type:varchar(128);comment:名称"` + CreateTime time.Time `json:"createTime" gorm:"type:timestamp;comment:CreateTime"` + UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp;comment:UpdateTime"` + DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp;comment:DeleteTime"` } func (SysChinaAreaData) TableName() string { - return "sys_china_area_data" + return "sys_china_area_data" } func (e *SysChinaAreaData) Generate() models.ActiveRecord { @@ -27,4 +27,4 @@ func (e *SysChinaAreaData) Generate() models.ActiveRecord { func (e *SysChinaAreaData) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/system/datascope.go b/app/admin/models/system/datascope.go index 68dc945..a95acfd 100644 --- a/app/admin/models/system/datascope.go +++ b/app/admin/models/system/datascope.go @@ -2,11 +2,11 @@ package system import ( "errors" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" log "github.com/go-admin-team/go-admin-core/logger" - "go-admin/tools" - "go-admin/tools/config" + "github.com/go-admin-team/go-admin-core/sdk/config" ) type DataPermission struct { @@ -19,7 +19,7 @@ type DataPermission struct { func (e *DataPermission) GetDataScope(tableName string, db *gorm.DB) (*gorm.DB, error) { if !config.ApplicationConfig.EnableDP { - usageStr := `数据权限已经为您` + tools.Green(`关闭`) + `,如需开启请参考配置文件字段说明` + usageStr := `数据权限已经为您` + pkg.Green(`关闭`) + `,如需开启请参考配置文件字段说明` log.Debug("%s\n", usageStr) return db, nil } @@ -40,7 +40,7 @@ func (e *DataPermission) GetDataScope(tableName string, db *gorm.DB) (*gorm.DB, db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId) } if role.DataScope == "4" { - db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(user.DeptId)+"%") + db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(user.DeptId)+"%") } if role.DataScope == "5" || role.DataScope == "" { db = db.Where(tableName+".create_by = ?", e.UserId) @@ -71,7 +71,7 @@ func DataScopes(tableName string, userId int) func(db *gorm.DB) *gorm.DB { return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId) } if role.DataScope == "4" { - return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(user.DeptId)+"%") + return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(user.DeptId)+"%") } if role.DataScope == "5" || role.DataScope == "" { return db.Where(tableName+".create_by = ?", userId) diff --git a/app/admin/models/system/login.go b/app/admin/models/system/login.go index 7238b5f..1963eb2 100644 --- a/app/admin/models/system/login.go +++ b/app/admin/models/system/login.go @@ -3,7 +3,7 @@ package system import ( "fmt" log "github.com/go-admin-team/go-admin-core/logger" - "go-admin/tools" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" ) @@ -21,7 +21,7 @@ func (u *Login) GetUser(tx *gorm.DB) (user SysUser, role SysRole, err error) { return } fmt.Println(user.Password, u.Password) - _, err = tools.CompareHashAndPassword(user.Password, u.Password) + _, err = pkg.CompareHashAndPassword(user.Password, u.Password) if err != nil { log.Errorf("user login error, %s", err.Error()) return diff --git a/app/admin/models/system/role_menu.go b/app/admin/models/system/role_menu.go index 9ddb627..df21054 100644 --- a/app/admin/models/system/role_menu.go +++ b/app/admin/models/system/role_menu.go @@ -2,11 +2,10 @@ package system import ( "fmt" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "github.com/casbin/casbin/v2" "gorm.io/gorm" - - "go-admin/tools" ) type RoleMenu struct { @@ -159,7 +158,7 @@ func (rm *RoleMenu) Insert(tx *gorm.DB, enforcer *casbin.SyncedEnforcer, roleId } func (rm *RoleMenu) Delete(tx *gorm.DB, RoleId string, MenuID string) (bool, error) { - rm.RoleId, _ = tools.StringToInt(RoleId) + rm.RoleId, _ = pkg.StringToInt(RoleId) table := tx.Table("sys_role_menu").Where("role_id = ?", RoleId) if MenuID != "" { table = table.Where("menu_id = ?", MenuID) diff --git a/app/admin/models/system/sys_config.go b/app/admin/models/system/sys_config.go index 80bbe34..f07e7cd 100644 --- a/app/admin/models/system/sys_config.go +++ b/app/admin/models/system/sys_config.go @@ -26,4 +26,4 @@ func (e *SysConfig) Generate() models.ActiveRecord { func (e *SysConfig) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/system/sys_login_log.go b/app/admin/models/system/sys_login_log.go index ee9f608..c1bbf1d 100644 --- a/app/admin/models/system/sys_login_log.go +++ b/app/admin/models/system/sys_login_log.go @@ -34,4 +34,4 @@ func (e *SysLoginLog) Generate() models.ActiveRecord { func (e *SysLoginLog) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/system/sys_opera_log.go b/app/admin/models/system/sys_opera_log.go index 1723994..e7c78be 100644 --- a/app/admin/models/system/sys_opera_log.go +++ b/app/admin/models/system/sys_opera_log.go @@ -42,4 +42,4 @@ func (e *SysOperaLog) Generate() models.ActiveRecord { func (e *SysOperaLog) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/models/system/sys_post.go b/app/admin/models/system/sys_post.go index c1954a2..a2dc3cd 100644 --- a/app/admin/models/system/sys_post.go +++ b/app/admin/models/system/sys_post.go @@ -4,11 +4,11 @@ import "go-admin/common/models" type SysPost struct { PostId int `gorm:"primaryKey;autoIncrement" json:"postId"` //岗位编号 - PostName string `gorm:"size:128;" json:"postName"` //岗位名称 - PostCode string `gorm:"size:128;" json:"postCode"` //岗位代码 - Sort int `gorm:"" json:"sort"` //岗位排序 - Status int `gorm:"size:4;" json:"status"` //状态 - Remark string `gorm:"size:255;" json:"remark"` //描述 + PostName string `gorm:"size:128;" json:"postName"` //岗位名称 + PostCode string `gorm:"size:128;" json:"postCode"` //岗位代码 + Sort int `gorm:"" json:"sort"` //岗位排序 + Status int `gorm:"size:4;" json:"status"` //状态 + Remark string `gorm:"size:255;" json:"remark"` //描述 models.ControlBy models.ModelTime diff --git a/app/admin/models/system/sys_role.go b/app/admin/models/system/sys_role.go index 3ae0fe0..3def8e1 100644 --- a/app/admin/models/system/sys_role.go +++ b/app/admin/models/system/sys_role.go @@ -4,12 +4,12 @@ import "go-admin/common/models" type SysRole struct { RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码 - RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称 - Status string `json:"status" gorm:"size:4;"` // - RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码 - RoleSort int `json:"roleSort" gorm:""` //角色排序 - Flag string `json:"flag" gorm:"size:128;"` // - Remark string `json:"remark" gorm:"size:255;"` //备注 + RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称 + Status string `json:"status" gorm:"size:4;"` // + RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码 + RoleSort int `json:"roleSort" gorm:""` //角色排序 + Flag string `json:"flag" gorm:"size:128;"` // + Remark string `json:"remark" gorm:"size:255;"` //备注 Admin bool `json:"admin" gorm:"size:4;"` DataScope string `json:"dataScope" gorm:"size:128;"` Params string `json:"params" gorm:"-"` diff --git a/app/admin/models/tools/dbcolumns.go b/app/admin/models/tools/dbcolumns.go index 8f33076..ef41f44 100644 --- a/app/admin/models/tools/dbcolumns.go +++ b/app/admin/models/tools/dbcolumns.go @@ -2,11 +2,11 @@ package tools import ( "errors" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" - "go-admin/tools" - "go-admin/tools/config" + "github.com/go-admin-team/go-admin-core/sdk/config" ) type DBColumns struct { @@ -62,7 +62,7 @@ func (e *DBColumns) GetList(tx *gorm.DB) ([]DBColumns, error) { table = table.Where("TABLE_NAME = ?", e.TableName).Order("ORDINAL_POSITION asc") } else { - tools.Assert(true, "目前只支持mysql数据库", 500) + pkg.Assert(true, "目前只支持mysql数据库", 500) } if err := table.Find(&doc).Error; err != nil { return doc, err diff --git a/app/admin/models/tools/dbtables.go b/app/admin/models/tools/dbtables.go index 728354c..77c4927 100644 --- a/app/admin/models/tools/dbtables.go +++ b/app/admin/models/tools/dbtables.go @@ -2,11 +2,11 @@ package tools import ( "errors" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" - "go-admin/tools" - config2 "go-admin/tools/config" + config2 "github.com/go-admin-team/go-admin-core/sdk/config" ) type DBTables struct { @@ -36,7 +36,7 @@ func (e *DBTables) GetPage(tx *gorm.DB, pageSize int, pageIndex int) ([]DBTables return nil, 0, err } } else { - tools.Assert(true, "目前只支持mysql数据库", 500) + pkg.Assert(true, "目前只支持mysql数据库", 500) } //table.Count(&count) @@ -56,7 +56,7 @@ func (e *DBTables) Get(tx *gorm.DB) (DBTables, error) { return doc, err } } else { - tools.Assert(true, "目前只支持mysql数据库", 500) + pkg.Assert(true, "目前只支持mysql数据库", 500) } return doc, nil } diff --git a/app/admin/models/wf_classify.go b/app/admin/models/wf_classify.go index 3b0695f..b842bc2 100644 --- a/app/admin/models/wf_classify.go +++ b/app/admin/models/wf_classify.go @@ -1,20 +1,20 @@ package models import ( - // "gorm.io/gorm" + // "gorm.io/gorm" "go-admin/common/models" ) type WfProcessClassify struct { - models.Model - models.ControlBy - - Name string `json:"name" gorm:"type:varchar(255);comment:名称"` + models.Model + models.ControlBy + + Name string `json:"name" gorm:"type:varchar(255);comment:名称"` } func (WfProcessClassify) TableName() string { - return "wf_process_classify" + return "wf_process_classify" } func (e *WfProcessClassify) Generate() models.ActiveRecord { @@ -24,4 +24,4 @@ func (e *WfProcessClassify) Generate() models.ActiveRecord { func (e *WfProcessClassify) GetId() interface{} { return e.Id -} \ No newline at end of file +} diff --git a/app/admin/router/init_router.go b/app/admin/router/init_router.go index 0b92cf0..18e2841 100644 --- a/app/admin/router/init_router.go +++ b/app/admin/router/init_router.go @@ -1,7 +1,8 @@ package router import ( - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "os" "github.com/gin-gonic/gin" @@ -10,18 +11,17 @@ import ( "go-admin/app/admin/middleware" "go-admin/app/admin/middleware/handler" common "go-admin/common/middleware" - //_ "go-admin/pkg/jwtauth" - "go-admin/tools" - "go-admin/tools/config" + + "github.com/go-admin-team/go-admin-core/sdk/config" ) // InitRouter 路由初始化,不要怀疑,这里用到了 func InitRouter() { var r *gin.Engine - h := app.Runtime.GetEngine() + h := sdk.Runtime.GetEngine() if h == nil { h = gin.New() - app.Runtime.SetEngine(h) + sdk.Runtime.SetEngine(h) } switch h.(type) { case *gin.Engine: @@ -35,7 +35,7 @@ func InitRouter() { } r.Use(common.Sentinel()). - Use(common.RequestId(tools.TrafficKey)) + Use(common.RequestId(pkg.TrafficKey)) middleware.InitMiddleware(r) // the jwt middleware authMiddleware, err := middleware.AuthInit() diff --git a/app/admin/router/monitor.go b/app/admin/router/monitor.go index 0c96939..b6cf2fa 100644 --- a/app/admin/router/monitor.go +++ b/app/admin/router/monitor.go @@ -1,7 +1,7 @@ package router import ( - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" "net/http" "github.com/gin-gonic/gin" @@ -12,10 +12,10 @@ import ( func Monitor() { var r *gin.Engine - h := app.Runtime.GetEngine() + h := sdk.Runtime.GetEngine() if h == nil { h = gin.New() - app.Runtime.SetEngine(h) + sdk.Runtime.SetEngine(h) } switch h.(type) { case *gin.Engine: diff --git a/app/admin/router/router.go b/app/admin/router/router.go index 83f9210..ed28347 100644 --- a/app/admin/router/router.go +++ b/app/admin/router/router.go @@ -3,8 +3,8 @@ package router import ( "github.com/gin-gonic/gin" _ "github.com/gin-gonic/gin" - "go-admin/pkg/jwtauth" - jwt "go-admin/pkg/jwtauth" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) var ( diff --git a/app/admin/router/sys_category.go b/app/admin/router/sys_category.go index 3eaa0a8..df8322a 100644 --- a/app/admin/router/sys_category.go +++ b/app/admin/router/sys_category.go @@ -1,31 +1,31 @@ package router import ( - "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" + middleware2 "go-admin/common/middleware" - "go-admin/app/admin/middleware" - "go-admin/app/admin/models" - "go-admin/app/admin/service/dto" - "go-admin/common/actions" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + "go-admin/app/admin/models" + "go-admin/app/admin/service/dto" + "go-admin/common/actions" ) -func init() { +func init() { routerCheckRole = append(routerCheckRole, registerSysCategoryRouter) } // 需认证的路由代码 func registerSysCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { - r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) - { - model := &models.SysCategory{} - r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysCategorySearch), func() interface{} { - list := make([]models.SysCategory, 0) - return &list - })) - r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysCategoryById), nil)) - r.POST("", actions.CreateAction(new(dto.SysCategoryControl))) - r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysCategoryControl))) - r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysCategoryById))) - } + r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) + { + model := &models.SysCategory{} + r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysCategorySearch), func() interface{} { + list := make([]models.SysCategory, 0) + return &list + })) + r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysCategoryById), nil)) + r.POST("", actions.CreateAction(new(dto.SysCategoryControl))) + r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysCategoryControl))) + r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysCategoryById))) + } } diff --git a/app/admin/router/sys_config.go b/app/admin/router/sys_config.go index 0497b39..f6cc894 100644 --- a/app/admin/router/sys_config.go +++ b/app/admin/router/sys_config.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_config" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -13,7 +13,7 @@ func init() { // 需认证的路由代码 func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { - r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { api := &sys_config.SysConfig{} r.GET("", api.GetSysConfigList) diff --git a/app/admin/router/sys_content.go b/app/admin/router/sys_content.go index 6c138a0..133d724 100644 --- a/app/admin/router/sys_content.go +++ b/app/admin/router/sys_content.go @@ -2,11 +2,11 @@ package router import ( "github.com/gin-gonic/gin" - "go-admin/app/admin/middleware" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/models" "go-admin/app/admin/service/dto" "go-admin/common/actions" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -16,7 +16,7 @@ func init() { // 需认证的路由代码 func registerSysContentRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { - r := v1.Group("/syscontent").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/syscontent").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { //r.GET("", sys_content.GetSysContentList) //r.GET("/:id", sys_content.GetSysContent) diff --git a/app/admin/router/sys_dept.go b/app/admin/router/sys_dept.go index 1bb5479..bc9ef1e 100644 --- a/app/admin/router/sys_dept.go +++ b/app/admin/router/sys_dept.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_dept" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysDeptRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_dept.SysDept{} - r := v1.Group("/dept").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/dept").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysDeptList) r.GET("/:id", api.GetSysDept) diff --git a/app/admin/router/sys_file_dir.go b/app/admin/router/sys_file_dir.go index 45cb49e..74adf16 100644 --- a/app/admin/router/sys_file_dir.go +++ b/app/admin/router/sys_file_dir.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/sys_file" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysFileDirRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_file.SysFileDir{} - r := v1.Group("/sysfiledir").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/sysfiledir").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysFileDirList) r.GET("/:id", api.GetSysFileDir) diff --git a/app/admin/router/sys_file_info.go b/app/admin/router/sys_file_info.go index d7409ff..f4e0f2f 100644 --- a/app/admin/router/sys_file_info.go +++ b/app/admin/router/sys_file_info.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/sys_file" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysFileInfoRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_file.SysFileInfo{} - r := v1.Group("/sysfileinfo").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/sysfileinfo").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysFileInfoList) r.GET("/:id", api.GetSysFileInfo) diff --git a/app/admin/router/sys_job.go b/app/admin/router/sys_job.go index 27fcef0..81c571b 100644 --- a/app/admin/router/sys_job.go +++ b/app/admin/router/sys_job.go @@ -2,12 +2,12 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/sys_job" - "go-admin/app/admin/middleware" "go-admin/app/admin/models" "go-admin/app/admin/service/dto" "go-admin/common/actions" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -17,7 +17,7 @@ func init() { // 需认证的路由代码 func registerSysJobRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { - r := v1.Group("/sysjob").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/sysjob").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { sysJob := &models.SysJob{} r.GET("", actions.PermissionAction(), actions.IndexAction(sysJob, new(dto.SysJobSearch), func() interface{} { diff --git a/app/admin/router/sys_login_log.go b/app/admin/router/sys_login_log.go index bf2662d..91458e0 100644 --- a/app/admin/router/sys_login_log.go +++ b/app/admin/router/sys_login_log.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_login_log" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_login_log.SysLoginLog{} - r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysLoginLogList) r.GET("/:id", api.GetSysLoginLog) diff --git a/app/admin/router/sys_menu.go b/app/admin/router/sys_menu.go index 61b43c3..6a8148d 100644 --- a/app/admin/router/sys_menu.go +++ b/app/admin/router/sys_menu.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_menu" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -21,7 +21,7 @@ func registerSysMenuRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle // menu.PUT("", system.UpdateMenu) // menu.DELETE("/:id", system.DeleteMenu) //} - r := v1.Group("/menu").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/menu").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysMenuList) r.GET("/:id", api.GetSysMenu) diff --git a/app/admin/router/sys_opera_log.go b/app/admin/router/sys_opera_log.go index 55bd809..2e34872 100644 --- a/app/admin/router/sys_opera_log.go +++ b/app/admin/router/sys_opera_log.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_opera_log" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysOperaLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_opera_log.SysOperaLog{} - r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysOperaLogList) r.GET("/:id", api.GetSysOperaLog) diff --git a/app/admin/router/sys_post.go b/app/admin/router/sys_post.go index 17c1ce7..af38a5b 100644 --- a/app/admin/router/sys_post.go +++ b/app/admin/router/sys_post.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_post" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSyPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_post.SysPost{} - r := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysPostList) r.GET("/:id", api.GetSysPost) @@ -23,4 +23,3 @@ func registerSyPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlew r.DELETE("/:id", api.DeleteSysPost) } } - diff --git a/app/admin/router/sys_role.go b/app/admin/router/sys_role.go index c9945f1..4d52c09 100644 --- a/app/admin/router/sys_role.go +++ b/app/admin/router/sys_role.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/system/sys_role" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysRoleRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_role.SysRole{} - r := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysRoleList) r.GET("/:id", api.GetSysRole) diff --git a/app/admin/router/sys_router.go b/app/admin/router/sys_router.go index 944be2d..0e63063 100644 --- a/app/admin/router/sys_router.go +++ b/app/admin/router/sys_router.go @@ -2,18 +2,18 @@ package router import ( "go-admin/app/admin/apis/system/sys_menu" + middleware2 "go-admin/common/middleware" "mime" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + "github.com/go-admin-team/go-admin-core/sdk/pkg/ws" "go-admin/app/admin/apis/monitor" "go-admin/app/admin/apis/public" "go-admin/app/admin/apis/system" "go-admin/app/admin/apis/system/dict" . "go-admin/app/admin/apis/tools" - "go-admin/app/admin/middleware" "go-admin/app/admin/middleware/handler" _ "go-admin/docs" - jwt "go-admin/pkg/jwtauth" - "go-admin/pkg/ws" "github.com/gin-gonic/gin" ginSwagger "github.com/swaggo/gin-swagger" @@ -110,7 +110,7 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := sys_menu.SysMenu{} - v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { //v1auth.GET("/getinfo", system.GetInfo) v1auth.GET("/roleMenuTreeselect/:roleId", api.GetMenuTreeSelect) @@ -160,7 +160,7 @@ func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { dictApi := &dict.SysDictType{} dataApi := &dict.SysDictData{} - dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { dicts.GET("/data", dataApi.GetSysDictDataList) diff --git a/app/admin/router/sys_user.go b/app/admin/router/sys_user.go index c78a935..1b0e83a 100644 --- a/app/admin/router/sys_user.go +++ b/app/admin/router/sys_user.go @@ -2,10 +2,10 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/sys_user" - "go-admin/app/admin/middleware" "go-admin/common/actions" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -15,7 +15,7 @@ func init() { // 需认证的路由代码 func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_user.SysUser{} - r := v1.Group("/sysUser").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()).Use(actions.PermissionAction()) + r := v1.Group("/sysUser").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()).Use(actions.PermissionAction()) { r.GET("", api.GetSysUserList) r.GET("/:id", api.GetSysUser) @@ -24,7 +24,7 @@ func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle r.DELETE("", api.DeleteSysUser) } - user := v1.Group("/user").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()).Use(actions.PermissionAction()) + user := v1.Group("/user").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()).Use(actions.PermissionAction()) { user.GET("/profile", api.GetSysUserProfile) user.POST("/avatar", api.InsetSysUserAvatar) diff --git a/app/admin/router/syschinaareadata.go b/app/admin/router/syschinaareadata.go index 096abad..6f47b89 100644 --- a/app/admin/router/syschinaareadata.go +++ b/app/admin/router/syschinaareadata.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/sys_china_area_data" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerSysChinaAreaDataRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &sys_china_area_data.SysChinaAreaData{} - r := v1.Group("/sys_china_area_data").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/sys_china_area_data").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetSysChinaAreaDataList) r.GET("/:id", api.GetSysChinaAreaData) @@ -22,4 +22,4 @@ func registerSysChinaAreaDataRouter(v1 *gin.RouterGroup, authMiddleware *jwt.Gin r.PUT("/:id", api.UpdateSysChinaAreaData) r.DELETE("", api.DeleteSysChinaAreaData) } -} \ No newline at end of file +} diff --git a/app/admin/router/wf_classify.go b/app/admin/router/wf_classify.go index be038da..57f47f6 100644 --- a/app/admin/router/wf_classify.go +++ b/app/admin/router/wf_classify.go @@ -2,9 +2,9 @@ package router import ( "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" "go-admin/app/admin/apis/process" - "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + middleware2 "go-admin/common/middleware" ) func init() { @@ -14,7 +14,7 @@ func init() { // 需认证的路由代码 func registerWfProcessClassifyRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { api := &process.WfProcessClassify{} - r := v1.Group("/process").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + r := v1.Group("/process").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole()) { r.GET("", api.GetWfProcessClassifyList) r.GET("/:id", api.GetWfProcessClassify) diff --git a/app/admin/service/dto/sys_file_info.go b/app/admin/service/dto/sys_file_info.go index 8765ebe..ba6e4bd 100644 --- a/app/admin/service/dto/sys_file_info.go +++ b/app/admin/service/dto/sys_file_info.go @@ -49,4 +49,4 @@ func (s *SysFileInfoControl) Generate() (*models.SysFileInfo, error) { type SysFileInfoById struct { dto.ObjectById UpdateBy int `json:"-"` -} \ No newline at end of file +} diff --git a/app/admin/service/sys_dept.go b/app/admin/service/sys_dept.go index bc34138..ae71d06 100644 --- a/app/admin/service/sys_dept.go +++ b/app/admin/service/sys_dept.go @@ -2,6 +2,7 @@ package service import ( "errors" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" @@ -9,7 +10,6 @@ import ( "go-admin/app/admin/service/dto" cDto "go-admin/common/dto" "go-admin/common/service" - "go-admin/tools" ) type SysDept struct { @@ -64,7 +64,7 @@ func (e *SysDept) InsertSysDept(model *system.SysDept) error { e.Log.Errorf("db error:%s", err) return err } - deptPath := "/" + tools.IntToString(model.DeptId) + deptPath := "/" + pkg.IntToString(model.DeptId) if model.ParentId != 0 { var deptP system.SysDept e.Orm.Model(&data).First(&deptP, model.ParentId) diff --git a/app/admin/service/sys_file_dir.go b/app/admin/service/sys_file_dir.go index 53169b4..541eec5 100644 --- a/app/admin/service/sys_file_dir.go +++ b/app/admin/service/sys_file_dir.go @@ -165,4 +165,4 @@ func SysFileDirCall(list *[]models.SysFileDirL, m models.SysFileDirL) models.Sys } return m -} \ No newline at end of file +} diff --git a/app/admin/service/sys_job.go b/app/admin/service/sys_job.go index 450c6e3..dde262d 100644 --- a/app/admin/service/sys_job.go +++ b/app/admin/service/sys_job.go @@ -8,7 +8,6 @@ import ( "go-admin/app/jobs" "go-admin/common/dto" "go-admin/common/service" - "go-admin/tools/app/msg" ) type SysJob struct { @@ -38,7 +37,7 @@ func (e *SysJob) RemoveJob(c *dto.GeneralDelDto) error { return err } case <-time.After(time.Second * 1): - e.Msg = msg.TimeOut + e.Msg = "操作超时!" return nil } return nil diff --git a/app/admin/service/sys_menu.go b/app/admin/service/sys_menu.go index 9aa1e54..40422de 100644 --- a/app/admin/service/sys_menu.go +++ b/app/admin/service/sys_menu.go @@ -2,11 +2,11 @@ package service import ( "errors" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "go-admin/app/admin/models/system" "go-admin/app/admin/service/dto" cDto "go-admin/common/dto" "go-admin/common/service" - "go-admin/tools" "gorm.io/gorm" ) @@ -93,9 +93,9 @@ func (e *SysMenu) initPaths(menu *system.SysMenu) error { err = errors.New("父级paths异常,请尝试对当前节点父级菜单进行更新操作!") return err } - menu.Paths = parentMenu.Paths + "/" + tools.IntToString(menu.MenuId) + menu.Paths = parentMenu.Paths + "/" + pkg.IntToString(menu.MenuId) } else { - menu.Paths = "/0/" + tools.IntToString(menu.MenuId) + menu.Paths = "/0/" + pkg.IntToString(menu.MenuId) } e.Orm.Model(&data).Where("menu_id = ?", menu.MenuId).Update("paths", menu.Paths) return err diff --git a/app/jobs/jobbase.go b/app/jobs/jobbase.go index 0e362be..3a21227 100644 --- a/app/jobs/jobbase.go +++ b/app/jobs/jobbase.go @@ -3,16 +3,16 @@ package jobs import ( "fmt" log "github.com/go-admin-team/go-admin-core/logger" - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" "gorm.io/gorm" "sync" "time" "github.com/robfig/cron/v3" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/cronjob" "go-admin/app/admin/models" - "go-admin/pkg" - "go-admin/pkg/cronjob" ) var timeFormat = "2006-01-02 15:04:05" @@ -101,13 +101,13 @@ func Setup(dbs map[string]*gorm.DB) { fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Starting...") for k, db := range dbs { - app.Runtime.SetCrontab(k, cronjob.NewWithSeconds()) + sdk.Runtime.SetCrontab(k, cronjob.NewWithSeconds()) setup(k, db) } } func setup(key string, db *gorm.DB) { - crontab := app.Runtime.GetCrontabKey(key) + crontab := sdk.Runtime.GetCrontabKey(key) sysJob := models.SysJob{} jobList := make([]models.SysJob, 0) err := sysJob.GetList(db, &jobList) diff --git a/cmd/api/server.go b/cmd/api/server.go index 764faf5..48ce63b 100644 --- a/cmd/api/server.go +++ b/cmd/api/server.go @@ -3,7 +3,8 @@ package api import ( "context" "fmt" - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "log" "net/http" "os" @@ -14,13 +15,12 @@ import ( "github.com/go-admin-team/go-admin-core/config/source/file" "github.com/spf13/cobra" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg/logger" "go-admin/app/admin/router" "go-admin/app/jobs" "go-admin/common/database" "go-admin/common/global" - "go-admin/pkg/logger" - "go-admin/tools" - "go-admin/tools/config" ) var ( @@ -54,7 +54,7 @@ func setup() { config.Setup(file.NewSource, file.WithPath(configYml)) go config.Watch() //2. 设置日志 - app.Runtime.SetLogger( + sdk.Runtime.SetLogger( logger.SetupLogger( config.LoggerConfig.Type, config.LoggerConfig.Path, @@ -70,10 +70,10 @@ func setup() { func run() error { defer config.Stop() - if config.ApplicationConfig.Mode == tools.ModeProd.String() { + if config.ApplicationConfig.Mode == pkg.ModeProd.String() { gin.SetMode(gin.ReleaseMode) } - engine := app.Runtime.GetEngine() + engine := sdk.Runtime.GetEngine() if engine == nil { engine = gin.New() } @@ -89,11 +89,11 @@ func run() error { srv := &http.Server{ Addr: fmt.Sprintf("%s:%d", config.ApplicationConfig.Host, config.ApplicationConfig.Port), - Handler: app.Runtime.GetEngine(), + Handler: sdk.Runtime.GetEngine(), } go func() { jobs.InitJob() - jobs.Setup(app.Runtime.GetDb()) + jobs.Setup(sdk.Runtime.GetDb()) }() @@ -112,20 +112,20 @@ func run() error { } } }() - fmt.Println(tools.Red(string(global.LogoContent))) + fmt.Println(pkg.Red(string(global.LogoContent))) tip() - fmt.Println(tools.Green("Server run at:")) + fmt.Println(pkg.Green("Server run at:")) fmt.Printf("- Local: http://localhost:%d/ \r\n", config.ApplicationConfig.Port) - fmt.Printf("- Network: http://%s:%d/ \r\n", tools.GetLocaHonst(), config.ApplicationConfig.Port) - fmt.Println(tools.Green("Swagger run at:")) + fmt.Printf("- Network: http://%s:%d/ \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port) + fmt.Println(pkg.Green("Swagger run at:")) fmt.Printf("- Local: http://localhost:%d/swagger/index.html \r\n", config.ApplicationConfig.Port) - fmt.Printf("- Network: http://%s:%d/swagger/index.html \r\n", tools.GetLocaHonst(), config.ApplicationConfig.Port) - fmt.Printf("%s Enter Control + C Shutdown Server \r\n", tools.GetCurrentTimeStr()) + fmt.Printf("- Network: http://%s:%d/swagger/index.html \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port) + fmt.Printf("%s Enter Control + C Shutdown Server \r\n", pkg.GetCurrentTimeStr()) // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间) quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) <-quit - fmt.Printf("%s Shutdown Server ... \r\n", tools.GetCurrentTimeStr()) + fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr()) if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server Shutdown:", err) @@ -136,6 +136,6 @@ func run() error { } func tip() { - usageStr := `欢迎使用 ` + tools.Green(`go-admin `+app.Version) + ` 可以使用 ` + tools.Red(`-h`) + ` 查看命令` + usageStr := `欢迎使用 ` + pkg.Green(`go-admin `+global.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令` fmt.Printf("%s \n\n", usageStr) } diff --git a/cmd/cobra.go b/cmd/cobra.go index 0e2769d..b4b04ce 100644 --- a/cmd/cobra.go +++ b/cmd/cobra.go @@ -3,7 +3,8 @@ package cmd import ( "errors" "fmt" - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "go-admin/common/global" "os" "github.com/spf13/cobra" @@ -12,7 +13,6 @@ import ( "go-admin/cmd/config" "go-admin/cmd/migrate" "go-admin/cmd/version" - "go-admin/tools" ) var rootCmd = &cobra.Command{ @@ -23,7 +23,7 @@ var rootCmd = &cobra.Command{ Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { tip() - return errors.New(tools.Red("requires at least one arg")) + return errors.New(pkg.Red("requires at least one arg")) } return nil }, @@ -34,7 +34,7 @@ var rootCmd = &cobra.Command{ } func tip() { - usageStr := `欢迎使用 ` + tools.Green(`go-admin `+app.Version) + ` 可以使用 ` + tools.Red(`-h`) + ` 查看命令` + usageStr := `欢迎使用 ` + pkg.Green(`go-admin `+global.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令` usageStr1 := `也可以参考 http://doc.zhangwj.com/go-admin-site/guide/ksks.html 里边的【启动】章节` fmt.Printf("%s\n", usageStr) fmt.Printf("%s\n", usageStr1) diff --git a/cmd/config/server.go b/cmd/config/server.go index 38d65af..388b4ed 100644 --- a/cmd/config/server.go +++ b/cmd/config/server.go @@ -7,7 +7,7 @@ import ( "github.com/go-admin-team/go-admin-core/config/source/file" "github.com/spf13/cobra" - "go-admin/tools/config" + "github.com/go-admin-team/go-admin-core/sdk/config" ) var ( diff --git a/cmd/migrate/migration/version/dictdata.go b/cmd/migrate/migration/version/dictdata.go index 7ee0f7c..efbc9e1 100644 --- a/cmd/migrate/migration/version/dictdata.go +++ b/cmd/migrate/migration/version/dictdata.go @@ -6,18 +6,18 @@ import ( type DictData struct { DictCode int `gorm:"primaryKey;autoIncrement;" json:"dictCode" example:"1"` //字典编码 - DictSort int `gorm:"" json:"dictSort"` //显示顺序 - DictLabel string `gorm:"size:128;" json:"dictLabel"` //数据标签 - DictValue string `gorm:"size:255;" json:"dictValue"` //数据键值 - DictType string `gorm:"size:64;" json:"dictType"` //字典类型 - CssClass string `gorm:"size:128;" json:"cssClass"` // - ListClass string `gorm:"size:128;" json:"listClass"` // - IsDefault string `gorm:"size:8;" json:"isDefault"` // - Status string `gorm:"size:4;" json:"status"` //状态 - Default string `gorm:"size:8;" json:"default"` // - CreateBy string `gorm:"size:64;" json:"createBy"` // - UpdateBy string `gorm:"size:64;" json:"updateBy"` // - Remark string `gorm:"size:255;" json:"remark"` //备注 + DictSort int `gorm:"" json:"dictSort"` //显示顺序 + DictLabel string `gorm:"size:128;" json:"dictLabel"` //数据标签 + DictValue string `gorm:"size:255;" json:"dictValue"` //数据键值 + DictType string `gorm:"size:64;" json:"dictType"` //字典类型 + CssClass string `gorm:"size:128;" json:"cssClass"` // + ListClass string `gorm:"size:128;" json:"listClass"` // + IsDefault string `gorm:"size:8;" json:"isDefault"` // + Status string `gorm:"size:4;" json:"status"` //状态 + Default string `gorm:"size:8;" json:"default"` // + CreateBy string `gorm:"size:64;" json:"createBy"` // + UpdateBy string `gorm:"size:64;" json:"updateBy"` // + Remark string `gorm:"size:255;" json:"remark"` //备注 models.BaseModel } diff --git a/cmd/migrate/server.go b/cmd/migrate/server.go index c233d46..f9ba127 100644 --- a/cmd/migrate/server.go +++ b/cmd/migrate/server.go @@ -3,7 +3,8 @@ package migrate import ( "bytes" "fmt" - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "strconv" "text/template" "time" @@ -11,14 +12,13 @@ import ( "github.com/go-admin-team/go-admin-core/config/source/file" "github.com/spf13/cobra" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg/logger" "go-admin/cmd/migrate/migration" _ "go-admin/cmd/migrate/migration/version" _ "go-admin/cmd/migrate/migration/version-local" "go-admin/common/database" "go-admin/common/models" - "go-admin/pkg/logger" - "go-admin/tools" - "go-admin/tools/config" ) var ( @@ -51,7 +51,7 @@ func run() { //1. 读取配置 config.Setup(file.NewSource, file.WithPath(configYml)) //2. 设置日志 - app.Runtime.SetLogger( + sdk.Runtime.SetLogger( logger.SetupLogger( config.LoggerConfig.Type, config.LoggerConfig.Path, @@ -68,7 +68,7 @@ func migrateModel() error { if host == "" { host = "*" } - db := app.Runtime.GetDbByKey(host) + db := sdk.Runtime.GetDbByKey(host) if config.DatabasesConfig[host].Driver == "mysql" { //初始化数据库时候用 db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4") @@ -105,9 +105,9 @@ func genFile() error { var b1 bytes.Buffer err = t1.Execute(&b1, m) if goAdmin { - tools.FileCreate(b1, "./cmd/migrate/migration/version/"+m["GenerateTime"]+"_migrate.go") + pkg.FileCreate(b1, "./cmd/migrate/migration/version/"+m["GenerateTime"]+"_migrate.go") } else { - tools.FileCreate(b1, "./cmd/migrate/migration/version-local/"+m["GenerateTime"]+"_migrate.go") + pkg.FileCreate(b1, "./cmd/migrate/migration/version-local/"+m["GenerateTime"]+"_migrate.go") } return nil } diff --git a/cmd/version/server.go b/cmd/version/server.go index 656a463..329e1ea 100644 --- a/cmd/version/server.go +++ b/cmd/version/server.go @@ -2,9 +2,8 @@ package version import ( "fmt" - "go-admin/tools/app" - "github.com/spf13/cobra" + "go-admin/common/global" ) var ( @@ -22,6 +21,6 @@ var ( ) func run() error { - fmt.Println(app.Version) + fmt.Println(global.Version) return nil } diff --git a/common/actions/create.go b/common/actions/create.go index 9a91c61..d765da3 100644 --- a/common/actions/create.go +++ b/common/actions/create.go @@ -1,22 +1,23 @@ package actions import ( - "go-admin/common/apis" "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "go-admin/common/apis" "go-admin/common/dto" "go-admin/common/models" - "go-admin/tools" - "go-admin/tools/app" ) // CreateAction 通用新增动作 func CreateAction(control dto.Control) gin.HandlerFunc { return func(c *gin.Context) { log := apis.GetRequestLogger(c) - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Error(err) return @@ -35,7 +36,7 @@ func CreateAction(control dto.Control) gin.HandlerFunc { app.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) err = db.WithContext(c).Create(object).Error if err != nil { log.Errorf("Create error: %s", err) diff --git a/common/actions/delete.go b/common/actions/delete.go index 5507e91..3555bd3 100644 --- a/common/actions/delete.go +++ b/common/actions/delete.go @@ -4,24 +4,25 @@ import ( "net/http" "github.com/gin-gonic/gin" - log "github.com/go-admin-team/go-admin-core/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "go-admin/common/dto" "go-admin/common/models" - "go-admin/tools" - "go-admin/tools/app" ) // DeleteAction 通用删除动作 func DeleteAction(control dto.Control) gin.HandlerFunc { return func(c *gin.Context) { - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Error(err) return } - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) //删除操作 req := control.Generate() err = req.Bind(c) @@ -37,7 +38,7 @@ func DeleteAction(control dto.Control) gin.HandlerFunc { return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) //数据权限检查 p := GetPermissionFromContext(c) diff --git a/common/actions/index.go b/common/actions/index.go index 5071e87..e32f947 100644 --- a/common/actions/index.go +++ b/common/actions/index.go @@ -5,25 +5,25 @@ import ( "net/http" "github.com/gin-gonic/gin" + log "github.com/go-admin-team/go-admin-core/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "gorm.io/gorm" - log "github.com/go-admin-team/go-admin-core/logger" "go-admin/common/dto" "go-admin/common/models" - "go-admin/tools" - "go-admin/tools/app" ) // IndexAction 通用查询动作 func IndexAction(m models.ActiveRecord, d dto.Index, f func() interface{}) gin.HandlerFunc { return func(c *gin.Context) { - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Error(err) return } - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) list := f() object := m.Generate() req := d.Generate() diff --git a/common/actions/permission.go b/common/actions/permission.go index 78b7d0f..e7b25f1 100644 --- a/common/actions/permission.go +++ b/common/actions/permission.go @@ -5,12 +5,12 @@ import ( "net/http" "github.com/gin-gonic/gin" - "gorm.io/gorm" - log "github.com/go-admin-team/go-admin-core/logger" - "go-admin/tools" - "go-admin/tools/app" - "go-admin/tools/config" + "github.com/go-admin-team/go-admin-core/sdk/config" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "gorm.io/gorm" ) type DataPermission struct { @@ -22,15 +22,15 @@ type DataPermission struct { func PermissionAction() gin.HandlerFunc { return func(c *gin.Context) { - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Error(err) return } - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) var p = new(DataPermission) - if userId := tools.GetUserIdStr(c); userId != "" { + if userId := user.GetUserIdStr(c); userId != "" { p, err = newDataPermission(db, userId) if err != nil { log.Errorf("MsgID[%s] PermissionAction error: %s", msgID, err) @@ -71,7 +71,7 @@ func Permission(tableName string, p *DataPermission) func(db *gorm.DB) *gorm.DB case "3": return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", p.DeptId) case "4": - return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(p.DeptId)+"%") + return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(p.DeptId)+"%") case "5": return db.Where(tableName+".create_by = ?", p.UserId) default: diff --git a/common/actions/update.go b/common/actions/update.go index 03c3d8f..c2e2e16 100644 --- a/common/actions/update.go +++ b/common/actions/update.go @@ -4,24 +4,25 @@ import ( "net/http" "github.com/gin-gonic/gin" - log "github.com/go-admin-team/go-admin-core/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + "go-admin/common/dto" "go-admin/common/models" - "go-admin/tools" - "go-admin/tools/app" ) // UpdateAction 通用更新动作 func UpdateAction(control dto.Control) gin.HandlerFunc { return func(c *gin.Context) { - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Error(err) return } - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) req := control.Generate() //更新操作 err = req.Bind(c) @@ -35,7 +36,7 @@ func UpdateAction(control dto.Control) gin.HandlerFunc { app.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) //数据权限检查 p := GetPermissionFromContext(c) diff --git a/common/actions/view.go b/common/actions/view.go index c0463d5..1eec5db 100644 --- a/common/actions/view.go +++ b/common/actions/view.go @@ -5,25 +5,25 @@ import ( "net/http" "github.com/gin-gonic/gin" + log "github.com/go-admin-team/go-admin-core/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "gorm.io/gorm" - log "github.com/go-admin-team/go-admin-core/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" "go-admin/common/dto" "go-admin/common/models" - "go-admin/tools" - "go-admin/tools/app" ) // ViewAction 通用详情动作 func ViewAction(control dto.Control, f func() interface{}) gin.HandlerFunc { return func(c *gin.Context) { - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { log.Error(err) return } - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) //查看详情 req := control.Generate() err = req.Bind(c) diff --git a/common/apis/api.go b/common/apis/api.go index 8c488c8..e88286a 100644 --- a/common/apis/api.go +++ b/common/apis/api.go @@ -2,14 +2,14 @@ package apis import ( "encoding/json" + "github.com/go-admin-team/go-admin-core/sdk/pkg" "net/http" "github.com/gin-gonic/gin" - "go-admin/pkg/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg/logger" "gorm.io/gorm" "go-admin/common/models" - "go-admin/tools" ) type Api struct { @@ -22,7 +22,7 @@ func (e *Api) GetLogger(c *gin.Context) *logger.Logger { // GetOrm 获取Orm DB func (e *Api) GetOrm(c *gin.Context) (*gorm.DB, error) { - db, err := tools.GetOrm(c) + db, err := pkg.GetOrm(c) if err != nil { e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败") return nil, err @@ -39,7 +39,7 @@ func (e *Api) Error(c *gin.Context, code int, err error, msg string) { if msg != "" { res.Msg = msg } - res.RequestId = tools.GenerateMsgIDFromContext(c) + res.RequestId = pkg.GenerateMsgIDFromContext(c) Return := res.ReturnError(code) e.setResult(c, Return, res.RequestId, code) c.AbortWithStatusJSON(http.StatusOK, Return) @@ -52,7 +52,7 @@ func (e *Api) OK(c *gin.Context, data interface{}, msg string) { if msg != "" { res.Msg = msg } - res.RequestId = tools.GenerateMsgIDFromContext(c) + res.RequestId = pkg.GenerateMsgIDFromContext(c) Return := res.ReturnOK() e.setResult(c, Return, res.RequestId, 200) c.AbortWithStatusJSON(http.StatusOK, Return) @@ -70,7 +70,7 @@ func (e *Api) PageOK(c *gin.Context, result interface{}, count int, pageIndex in // Custom 兼容函数 func (e *Api) Custom(c *gin.Context, data gin.H) { - msgID := tools.GenerateMsgIDFromContext(c) + msgID := pkg.GenerateMsgIDFromContext(c) Return := data e.setResult(c, Return, msgID, 200) c.AbortWithStatusJSON(http.StatusOK, Return) diff --git a/common/apis/request_logger.go b/common/apis/request_logger.go index 489a1d1..71f7a7e 100644 --- a/common/apis/request_logger.go +++ b/common/apis/request_logger.go @@ -2,17 +2,17 @@ package apis import ( "github.com/gin-gonic/gin" - "go-admin/pkg/logger" - "go-admin/tools" - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg/logger" "strings" ) // GetRequestLogger 获取上下文提供的日志 func GetRequestLogger(c *gin.Context) *logger.Logger { - requestId := tools.GenerateMsgIDFromContext(c) - log := app.Runtime.GetLogger().Fields(map[string]interface{}{ - strings.ToLower(tools.TrafficKey): requestId, + requestId := pkg.GenerateMsgIDFromContext(c) + log := sdk.Runtime.GetLogger().Fields(map[string]interface{}{ + strings.ToLower(pkg.TrafficKey): requestId, }) return &logger.Logger{Logger: log} } diff --git a/common/database/initialize.go b/common/database/initialize.go index 5d767b7..f1bac25 100644 --- a/common/database/initialize.go +++ b/common/database/initialize.go @@ -1,7 +1,9 @@ package database import ( - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "go-admin/common/global" . "log" "time" @@ -12,9 +14,8 @@ import ( "gorm.io/gorm/schema" log "github.com/go-admin-team/go-admin-core/logger" - mycasbin "go-admin/pkg/casbin" - "go-admin/tools" - toolsConfig "go-admin/tools/config" + toolsConfig "github.com/go-admin-team/go-admin-core/sdk/config" + mycasbin "github.com/go-admin-team/go-admin-core/sdk/pkg/casbin" ) // Setup 配置数据库 @@ -25,10 +26,10 @@ func Setup() { } func setupSimpleDatabase(host string, c *toolsConfig.Database) { - if app.Driver == "" { - app.Driver = c.Driver + if global.Driver == "" { + global.Driver = c.Driver } - log.Infof("%s => %s", host, tools.Green(c.Source)) + log.Infof("%s => %s", host, pkg.Green(c.Source)) registers := make([]toolsDB.ResolverConfigure, len(c.Registers)) for i := range c.Registers { registers[i] = toolsDB.NewResolverConfigure( @@ -54,9 +55,9 @@ func setupSimpleDatabase(host string, c *toolsConfig.Database) { }, opens[c.Driver]) if err != nil { - log.Fatal(tools.Red(c.Driver+" connect error :"), err) + log.Fatal(pkg.Red(c.Driver+" connect error :"), err) } else { - log.Info(tools.Green(c.Driver + " connect success !")) + log.Info(pkg.Green(c.Driver + " connect success !")) } e := mycasbin.Setup(db, "sys_") @@ -65,6 +66,6 @@ func setupSimpleDatabase(host string, c *toolsConfig.Database) { // global.Eloquent = db //} - app.Runtime.SetDb(host, db) - app.Runtime.SetCasbin(host, e) + sdk.Runtime.SetDb(host, db) + sdk.Runtime.SetCasbin(host, e) } diff --git a/common/dto/search.go b/common/dto/search.go index 03d237a..72cc60e 100644 --- a/common/dto/search.go +++ b/common/dto/search.go @@ -2,7 +2,7 @@ package dto import ( "github.com/go-admin-team/go-admin-core/tools/search" - "go-admin/tools/app" + "go-admin/common/global" "gorm.io/gorm" ) @@ -44,7 +44,7 @@ func MakeCondition(q interface{}) func(db *gorm.DB) *gorm.DB { GormPublic: search.GormPublic{}, Join: make([]*search.GormJoin, 0), } - search.ResolveSearchQuery(app.Driver, q, condition) + search.ResolveSearchQuery(global.Driver, q, condition) for _, join := range condition.Join { if join == nil { continue diff --git a/common/file_store/initialize.go b/common/file_store/initialize.go index 20f9391..2190b21 100644 --- a/common/file_store/initialize.go +++ b/common/file_store/initialize.go @@ -1,7 +1,6 @@ package file_store type FileStore struct { - } // Setup 配置数据库 diff --git a/common/file_store/interface.go b/common/file_store/interface.go index f22f6a7..5ba5c42 100644 --- a/common/file_store/interface.go +++ b/common/file_store/interface.go @@ -3,4 +3,4 @@ package file_store type FileStoreType interface { Setup() error UpLoad(yourObjectName string, localFile string) error -} \ No newline at end of file +} diff --git a/common/global/adm.go b/common/global/adm.go new file mode 100644 index 0000000..d5da41c --- /dev/null +++ b/common/global/adm.go @@ -0,0 +1,12 @@ +package global + +const ( + // go-admin Version Info + Version = "1.3.0-rc.0" +) + +var ( + Source string + Driver string + DBName string +) diff --git a/common/global/casbin.go b/common/global/casbin.go index c8ecce7..2770630 100644 --- a/common/global/casbin.go +++ b/common/global/casbin.go @@ -3,14 +3,14 @@ package global import ( "github.com/casbin/casbin/v2" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk" "go-admin/common/apis" - "go-admin/tools/app" ) func LoadPolicy(c *gin.Context) (*casbin.SyncedEnforcer, error) { log := apis.GetRequestLogger(c) - if err := app.Runtime.GetCasbinKey(c.Request.Host).LoadPolicy(); err == nil { - return app.Runtime.GetCasbinKey(c.Request.Host), err + if err := sdk.Runtime.GetCasbinKey(c.Request.Host).LoadPolicy(); err == nil { + return sdk.Runtime.GetCasbinKey(c.Request.Host), err } else { log.Errorf("casbin rbac_model or policy init error, %s ", err.Error()) return nil, err diff --git a/common/middleware/db.go b/common/middleware/db.go index 5c0cd8a..308e9df 100644 --- a/common/middleware/db.go +++ b/common/middleware/db.go @@ -2,10 +2,10 @@ package middleware import ( "github.com/gin-gonic/gin" - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" ) func WithContextDb(c *gin.Context) { - c.Set("db", app.Runtime.GetDbByKey(c.Request.Host)) + c.Set("db", sdk.Runtime.GetDbByKey(c.Request.Host)) c.Next() } diff --git a/common/middleware/log.go b/common/middleware/log.go deleted file mode 100644 index e91e45d..0000000 --- a/common/middleware/log.go +++ /dev/null @@ -1,9 +0,0 @@ -package middleware - -import "github.com/gin-gonic/gin" - -func SetLogger() gin.HandlerFunc { - return func(ctx *gin.Context) { - - } -} diff --git a/app/admin/middleware/permission.go b/common/middleware/permission.go similarity index 85% rename from app/admin/middleware/permission.go rename to common/middleware/permission.go index c48e9b3..9c71999 100644 --- a/app/admin/middleware/permission.go +++ b/common/middleware/permission.go @@ -1,13 +1,14 @@ package middleware import ( - "go-admin/common/apis" "net/http" "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + "github.com/go-admin-team/go-admin-core/sdk/pkg/response" - "go-admin/pkg/jwtauth" - "go-admin/tools/app" + "go-admin/common/apis" ) //权限检查中间件 @@ -16,7 +17,7 @@ func AuthCheckRole() gin.HandlerFunc { log := apis.GetRequestLogger(c) data, _ := c.Get(jwtauth.JwtPayloadKey) v := data.(jwtauth.MapClaims) - e := app.Runtime.GetCasbinKey(c.Request.Host) + e := sdk.Runtime.GetCasbinKey(c.Request.Host) var res bool var err error //检查权限 diff --git a/common/models/by.go b/common/models/by.go index 055135f..15d3b42 100644 --- a/common/models/by.go +++ b/common/models/by.go @@ -27,4 +27,4 @@ type ModelTime struct { CreatedAt time.Time `json:"createdAt" gorm:"comment:创建时间"` UpdatedAt time.Time `json:"updatedAt" gorm:"comment:最后更新时间"` DeletedAt gorm.DeletedAt `json:"-" gorm:"index;comment:删除时间"` -} \ No newline at end of file +} diff --git a/common/models/response.go b/common/models/response.go index 2bf6f72..8ee0625 100644 --- a/common/models/response.go +++ b/common/models/response.go @@ -27,4 +27,4 @@ func (res *Response) ReturnOK() *Response { func (res *Response) ReturnError(code int) *Response { res.Code = code return res -} \ No newline at end of file +} diff --git a/common/models/user.go b/common/models/user.go index 0ecc338..6053bb3 100644 --- a/common/models/user.go +++ b/common/models/user.go @@ -3,7 +3,7 @@ package models import ( "gorm.io/gorm" - "go-admin/pkg" + "github.com/go-admin-team/go-admin-core/sdk/pkg" ) // BaseUser 密码登录基础用户 diff --git a/common/service/service.go b/common/service/service.go index d6cbb51..87e0cd6 100644 --- a/common/service/service.go +++ b/common/service/service.go @@ -1,7 +1,7 @@ package service import ( - "go-admin/pkg/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg/logger" "gorm.io/gorm" ) diff --git a/examples/run.go b/examples/run.go index f797675..2bb61e2 100644 --- a/examples/run.go +++ b/examples/run.go @@ -3,13 +3,13 @@ package main import ( - "go-admin/tools/app" + "github.com/go-admin-team/go-admin-core/sdk" "log" "github.com/gin-gonic/gin" "gorm.io/gorm" - myCasbin "go-admin/pkg/casbin" + myCasbin "github.com/go-admin-team/go-admin-core/sdk/pkg/casbin" "gorm.io/driver/mysql" ) @@ -19,10 +19,10 @@ func main() { panic(err) } syncEnforce := myCasbin.Setup(db, "sys_") - app.Runtime.SetDb("*", db) - app.Runtime.SetCasbin("*", syncEnforce) + sdk.Runtime.SetDb("*", db) + sdk.Runtime.SetCasbin("*", syncEnforce) e := gin.Default() - app.Runtime.SetEngine(e) + sdk.Runtime.SetEngine(e) log.Fatal(e.Run(":8000")) } diff --git a/go.mod b/go.mod index 9c39218..5f5f888 100644 --- a/go.mod +++ b/go.mod @@ -6,37 +6,27 @@ require ( github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 github.com/alibaba/sentinel-golang v0.6.1 github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5 - github.com/casbin/casbin/v2 v2.24.0 - github.com/casbin/gorm-adapter/v3 v3.0.2 - github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/casbin/casbin/v2 v2.25.1 github.com/gin-gonic/gin v1.6.3 - github.com/go-admin-team/go-admin-core v1.2.3-0.20210305064904-6d101c8bc904 - github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210305064904-6d101c8bc904 - github.com/go-redis/redis/v7 v7.4.0 - github.com/google/uuid v1.1.2 - github.com/gorilla/websocket v1.4.2 + github.com/go-admin-team/go-admin-core v1.3.0-rc.0.0.20210309094332-92435b42cec0 + github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210309094332-92435b42cec0 // indirect + github.com/go-admin-team/go-admin-core/sdk v0.0.0-20210309094332-92435b42cec0 + github.com/google/uuid v1.2.0 github.com/mojocn/base64Captcha v1.3.1 github.com/mssola/user_agent v0.5.2 - github.com/opentracing/basictracer-go v1.1.0 // indirect github.com/opentracing/opentracing-go v1.1.0 github.com/prometheus/client_golang v1.1.0 github.com/robfig/cron/v3 v3.0.1 - github.com/robinjoseph08/redisqueue/v2 v2.1.0 - github.com/satori/go.uuid v1.2.0 - github.com/shamsher31/goimgext v1.0.0 github.com/shirou/gopsutil v2.20.7+incompatible - github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 // indirect - github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 // indirect github.com/spf13/cast v1.3.1 github.com/spf13/cobra v1.0.0 github.com/swaggo/gin-swagger v1.2.0 github.com/swaggo/swag v1.6.7 github.com/unrolled/secure v1.0.8 - golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a + golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 + golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect gorm.io/driver/mysql v1.0.4-0.20201206014609-ae5fd10184f6 gorm.io/driver/postgres v1.0.6-0.20201208020313-1ed927cfab53 gorm.io/driver/sqlite v1.1.5-0.20201206014648-c84401fbe3ba - gorm.io/gorm v1.20.12 - sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0 - sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 // indirect + gorm.io/gorm v1.21.3 ) diff --git a/go.sum b/go.sum index 704061c..843b754 100644 --- a/go.sum +++ b/go.sum @@ -35,7 +35,6 @@ github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= github.com/Microsoft/hcsshim v0.8.7-0.20191101173118-65519b62243c/go.mod h1:7xhjOwRV2+0HXGmM0jxaEu+ZiXJFoVZOTfL/dmqbrD8= -github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8 h1:xzYJEypr/85nBpB11F9br+3HUrpgb+fcm5iADzXXYEw= github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87/go.mod h1:iGLljf5n9GjT6kc0HBvyI1nOKnGQbNB66VzSNbK5iks= @@ -81,16 +80,16 @@ github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngE github.com/blang/semver v3.1.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= -github.com/bsm/redislock v0.5.0 h1:ODM11/cbuUXQqLgZWK6XQnufaTjsBE2UcwBc2EAFNDA= github.com/bsm/redislock v0.5.0/go.mod h1:qagqKlV+xiLy26iV34Y3zRPxRcJjQYbV7pZfWFeSZ8M= github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= github.com/bwmarrin/discordgo v0.20.2/go.mod h1:O9S4p+ofTFwB02em7jkpkV8M3R0/PUVOwN61zSZ0r4Q= github.com/caddyserver/certmagic v0.10.6/go.mod h1:Y8jcUBctgk/IhpAzlHKfimZNyXCkfGgRTC0orl8gROQ= -github.com/casbin/casbin/v2 v2.2.2/go.mod h1:XXtYGrs/0zlOsJMeRteEdVi/FsB0ph7KgNfjoCoJUD8= -github.com/casbin/casbin/v2 v2.24.0 h1:peiFTw+PNpAMSz7hDDz768nEwzUsBMMZNV4yFGCayI8= +github.com/casbin/casbin/v2 v2.21.0/go.mod h1:wUgota0cQbTXE6Vd+KWpg41726jFRi7upxio0sR+Xd0= github.com/casbin/casbin/v2 v2.24.0/go.mod h1:wUgota0cQbTXE6Vd+KWpg41726jFRi7upxio0sR+Xd0= -github.com/casbin/gorm-adapter/v3 v3.0.2 h1:4F2VFElwPyFzvHfgwizD2JQxk2OFLwvRFZct1np0yBg= -github.com/casbin/gorm-adapter/v3 v3.0.2/go.mod h1:mQI09sqvXfy5p6kZB5HBzZrgKWwxaJ4xMWpd5OGfHRY= +github.com/casbin/casbin/v2 v2.25.1 h1:WjDyCFo1Ctl6o2Lh9GI1FEyfHcFHCHKfTJGvijx02IE= +github.com/casbin/casbin/v2 v2.25.1/go.mod h1:wUgota0cQbTXE6Vd+KWpg41726jFRi7upxio0sR+Xd0= +github.com/casbin/gorm-adapter/v3 v3.2.0 h1:ep5hcilJb3mfg1CH4MweJlVaXw3PrRzKcyIq20MHncA= +github.com/casbin/gorm-adapter/v3 v3.2.0/go.mod h1:kaMBsBHluoYwudSbVnism8LhJeVyuuqIb5nWYS/1IBU= github.com/cenkalti/backoff/v4 v4.0.0/go.mod h1:eEew/i+1Q6OrCDZh3WiXYv3+nJwBASZ8Bog/87DQnVg= github.com/census-instrumentation/opencensus-proto v0.2.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -121,10 +120,8 @@ github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7 github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpu/goacmedns v0.0.1/go.mod h1:sesf/pNnCYwUevQEQfEwY0Y3DydlQWSGZbaMElOWxok= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.0 h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= -github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -153,7 +150,6 @@ github.com/evanphx/json-patch/v5 v5.0.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2Vvl github.com/exoscale/egoscale v0.18.1/go.mod h1:Z7OOdzzTOz1Q1PjQXumlz9Wn/CddH0zSYdCF3rnBKXE= github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= @@ -174,15 +170,17 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/ github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do= github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= -github.com/git-chglog/git-chglog v0.0.0-20190611050339-63a4e637021f h1:8l4Aw3Jmx0pLKYMkY+1b6yBPgE+rzRtA5T3vqFyI2Z8= github.com/git-chglog/git-chglog v0.0.0-20190611050339-63a4e637021f/go.mod h1:Dcsy1kii/xFyNad5JqY/d0GO5mu91sungp5xotbm3Yk= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-acme/lego/v3 v3.4.0/go.mod h1:xYbLDuxq3Hy4bMUT1t9JIuz6GWIWb3m5X+TeTHYaT7M= github.com/go-admin-team/go-admin-core v1.2.3-0.20210225031955-e373f5bcdf3f/go.mod h1:hNfmIFc75XLFdfWGeGV1ted94FGnozbKfXXVLTDJKMM= -github.com/go-admin-team/go-admin-core v1.2.3-0.20210305064904-6d101c8bc904 h1:/ceH+zpFwLzuEpn0uvvG3BVXKxbYvO4TU5b1AnP237Y= -github.com/go-admin-team/go-admin-core v1.2.3-0.20210305064904-6d101c8bc904/go.mod h1:ovPTQZXwSsq8Hd/brQsPPD/vwL7/altQa+l+78AJjhE= -github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210305064904-6d101c8bc904 h1:tRfUHqpG/GldzthSDMrHN+oWRmqZRlIyMooizskHAzE= -github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210305064904-6d101c8bc904/go.mod h1:U4GEXHDPRUv6Z5OQWzdkwrIZUZ8JIpWPPfyYsUICXWo= +github.com/go-admin-team/go-admin-core v1.3.0-rc.0.0.20210309094332-92435b42cec0 h1:/bkcbkUgPC9xkySNGGLCd4kDxPepLv7q5rGpIqb8FTE= +github.com/go-admin-team/go-admin-core v1.3.0-rc.0.0.20210309094332-92435b42cec0/go.mod h1:lWlGJ6F+9Z/F4XLLiI2o27/1JcqSXEWq/7xGGz4Fp/c= +github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210308142402-1af6382872c0/go.mod h1:U4GEXHDPRUv6Z5OQWzdkwrIZUZ8JIpWPPfyYsUICXWo= +github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210309094332-92435b42cec0 h1:MOJ9Z+nts/gOQmboOsQvfZcJkWNTwliAnxYrVeLEZN8= +github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210309094332-92435b42cec0/go.mod h1:U4GEXHDPRUv6Z5OQWzdkwrIZUZ8JIpWPPfyYsUICXWo= +github.com/go-admin-team/go-admin-core/sdk v0.0.0-20210309094332-92435b42cec0 h1:bPmisd+PtQ1RlGir25lGx4AEFkvUeHMlUJNnICSSHbg= +github.com/go-admin-team/go-admin-core/sdk v0.0.0-20210309094332-92435b42cec0/go.mod h1:PpxJOmqcUUrkWWlFNPMf67jrS0a+Lz8nFsKe8SF/9xw= github.com/go-cmd/cmd v1.0.5/go.mod h1:y8q8qlK5wQibcw63djSl/ntiHUHXHGdCkPk0j4QeW4s= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= @@ -224,7 +222,6 @@ github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1 github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= github.com/go-redis/redis/v7 v7.2.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= github.com/go-redis/redis/v7 v7.3.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= -github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4= github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= @@ -239,7 +236,6 @@ github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRx github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= @@ -285,8 +281,9 @@ github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OI github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gophercloud/gophercloud v0.3.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= @@ -295,7 +292,6 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORR github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= @@ -333,9 +329,7 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174 h1:WlZsjVhE8Af9IcZDGgJGQpNflI3+MJSBhsgT5PCtzBQ= github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df/go.mod h1:QMZY7/J/KSQEhKWFeDesPjMj+wCHReeknARU3wqlyN4= github.com/imdario/mergo v0.3.7/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= @@ -354,7 +348,7 @@ github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsU github.com/jackc/pgconn v1.4.0/go.mod h1:Y2O3ZDF0q4mMacyWV3AstPJpeHXWGEetiFttmq5lahk= github.com/jackc/pgconn v1.5.0/go.mod h1:QeD3lBfpTFe8WUnPZWN5KY/mB8FGMIYRdd8P8Jr0fAI= github.com/jackc/pgconn v1.5.1-0.20200601181101-fa742c524853/go.mod h1:QeD3lBfpTFe8WUnPZWN5KY/mB8FGMIYRdd8P8Jr0fAI= -github.com/jackc/pgconn v1.6.1/go.mod h1:g8mKMqmSUO6AzAvha7vy07g1rbGOlc7iF0nU0ei83hc= +github.com/jackc/pgconn v1.6.4/go.mod h1:w2pne1C2tZgP+TvjqLpOigGzNqjBgQW9dUw/4Chex78= github.com/jackc/pgconn v1.8.0 h1:FmjZ0rOyXTr1wfWs45i4a9vjnjWUAGpMuQLD9OSs+lw= github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= @@ -382,7 +376,7 @@ github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrU github.com/jackc/pgtype v1.2.0/go.mod h1:5m2OfMh1wTK7x+Fk952IDmI4nw3nPrvtQdM0ZT4WpC0= github.com/jackc/pgtype v1.3.1-0.20200510190516-8cd94a14c75a/go.mod h1:vaogEUkALtxZMCH411K+tKzNpwzCKU+AnPzBKZ+I+Po= github.com/jackc/pgtype v1.3.1-0.20200606141011-f6355165a91c/go.mod h1:cvk9Bgu/VzJ9/lxTO5R5sf80p0DiucVtN7ZxvaC4GmQ= -github.com/jackc/pgtype v1.4.0/go.mod h1:JCULISAZBFGrHaOXIIFiyfzW5VY0GRitRr8NeJsrdig= +github.com/jackc/pgtype v1.4.2/go.mod h1:JCULISAZBFGrHaOXIIFiyfzW5VY0GRitRr8NeJsrdig= github.com/jackc/pgtype v1.6.2 h1:b3pDeuhbbzBYcg5kwNmNDun4pFUD/0AAr1kLXZLeNt8= github.com/jackc/pgtype v1.6.2/go.mod h1:JCULISAZBFGrHaOXIIFiyfzW5VY0GRitRr8NeJsrdig= github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= @@ -391,7 +385,7 @@ github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQ github.com/jackc/pgx/v4 v4.5.0/go.mod h1:EpAKPLdnTorwmPUUsqrPxy5fphV18j9q3wrfRXgo+kA= github.com/jackc/pgx/v4 v4.6.1-0.20200510190926-94ba730bb1e9/go.mod h1:t3/cdRQl6fOLDxqtlyhe9UWgfIi9R8+8v8GKV5TRA/o= github.com/jackc/pgx/v4 v4.6.1-0.20200606145419-4e5062306904/go.mod h1:ZDaNWkt9sW1JMiNn0kdYBaLelIhw7Pg4qd+Vk6tw7Hg= -github.com/jackc/pgx/v4 v4.7.1/go.mod h1:nu42q3aPjuC1M0Nak4bnoprKlXPINqopEKqbq5AZSC4= +github.com/jackc/pgx/v4 v4.8.1/go.mod h1:4HOLxrl8wToZJReD04/yB20GDwf4KBYETvlHciCnwW0= github.com/jackc/pgx/v4 v4.10.0 h1:xXTl+lSiF1eFQ4U7vUL493n/1q8ZhSDP962rSKhgRZo= github.com/jackc/pgx/v4 v4.10.0/go.mod h1:QlrWebbs3kqEZPHCTGyxecvzG6tvIsYu+A5b1raylkA= github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= @@ -417,7 +411,6 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= @@ -433,7 +426,6 @@ github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= -github.com/kr/pty v1.1.8 h1:AkaSdXYQOWeaO3neb8EM634ahkXXe3jYbVh/F9lq+GI= github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -451,8 +443,9 @@ github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042/go.mod h1:TPp github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU= github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.8.0 h1:9xohqzkUwzR4Ga4ivdTcawVS89YSDVxXMa3xJX3cGzg= +github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/linode/linodego v0.10.0/go.mod h1:cziNP7pbvE3mXIPneHj0oRY8L1WtGEIKlZ8LANE4eXA= github.com/liquidweb/liquidweb-go v1.6.0/go.mod h1:UDcVnAMDkZxpw4Y7NOHkqoeiGacVLEIG/i5J9cyixzQ= github.com/lucas-clemente/quic-go v0.14.1/go.mod h1:Vn3/Fb0/77b02SGhQk36KzOUmXgVpFfizUfW5WMaqyU= @@ -468,7 +461,6 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= @@ -485,11 +477,9 @@ github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzp github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ= github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI= github.com/mattn/go-tty v0.0.0-20180219170247-931426f7535a/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= -github.com/mattn/goveralls v0.0.2 h1:7eJB6EqsPhRVxvwEXGnqdO2sJI0PTsrWoTMXEk9/OQc= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/micro/cli/v2 v2.1.2/go.mod h1:EguNh6DAoWKm9nmk+k/Rg0H3lQnDxqzu5x5srOtGtYg= github.com/micro/go-micro/v2 v2.9.1/go.mod h1:x55ZM3Puy0FyvvkR3e0ha0xsE9DFwfPSUMWAIbFY0SY= @@ -537,10 +527,8 @@ github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.1 h1:q/mM8GF/n0shIN8SaAZ0V+jnLPzen6WIVZdiwrRlMlo= github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= @@ -549,8 +537,6 @@ github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f/go.mod h1:qT5X github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= github.com/opencontainers/runtime-spec v0.1.2-0.20190507144316-5b71a03e2700/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= -github.com/opentracing/basictracer-go v1.1.0 h1:Oa1fTSBvAl8pa3U+IJYqrKm0NALwH9OsgwOqDv4xJW0= -github.com/opentracing/basictracer-go v1.1.0/go.mod h1:V2HZueSJEp879yv285Aap1BS69fQMD+MNP1mRs6mBQc= github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= @@ -559,7 +545,6 @@ github.com/ovh/go-ovh v0.0.0-20181109152953-ba5adb4cf014/go.mod h1:joRatxRJaZBsY github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= -github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= @@ -599,14 +584,12 @@ github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2/go.mod h1:7tZKc github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -github.com/robinjoseph08/redisqueue/v2 v2.1.0 h1:GactHlrxS8YSCJc4CbP1KbTObo14pieNmNWSUlquTGI= github.com/robinjoseph08/redisqueue/v2 v2.1.0/go.mod h1:fiNYBqIF/DqZxKvO6faLB6nkBtfJucuM+rDbFhZG1vs= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= -github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sacloud/libsacloud v1.26.1/go.mod h1:79ZwATmHLIFZIMd7sxA3LwzVy/B77uj3LDoToVTxDoQ= @@ -622,12 +605,7 @@ github.com/shirou/gopsutil v2.20.7+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc h1:jUIKcSPO9MoMJBbEoyE/RJoE8vz7Mb8AjvifMMwSyvY= github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 h1:bUGsEnyNbVPw06Bs80sCeARAlK8lhwqGyi6UT8ymuGk= -github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 h1:pXY9qYc/MP5zdvqWEUH6SjNiu7VhSjuVFTFiTcphaLU= -github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= @@ -675,7 +653,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1 github.com/tmc/grpc-websocket-proxy v0.0.0-20200122045848-3419fae592fc/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/toolkits/concurrent v0.0.0-20150624120057-a4371d70e3e3/go.mod h1:QDlpd3qS71vYtakd2hmdpqhJ9nwv6mD6A30bQ1BPBFE= github.com/transip/gotransip v0.0.0-20190812104329-6d8d9179b66f/go.mod h1:i0f4R4o2HM0m3DZYQWsj6/MEowD57VzoH0v3d7igeFY= -github.com/tsuyoshiwada/go-gitcmd v0.0.0-20180205145712-5f1f5f9475df h1:Y2l28Jr3vOEeYtxfVbMtVfOdAwuUqWaP9fvNKiBVeXY= github.com/tsuyoshiwada/go-gitcmd v0.0.0-20180205145712-5f1f5f9475df/go.mod h1:pnyouUty/nBr/zm3GYwTIt+qFTLWbdjeLjZmJdzJOu8= github.com/uber-go/atomic v1.3.2/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= @@ -690,7 +667,6 @@ github.com/unrolled/secure v1.0.8 h1:JaMvKbe4CRt8oyxVXn+xY+6jlqd7pyJNSVkmsBxxQsM github.com/unrolled/secure v1.0.8/go.mod h1:fO+mEan+FLB0CdEnHf6Q4ZZVNqG+5fuLFnP8p0BXDPI= github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.22.1 h1:+mkCCcOFKPnCmVYVcURKps1Xe+3zP90gSYGNfRkjoIY= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc= @@ -758,8 +734,8 @@ golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM= -golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -768,8 +744,9 @@ golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190501045829-6d32002ffd75/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/image v0.0.0-20201208152932-35266b937fa6 h1:nfeHNc1nAqecKCy2FCy4HY+soOOe5sDLJ/gZLbx6GYI= golang.org/x/image v0.0.0-20201208152932-35266b937fa6/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -818,7 +795,6 @@ golang.org/x/net v0.0.0-20190930134127-c5a3c61f89f3/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20191027093000-83d349e8ac1a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= @@ -877,6 +853,7 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -970,7 +947,6 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -gopkg.in/AlecAivazis/survey.v1 v1.8.5 h1:QoEEmn/d5BbuPIL2qvXwzJdttFFhRQFkaq+tEKb7SMI= gopkg.in/AlecAivazis/survey.v1 v1.8.5/go.mod h1:iBNOmqKz/NUbZx3bA+4hAGLRC7fSK7tgtVDT4tB22XA= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -979,7 +955,6 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= @@ -988,14 +963,12 @@ gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdOD gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.44.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/kyokomi/emoji.v1 v1.5.1 h1:beetH5mWDMzFznJ+Qzd5KVHp79YKhVUMcdO8LpRLeGw= gopkg.in/kyokomi/emoji.v1 v1.5.1/go.mod h1:N9AZ6hi1jHOPn34PsbpufQZUcKftSD7WgS2pgpmH4Lg= gopkg.in/ns1/ns1-go.v2 v2.0.0-20190730140822-b51389932cbc/go.mod h1:VV+3haRsgDiVLxyifmMBrBIuCWFBPYKbRssXB9z67Hw= gopkg.in/resty.v1 v1.9.1/go.mod h1:vo52Hzryw9PnPHcJfPsBiFW62XhNx5OczbV9y+IMpgc= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/square/go-jose.v2 v2.3.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= gopkg.in/telegram-bot-api.v4 v4.6.4/go.mod h1:5DpGO5dbumb40px+dXcwCpcjmeHNYLpk0bp3XRNvWDM= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= @@ -1007,24 +980,27 @@ gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gorm.io/driver/mysql v0.3.0/go.mod h1:A7H1JD9dKdcjeUTpTuWKEC+E1a74qzW7/zaXqKaTbfM= +gorm.io/driver/mysql v1.0.1/go.mod h1:KtqSthtg55lFp3S5kUXqlGaelnWpKitn4k1xZTnoiPw= gorm.io/driver/mysql v1.0.3/go.mod h1:twGxftLBlFgNVNakL7F+P/x9oYqoymG3YYT8cAfI9oI= gorm.io/driver/mysql v1.0.4-0.20201206014609-ae5fd10184f6 h1:GTZ4w9Fx9LTCtaUq7RDX6a1PSmo7BEwD3H1A8n365YI= gorm.io/driver/mysql v1.0.4-0.20201206014609-ae5fd10184f6/go.mod h1:2r8kyPBl12K36bLBN+vsYYHXRQcNmR+gNHOnSNVqLJs= -gorm.io/driver/postgres v0.2.6/go.mod h1:AsPyuhKFOplSmQwOPsycVKbe0dRxF8v18KZ7p9i8dIs= +gorm.io/driver/postgres v1.0.1/go.mod h1:pv4dVhHvEVrP7k/UYqdBIllbdbpB5VTz89X1O0uOrCA= gorm.io/driver/postgres v1.0.6-0.20201208020313-1ed927cfab53 h1:akdlzUX42w3fucnmRQXa76vjh5tJDC4Ur6VUoGULu4s= gorm.io/driver/postgres v1.0.6-0.20201208020313-1ed927cfab53/go.mod h1:VoA/W0CQ3ZgsKxbrSSTqpUROHGLyHs6NcgWBarc2GU4= gorm.io/driver/sqlite v1.1.5-0.20201206014648-c84401fbe3ba h1:fQaYq+ZqofXtk6EIMRj6R+arzZ1a+P4l6qZAdpNLjCE= gorm.io/driver/sqlite v1.1.5-0.20201206014648-c84401fbe3ba/go.mod h1:77oQ9J0MEOMY8ctRKoP0t3//37Hrjy2rNADq8E+KhaI= -gorm.io/driver/sqlserver v0.2.4 h1:AGofGL/TfzTZotzIHlaLISfxEKJpzj0ATbtXJW+ga1A= -gorm.io/driver/sqlserver v0.2.4/go.mod h1:TcPfkdce5b8qlCMgyUeUdm7HQa1ZzWUuxzI+odcueLA= -gorm.io/gorm v0.2.19/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= -gorm.io/gorm v0.2.23/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= +gorm.io/driver/sqlserver v1.0.4 h1:V15fszi0XAo7fbx3/cF50ngshDSN4QT0MXpWTylyPTY= +gorm.io/driver/sqlserver v1.0.4/go.mod h1:ciEo5btfITTBCj9BkoUVDvgQbUdLWQNqdFY5OGuGnRg= +gorm.io/gorm v1.9.19/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= +gorm.io/gorm v1.20.0/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= +gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= gorm.io/gorm v1.20.4/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= +gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= gorm.io/gorm v1.20.8/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= gorm.io/gorm v1.20.11/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= -gorm.io/gorm v1.20.12 h1:ebZ5KrSHzet+sqOCVdH9mTjW91L298nX3v5lVxAzSUY= gorm.io/gorm v1.20.12/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= +gorm.io/gorm v1.21.3 h1:qDFi55ZOsjZTwk5eN+uhAmHi8GysJ/qCTichM/yO7ME= +gorm.io/gorm v1.21.3/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= gorm.io/plugin/dbresolver v1.1.0 h1:cegr4DeprR6SkLIQlKhJLYxH8muFbJ4SmnojXvoeb00= gorm.io/plugin/dbresolver v1.1.0/go.mod h1:tpImigFAEejCALOttyhWqsy4vfa2Uh/vAUVnL5IRF7Y= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= @@ -1038,7 +1014,3 @@ honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt k8s.io/kubernetes v1.13.0/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= -sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0 h1:ucqkfpjg9WzSUubAO62csmucvxl4/JeW3F4I4909XkM= -sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= -sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 h1:e1sMhtVq9AfcEy8AXNb8eSg6gbzfdpYhoNqnPJa+GzI= -sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67/go.mod h1:L5q+DGLGOQFpo1snNEkLOJT2d1YTW66rWNzatr3He1k= diff --git a/pkg/cache/doc.go b/pkg/cache/doc.go deleted file mode 100644 index d50e5b1..0000000 --- a/pkg/cache/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -package cache - -// 缓存+队列套件,redis队列使用时,请参考单元测试中的配置 -// 目前支持: -// - redis -// - memory diff --git a/pkg/cache/memory.go b/pkg/cache/memory.go deleted file mode 100644 index 09ca8a7..0000000 --- a/pkg/cache/memory.go +++ /dev/null @@ -1,15 +0,0 @@ -package cache - -import ( - "github.com/go-admin-team/go-admin-core/cache" -) - -var MemoryAdapter Adapter - -func InitMemory() error { - MemoryAdapter = &cache.Memory{ - PoolNum: 100, - } - err := MemoryAdapter.Connect() - return err -} diff --git a/pkg/cache/memory_test.go b/pkg/cache/memory_test.go deleted file mode 100644 index 4bde75d..0000000 --- a/pkg/cache/memory_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package cache - -import ( - "fmt" - "testing" - "time" - - "github.com/go-admin-team/go-admin-core/cache" -) - -func TestInitMemory(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - { - "test01", - false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := InitMemory(); (err != nil) != tt.wantErr { - t.Errorf("InitRedis() error = %v, wantErr %v", err, tt.wantErr) - } - MemoryAdapter.Set("test", "1", 100) - key, _ := MemoryAdapter.Get("test") - message := &cache.MemoryMessage{} - message.Stream = "queuetest" - message.Values = map[string]interface{}{ - "key": "value", - } - MemoryAdapter.Append("queuetest", message) - MemoryAdapter.Register("queuetest", func(message cache.Message) error { - fmt.Println(message.GetValues()) - return nil - }) - go func() { - MemoryAdapter.Run() - }() - time.Sleep(time.Second) - MemoryAdapter.Shutdown() - fmt.Println(key) - }) - } -} diff --git a/pkg/cache/redis.go b/pkg/cache/redis.go deleted file mode 100644 index 0af1738..0000000 --- a/pkg/cache/redis.go +++ /dev/null @@ -1,32 +0,0 @@ -package cache - -import ( - "time" - - "github.com/go-admin-team/go-admin-core/cache" - "github.com/go-redis/redis/v7" - "github.com/robinjoseph08/redisqueue/v2" -) - -var RedisAdapter Adapter - -func InitRedis() error { - RedisAdapter = &cache.Redis{ - ConnectOption: &redis.Options{ - Addr: "127.0.0.1:6379", - }, - ConsumerOptions: &redisqueue.ConsumerOptions{ - VisibilityTimeout: 60 * time.Second, - BlockingTimeout: 5 * time.Second, - ReclaimInterval: 1 * time.Second, - BufferSize: 100, - Concurrency: 10, - }, - ProducerOptions: &redisqueue.ProducerOptions{ - StreamMaxLength: 100, - ApproximateMaxLength: true, - }, - } - err := RedisAdapter.Connect() - return err -} diff --git a/pkg/cache/redis_test.go b/pkg/cache/redis_test.go deleted file mode 100644 index 5056b2e..0000000 --- a/pkg/cache/redis_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package cache - -import ( - "fmt" - "testing" - "time" - - "github.com/go-admin-team/go-admin-core/cache" -) - -func TestInitRedis(t *testing.T) { - tests := []struct { - name string - wantErr bool - }{ - { - "test01", - false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := InitRedis(); (err != nil) != tt.wantErr { - t.Errorf("InitRedis() error = %v, wantErr %v", err, tt.wantErr) - } - RedisAdapter.Set("test", "1", 100) - key, _ := RedisAdapter.Get("test") - message := &cache.RedisMessage{} - message.Stream = "queuetest" - message.Values = map[string]interface{}{ - "key": "value", - } - RedisAdapter.Append("queuetest", message) - RedisAdapter.Register("queuetest", func(message cache.Message) error { - fmt.Println(message.GetValues()) - return nil - }) - go func() { - RedisAdapter.Run() - }() - time.Sleep(time.Second) - RedisAdapter.Shutdown() - fmt.Println(key) - }) - } -} diff --git a/pkg/cache/type.go b/pkg/cache/type.go deleted file mode 100644 index c3a4a92..0000000 --- a/pkg/cache/type.go +++ /dev/null @@ -1,29 +0,0 @@ -package cache - -import ( - "time" - - "github.com/go-admin-team/go-admin-core/cache" -) - -type Adapter interface { - Connect() error - Get(key string) (string, error) - Set(key string, val interface{}, expire int) error - Del(key string) error - HashGet(hk, key string) (string, error) - HashDel(hk, key string) error - Increase(key string) error - Decrease(key string) error - Expire(key string, dur time.Duration) error - cache.AdapterQueue -} - -type Message interface { - SetID(string) - SetStream(string) - SetValues(map[string]interface{}) - GetID() string - GetStream() string - GetValues() map[string]interface{} -} diff --git a/pkg/casbin/log.go b/pkg/casbin/log.go deleted file mode 100644 index 6498c24..0000000 --- a/pkg/casbin/log.go +++ /dev/null @@ -1,76 +0,0 @@ -package mycasbin - -import ( - "sync/atomic" - - "github.com/go-admin-team/go-admin-core/logger" -) - -// Logger is the implementation for a Logger using golang log. -type Logger struct { - enable int32 -} - -// EnableLog controls whether print the message. -func (l *Logger) EnableLog(enable bool) { - i := 0 - if enable { - i = 1 - } - atomic.StoreInt32(&(l.enable), int32(i)) -} - -// IsEnabled returns if logger is enabled. -func (l *Logger) IsEnabled() bool { - return atomic.LoadInt32(&(l.enable)) != 0 -} - -// LogModel log info related to model. -func (l *Logger) LogModel(model [][]string) { - var str string - for i := range model { - for j := range model[i] { - str += " " + model[i][j] - } - str += "\n" - } - logger.DefaultLogger.Log(logger.InfoLevel, str) -} - -// LogEnforce log info related to enforce. -func (l *Logger) LogEnforce(matcher string, request []interface{}, result bool, explains [][]string) { - logger.DefaultLogger.Fields(map[string]interface{}{ - "matcher": matcher, - "request": request, - "result": result, - "explains": explains, - }).Log(logger.InfoLevel, nil) -} - -// LogRole log info related to role. -func (l *Logger) LogRole(roles []string) { - logger.DefaultLogger.Fields(map[string]interface{}{ - "roles": roles, - }) -} - -// LogPolicy log info related to policy. -func (l *Logger) LogPolicy(policy map[string][][]string) { - data := make(map[string]interface{}, len(policy)) - for k := range policy { - data[k] = policy[k] - } - logger.DefaultLogger.Fields(data).Log(logger.InfoLevel, nil) -} - -//func (l *Logger) Print(v ...interface{}) { -// if l.IsEnabled() { -// logger.DefaultLogger.Log(logger.InfoLevel, v...) -// } -//} -// -//func (l *Logger) Printf(format string, v ...interface{}) { -// if l.IsEnabled() { -// logger.DefaultLogger.Logf(logger.InfoLevel, format, v...) -// } -//} diff --git a/pkg/casbin/mycasbin.go b/pkg/casbin/mycasbin.go deleted file mode 100644 index e65c623..0000000 --- a/pkg/casbin/mycasbin.go +++ /dev/null @@ -1,47 +0,0 @@ -package mycasbin - -import ( - "github.com/casbin/casbin/v2" - "github.com/casbin/casbin/v2/log" - "github.com/casbin/casbin/v2/model" - gormAdapter "github.com/casbin/gorm-adapter/v3" - "gorm.io/gorm" -) - -// Initialize the model from a string. -var text = ` -[request_definition] -r = sub, obj, act - -[policy_definition] -p = sub, obj, act - -[policy_effect] -e = some(where (p.eft == allow)) - -[matchers] -m = r.sub == p.sub && (keyMatch2(r.obj, p.obj) || keyMatch(r.obj, p.obj)) && (r.act == p.act || p.act == "*") -` - -func Setup(db *gorm.DB, prefix string) *casbin.SyncedEnforcer { - Apter, err := gormAdapter.NewAdapterByDBUsePrefix(db, prefix) - if err != nil { - panic(err) - } - m, err := model.NewModelFromString(text) - if err != nil { - panic(err) - } - e, err := casbin.NewSyncedEnforcer(m, Apter) - if err != nil { - panic(err) - } - err = e.LoadPolicy() - if err != nil { - panic(err) - } - - log.SetLogger(&Logger{}) - e.EnableLog(true) - return e -} diff --git a/pkg/cronjob/gadmjob.go b/pkg/cronjob/gadmjob.go deleted file mode 100644 index 12b3875..0000000 --- a/pkg/cronjob/gadmjob.go +++ /dev/null @@ -1,12 +0,0 @@ -package cronjob - -import ( - "github.com/robfig/cron/v3" -) - -// newWithSeconds returns a Cron with the seconds field enabled. -func NewWithSeconds() *cron.Cron { - secondParser := cron.NewParser(cron.Second | cron.Minute | - cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor) - return cron.New(cron.WithParser(secondParser), cron.WithChain()) -} diff --git a/pkg/http.go b/pkg/http.go deleted file mode 100644 index 62adadc..0000000 --- a/pkg/http.go +++ /dev/null @@ -1,52 +0,0 @@ -package pkg - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "time" -) - -// 发送GET请求 -// url: 请求地址 -// response: 请求返回的内容 -func Get(url string) (string, error) { - - client := &http.Client{} - req, err := http.NewRequest("GET", url, nil) - req.Header.Set("Accept", "*/*") - req.Header.Set("Content-Type", "application/json") - if err != nil { - return "", err - } - - resp, err := client.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - result, _ := ioutil.ReadAll(resp.Body) - - return string(result), nil -} - -// 发送POST请求 -// url: 请求地址 -// data: POST请求提交的数据 -// contentType: 请求体格式,如:application/json -// content: 请求放回的内容 -func Post(url string, data interface{}, contentType string) string { - - // 超时时间:5秒 - client := &http.Client{Timeout: 5 * time.Second} - jsonStr, _ := json.Marshal(data) - resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr)) - if err != nil { - panic(err) - } - defer resp.Body.Close() - - result, _ := ioutil.ReadAll(resp.Body) - return string(result) -} diff --git a/pkg/jwtauth/jwtauth.go b/pkg/jwtauth/jwtauth.go deleted file mode 100644 index 216a7f0..0000000 --- a/pkg/jwtauth/jwtauth.go +++ /dev/null @@ -1,740 +0,0 @@ -package jwtauth - -import ( - "crypto/rsa" - "errors" - "io/ioutil" - "net/http" - "strings" - "time" - - "github.com/dgrijalva/jwt-go" - "github.com/gin-gonic/gin" -) - -const JwtPayloadKey = "JWT_PAYLOAD" - -type MapClaims map[string]interface{} - -// GinJWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response -// is returned. On success, the wrapped middleware is called, and the userID is made available as -// c.Get("userID").(string). -// Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in -// the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX -type GinJWTMiddleware struct { - // Realm name to display to the user. Required. - Realm string - - // signing algorithm - possible values are HS256, HS384, HS512 - // Optional, default is HS256. - SigningAlgorithm string - - // Secret key used for signing. Required. - Key []byte - - // Duration that a jwt token is valid. Optional, defaults to one hour. - Timeout time.Duration - - // This field allows clients to refresh their token until MaxRefresh has passed. - // Note that clients can refresh their token in the last moment of MaxRefresh. - // This means that the maximum validity timespan for a token is TokenTime + MaxRefresh. - // Optional, defaults to 0 meaning not refreshable. - MaxRefresh time.Duration - - // Callback function that should perform the authentication of the user based on login info. - // Must return user data as user identifier, it will be stored in Claim Array. Required. - // Check error (e) to determine the appropriate error message. - Authenticator func(c *gin.Context) (interface{}, error) - - // Callback function that should perform the authorization of the authenticated user. Called - // only after an authentication success. Must return true on success, false on failure. - // Optional, default to success. - Authorizator func(data interface{}, c *gin.Context) bool - - // Callback function that will be called during login. - // Using this function it is possible to add additional payload data to the webtoken. - // The data is then made available during requests via c.Get("JWT_PAYLOAD"). - // Note that the payload is not encrypted. - // The attributes mentioned on jwt.io can't be used as keys for the map. - // Optional, by default no additional data will be set. - PayloadFunc func(data interface{}) MapClaims - - // User can define own Unauthorized func. - Unauthorized func(*gin.Context, int, string) - - // User can define own LoginResponse func. - LoginResponse func(*gin.Context, int, string, time.Time) - - // User can define own RefreshResponse func. - RefreshResponse func(*gin.Context, int, string, time.Time) - - // Set the identity handler function - IdentityHandler func(*gin.Context) interface{} - - // Set the identity key - IdentityKey string - - // username - NiceKey string - - DataScopeKey string - - // rolekey - RKey string - - // roleId - RoleIdKey string - - RoleKey string - - // roleName - RoleNameKey string - - // TokenLookup is a string in the form of ":" that is used - // to extract token from the request. - // Optional. Default value "header:Authorization". - // Possible values: - // - "header:" - // - "query:" - // - "cookie:" - TokenLookup string - - // TokenHeadName is a string in the header. Default value is "Bearer" - TokenHeadName string - - // TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens. - TimeFunc func() time.Time - - // HTTP Status messages for when something in the JWT middleware fails. - // Check error (e) to determine the appropriate error message. - HTTPStatusMessageFunc func(e error, c *gin.Context) string - - // Private key file for asymmetric algorithms - PrivKeyFile string - - // Public key file for asymmetric algorithms - PubKeyFile string - - // Private key - privKey *rsa.PrivateKey - - // Public key - pubKey *rsa.PublicKey - - // Optionally return the token as a cookie - SendCookie bool - - // Allow insecure cookies for development over http - SecureCookie bool - - // Allow cookies to be accessed client side for development - CookieHTTPOnly bool - - // Allow cookie domain change for development - CookieDomain string - - // SendAuthorization allow return authorization header for every request - SendAuthorization bool - - // Disable abort() of context. - DisabledAbort bool - - // CookieName allow cookie name change for development - CookieName string -} - -var ( - // ErrMissingSecretKey indicates Secret key is required - ErrMissingSecretKey = errors.New("secret key is required") - - // ErrForbidden when HTTP status 403 is given - ErrForbidden = errors.New("you don't have permission to access this resource") - - // ErrMissingAuthenticatorFunc indicates Authenticator is required - ErrMissingAuthenticatorFunc = errors.New("ginJWTMiddleware.Authenticator func is undefined") - - // ErrMissingLoginValues indicates a user tried to authenticate without username or password - ErrMissingLoginValues = errors.New("missing Username or Password or Code") - - // ErrFailedAuthentication indicates authentication failed, could be faulty username or password - ErrFailedAuthentication = errors.New("incorrect Username or Password") - - // ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown - ErrFailedTokenCreation = errors.New("failed to create JWT Token") - - // ErrExpiredToken indicates JWT token has expired. Can't refresh. - ErrExpiredToken = errors.New("token is expired") - - // ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set - ErrEmptyAuthHeader = errors.New("auth header is empty") - - // ErrMissingExpField missing exp field in token - ErrMissingExpField = errors.New("missing exp field") - - // ErrWrongFormatOfExp field must be float64 format - ErrWrongFormatOfExp = errors.New("exp must be float64 format") - - // ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name - ErrInvalidAuthHeader = errors.New("auth header is invalid") - - // ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty - ErrEmptyQueryToken = errors.New("query token is empty") - - // ErrEmptyCookieToken can be thrown if authing with a cookie, the token cokie is empty - ErrEmptyCookieToken = errors.New("cookie token is empty") - - // ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty - ErrEmptyParamToken = errors.New("parameter token is empty") - - // ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512 - ErrInvalidSigningAlgorithm = errors.New("invalid signing algorithm") - - ErrInvalidVerificationode = errors.New("验证码错误") - - // ErrNoPrivKeyFile indicates that the given private key is unreadable - ErrNoPrivKeyFile = errors.New("private key file unreadable") - - // ErrNoPubKeyFile indicates that the given public key is unreadable - ErrNoPubKeyFile = errors.New("public key file unreadable") - - // ErrInvalidPrivKey indicates that the given private key is invalid - ErrInvalidPrivKey = errors.New("private key invalid") - - // ErrInvalidPubKey indicates the the given public key is invalid - ErrInvalidPubKey = errors.New("public key invalid") - - // IdentityKey default identity key - IdentityKey = "identity" - - NiceKey = "nice" - - DataScopeKey = "datascope" - - RKey = "r" - RoleIdKey = "roleid" - - RoleKey = "rolekey" - - RoleNameKey = "rolename" -) - -// New for check error with GinJWTMiddleware -func New(m *GinJWTMiddleware) (*GinJWTMiddleware, error) { - if err := m.MiddlewareInit(); err != nil { - return nil, err - } - - return m, nil -} - -func (mw *GinJWTMiddleware) readKeys() error { - err := mw.privateKey() - if err != nil { - return err - } - err = mw.publicKey() - if err != nil { - return err - } - return nil -} - -func (mw *GinJWTMiddleware) privateKey() error { - keyData, err := ioutil.ReadFile(mw.PrivKeyFile) - if err != nil { - return ErrNoPrivKeyFile - } - key, err := jwt.ParseRSAPrivateKeyFromPEM(keyData) - if err != nil { - return ErrInvalidPrivKey - } - mw.privKey = key - return nil -} - -func (mw *GinJWTMiddleware) publicKey() error { - keyData, err := ioutil.ReadFile(mw.PubKeyFile) - if err != nil { - return ErrNoPubKeyFile - } - key, err := jwt.ParseRSAPublicKeyFromPEM(keyData) - if err != nil { - return ErrInvalidPubKey - } - mw.pubKey = key - return nil -} - -func (mw *GinJWTMiddleware) usingPublicKeyAlgo() bool { - switch mw.SigningAlgorithm { - case "RS256", "RS512", "RS384": - return true - } - return false -} - -// MiddlewareInit initialize jwt configs. -func (mw *GinJWTMiddleware) MiddlewareInit() error { - - if mw.TokenLookup == "" { - mw.TokenLookup = "header:Authorization" - } - - if mw.SigningAlgorithm == "" { - mw.SigningAlgorithm = "HS256" - } - - if mw.TimeFunc == nil { - mw.TimeFunc = time.Now - } - - mw.TokenHeadName = strings.TrimSpace(mw.TokenHeadName) - if len(mw.TokenHeadName) == 0 { - mw.TokenHeadName = "Bearer" - } - - if mw.Authorizator == nil { - mw.Authorizator = func(data interface{}, c *gin.Context) bool { - return true - } - } - - if mw.Unauthorized == nil { - mw.Unauthorized = func(c *gin.Context, code int, message string) { - c.JSON(http.StatusOK, gin.H{ - "code": code, - "message": message, - }) - } - } - - if mw.LoginResponse == nil { - mw.LoginResponse = func(c *gin.Context, code int, token string, expire time.Time) { - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "token": token, - "expire": expire.Format(time.RFC3339), - }) - } - } - - if mw.RefreshResponse == nil { - mw.RefreshResponse = func(c *gin.Context, code int, token string, expire time.Time) { - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "token": token, - "expire": expire.Format(time.RFC3339), - }) - } - } - - if mw.IdentityKey == "" { - mw.IdentityKey = IdentityKey - } - - if mw.IdentityHandler == nil { - mw.IdentityHandler = func(c *gin.Context) interface{} { - claims := ExtractClaims(c) - return claims - } - } - - if mw.HTTPStatusMessageFunc == nil { - mw.HTTPStatusMessageFunc = func(e error, c *gin.Context) string { - return e.Error() - } - } - - if mw.Realm == "" { - mw.Realm = "gin jwt" - } - - if mw.CookieName == "" { - mw.CookieName = "jwt" - } - - if mw.usingPublicKeyAlgo() { - return mw.readKeys() - } - - if mw.Key == nil { - return ErrMissingSecretKey - } - return nil -} - -// MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface. -func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc { - return func(c *gin.Context) { - mw.middlewareImpl(c) - } -} - -func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) { - claims, err := mw.GetClaimsFromJWT(c) - if err != nil { - mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c)) - return - } - - if claims["exp"] == nil { - mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrMissingExpField, c)) - return - } - - if _, ok := claims["exp"].(float64); !ok { - mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrWrongFormatOfExp, c)) - return - } - if int64(claims["exp"].(float64)) < mw.TimeFunc().Unix() { - mw.unauthorized(c, 6401, mw.HTTPStatusMessageFunc(ErrExpiredToken, c)) - return - } - - c.Set(JwtPayloadKey, claims) - identity := mw.IdentityHandler(c) - - if identity != nil { - c.Set(mw.IdentityKey, identity) - } - - if !mw.Authorizator(identity, c) { - mw.unauthorized(c, http.StatusForbidden, mw.HTTPStatusMessageFunc(ErrForbidden, c)) - return - } - - c.Next() -} - -// GetClaimsFromJWT get claims from JWT token -func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) { - token, err := mw.ParseToken(c) - - if err != nil { - return nil, err - } - - if mw.SendAuthorization { - if v, ok := c.Get("JWT_TOKEN"); ok { - c.Header("Authorization", mw.TokenHeadName+" "+v.(string)) - } - } - - claims := MapClaims{} - for key, value := range token.Claims.(jwt.MapClaims) { - claims[key] = value - } - - return claims, nil -} - -// LoginHandler can be used by clients to get a jwt token. -// Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}. -// Reply will be of the form {"token": "TOKEN"}. -func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) { - if mw.Authenticator == nil { - mw.unauthorized(c, http.StatusInternalServerError, mw.HTTPStatusMessageFunc(ErrMissingAuthenticatorFunc, c)) - return - } - - data, err := mw.Authenticator(c) - - if err != nil { - mw.unauthorized(c, 400, mw.HTTPStatusMessageFunc(err, c)) - return - } - - // Create the token - token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) - claims := token.Claims.(jwt.MapClaims) - - if mw.PayloadFunc != nil { - for key, value := range mw.PayloadFunc(data) { - claims[key] = value - } - } - - expire := mw.TimeFunc().Add(mw.Timeout) - claims["exp"] = expire.Unix() - claims["orig_iat"] = mw.TimeFunc().Unix() - tokenString, err := mw.signedString(token) - - if err != nil { - mw.unauthorized(c, http.StatusOK, mw.HTTPStatusMessageFunc(ErrFailedTokenCreation, c)) - return - } - - // set cookie - if mw.SendCookie { - maxage := int(expire.Unix() - time.Now().Unix()) - c.SetCookie( - mw.CookieName, - tokenString, - maxage, - "/", - mw.CookieDomain, - mw.SecureCookie, - mw.CookieHTTPOnly, - ) - } - - mw.LoginResponse(c, http.StatusOK, tokenString, expire) -} - -func (mw *GinJWTMiddleware) signedString(token *jwt.Token) (string, error) { - var tokenString string - var err error - if mw.usingPublicKeyAlgo() { - tokenString, err = token.SignedString(mw.privKey) - } else { - tokenString, err = token.SignedString(mw.Key) - } - return tokenString, err -} - -// RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh. -// Shall be put under an endpoint that is using the GinJWTMiddleware. -// Reply will be of the form {"token": "TOKEN"}. -func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) { - tokenString, expire, err := mw.RefreshToken(c) - if err != nil { - mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c)) - return - } - - mw.RefreshResponse(c, http.StatusOK, tokenString, expire) -} - -// RefreshToken refresh token and check if token is expired -func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) { - claims, err := mw.CheckIfTokenExpire(c) - if err != nil { - return "", time.Now(), err - } - - // Create the token - newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) - newClaims := newToken.Claims.(jwt.MapClaims) - - for key := range claims { - newClaims[key] = claims[key] - } - - expire := mw.TimeFunc().Add(mw.Timeout) - newClaims["exp"] = expire.Unix() - newClaims["orig_iat"] = mw.TimeFunc().Unix() - tokenString, err := mw.signedString(newToken) - - if err != nil { - return "", time.Now(), err - } - - // set cookie - if mw.SendCookie { - maxage := int(expire.Unix() - time.Now().Unix()) - c.SetCookie( - mw.CookieName, - tokenString, - maxage, - "/", - mw.CookieDomain, - mw.SecureCookie, - mw.CookieHTTPOnly, - ) - } - - return tokenString, expire, nil -} - -// CheckIfTokenExpire check if token expire -func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error) { - token, err := mw.ParseToken(c) - - if err != nil { - // If we receive an error, and the error is anything other than a single - // ValidationErrorExpired, we want to return the error. - // If the error is just ValidationErrorExpired, we want to continue, as we can still - // refresh the token if it's within the MaxRefresh time. - // (see https://github.com/appleboy/gin-jwt/issues/176) - validationErr, ok := err.(*jwt.ValidationError) - if !ok || validationErr.Errors != jwt.ValidationErrorExpired { - return nil, err - } - } - - claims := token.Claims.(jwt.MapClaims) - - origIat := int64(claims["orig_iat"].(float64)) - - if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() { - return nil, ErrExpiredToken - } - - return claims, nil -} - -// TokenGenerator method that clients can use to get a jwt token. -func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) { - token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) - claims := token.Claims.(jwt.MapClaims) - - if mw.PayloadFunc != nil { - for key, value := range mw.PayloadFunc(data) { - claims[key] = value - } - } - - expire := mw.TimeFunc().UTC().Add(mw.Timeout) - claims["exp"] = expire.Unix() - claims["orig_iat"] = mw.TimeFunc().Unix() - tokenString, err := mw.signedString(token) - if err != nil { - return "", time.Time{}, err - } - - return tokenString, expire, nil -} - -func (mw *GinJWTMiddleware) jwtFromHeader(c *gin.Context, key string) (string, error) { - authHeader := c.Request.Header.Get(key) - - if authHeader == "" { - return "", ErrEmptyAuthHeader - } - - parts := strings.SplitN(authHeader, " ", 2) - if !(len(parts) == 2 && parts[0] == mw.TokenHeadName) { - return "", ErrInvalidAuthHeader - } - - return parts[1], nil -} - -func (mw *GinJWTMiddleware) jwtFromQuery(c *gin.Context, key string) (string, error) { - token := c.Query(key) - - if token == "" { - return "", ErrEmptyQueryToken - } - - return token, nil -} - -func (mw *GinJWTMiddleware) jwtFromCookie(c *gin.Context, key string) (string, error) { - cookie, _ := c.Cookie(key) - - if cookie == "" { - return "", ErrEmptyCookieToken - } - - return cookie, nil -} - -func (mw *GinJWTMiddleware) jwtFromParam(c *gin.Context, key string) (string, error) { - token := c.Param(key) - - if token == "" { - return "", ErrEmptyParamToken - } - - return token, nil -} - -// ParseToken parse jwt token from gin context -func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) { - var token string - var err error - - methods := strings.Split(mw.TokenLookup, ",") - for _, method := range methods { - if len(token) > 0 { - break - } - parts := strings.Split(strings.TrimSpace(method), ":") - k := strings.TrimSpace(parts[0]) - v := strings.TrimSpace(parts[1]) - switch k { - case "header": - token, err = mw.jwtFromHeader(c, v) - case "query": - token, err = mw.jwtFromQuery(c, v) - case "cookie": - token, err = mw.jwtFromCookie(c, v) - case "param": - token, err = mw.jwtFromParam(c, v) - } - } - - if err != nil { - return nil, err - } - - return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { - if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method { - return nil, ErrInvalidSigningAlgorithm - } - if mw.usingPublicKeyAlgo() { - return mw.pubKey, nil - } - c.Set("JWT_TOKEN", token) - - return mw.Key, nil - }) -} - -// ParseTokenString parse jwt token string -func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) { - return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { - if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method { - return nil, ErrInvalidSigningAlgorithm - } - if mw.usingPublicKeyAlgo() { - return mw.pubKey, nil - } - - return mw.Key, nil - }) -} - -func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message string) { - c.Header("WWW-Authenticate", "JWT realm="+mw.Realm) - if !mw.DisabledAbort { - c.Abort() - } - - mw.Unauthorized(c, code, message) -} - -// ExtractClaims help to extract the JWT claims -func ExtractClaims(c *gin.Context) MapClaims { - claims, exists := c.Get(JwtPayloadKey) - if !exists { - return make(MapClaims) - } - - return claims.(MapClaims) -} - -// ExtractClaimsFromToken help to extract the JWT claims from token -func ExtractClaimsFromToken(token *jwt.Token) MapClaims { - if token == nil { - return make(MapClaims) - } - - claims := MapClaims{} - for key, value := range token.Claims.(jwt.MapClaims) { - claims[key] = value - } - - return claims -} - -// GetToken help to get the JWT token string -func GetToken(c *gin.Context) string { - token, exists := c.Get("JWT_TOKEN") - if !exists { - return "" - } - - return token.(string) -} diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go deleted file mode 100644 index a1e0968..0000000 --- a/pkg/logger/logger.go +++ /dev/null @@ -1,73 +0,0 @@ -package logger - -import ( - "github.com/go-admin-team/go-admin-core/logger" - "os" -) - -// Logger 通用log个性化实现 -type Logger struct { - logger.Logger -} - -// Info info级日志输出 -func (l *Logger) Info(args ...interface{}) { - l.Logger.Log(logger.InfoLevel, args...) -} - -// Infof info级日志输出 -func (l *Logger) Infof(template string, args ...interface{}) { - l.Logger.Logf(logger.InfoLevel, template, args...) -} - -// Trace trace级日志输出 -func (l *Logger) Trace(args ...interface{}) { - l.Logger.Log(logger.TraceLevel, args...) -} - -// Tracef trace级日志输出 -func (l *Logger) Tracef(template string, args ...interface{}) { - l.Logger.Logf(logger.TraceLevel, template, args...) -} - -// Debug debug级日志输出 -func (l *Logger) Debug(args ...interface{}) { - l.Logger.Log(logger.DebugLevel, args...) -} - -// Debugf debug级日志输出 -func (l *Logger) Debugf(template string, args ...interface{}) { - l.Logger.Logf(logger.DebugLevel, template, args...) -} - -// Warn warn级日志输出 -func (l *Logger) Warn(args ...interface{}) { - l.Logger.Log(logger.WarnLevel, args...) -} - -// Warnf warn级日志输出 -func (l *Logger) Warnf(template string, args ...interface{}) { - l.Logger.Logf(logger.WarnLevel, template, args...) -} - -// Error error级日志输出 -func (l *Logger) Error(args ...interface{}) { - l.Logger.Log(logger.ErrorLevel, args...) -} - -// Errorf error级日志输出 -func (l *Logger) Errorf(template string, args ...interface{}) { - l.Logger.Logf(logger.ErrorLevel, template, args...) -} - -// Fatal fatal级日志输出 -func (l *Logger) Fatal(args ...interface{}) { - l.Logger.Log(logger.FatalLevel, args...) - os.Exit(1) -} - -// Fatalf fatal级日志输出 -func (l *Logger) Fatalf(template string, args ...interface{}) { - l.Logger.Logf(logger.FatalLevel, template, args...) - os.Exit(1) -} diff --git a/pkg/logger/setup.go b/pkg/logger/setup.go deleted file mode 100644 index c7e5eec..0000000 --- a/pkg/logger/setup.go +++ /dev/null @@ -1,53 +0,0 @@ -package logger - -import ( - "io" - "os" - - "github.com/go-admin-team/go-admin-core/debug/writer" - "github.com/go-admin-team/go-admin-core/logger" - "github.com/go-admin-team/go-admin-core/plugins/logger/zap" - - log "github.com/go-admin-team/go-admin-core/logger" - "go-admin/tools" -) - -// SetupLogger 日志 -func SetupLogger(logType, path, levelStr, outputType string) logger.Logger { - var setLogger logger.Logger - if !tools.PathExist(path) { - err := tools.PathCreate(path) - if err != nil { - log.Fatalf("create dir error: %s", err.Error()) - } - } - var err error - var output io.Writer - switch outputType { - case "file": - output, err = writer.NewFileWriter(path, "log") - if err != nil { - log.Fatal("logger setup error: %s", err.Error()) - } - default: - output = os.Stdout - } - var level logger.Level - level, err = logger.GetLevel(levelStr) - if err != nil { - log.Fatalf("get logger level error, %s", err.Error()) - } - - switch logType { - case "zap": - setLogger, err = zap.NewLogger(logger.WithLevel(level), logger.WithOutput(output), zap.WithCallerSkip(2)) - if err != nil { - log.Fatalf("new zap logger error, %s", err.Error()) - } - //case "logrus": - // setLogger = logrus.NewLogger(logger.WithLevel(level), logger.WithOutput(output), logrus.ReportCaller()) - default: - setLogger = logger.NewLogger(logger.WithLevel(level), logger.WithOutput(output)) - } - return setLogger -} diff --git a/pkg/security.go b/pkg/security.go deleted file mode 100644 index dcb030e..0000000 --- a/pkg/security.go +++ /dev/null @@ -1,67 +0,0 @@ -package pkg - -import ( - "encoding/hex" - "math/rand" - - "golang.org/x/crypto/scrypt" -) - -const ( - symbol = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~" - letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" -) - -func generateRandString(length int, s string) string { - var chars = []byte(s) - clen := len(chars) - if clen < 2 || clen > 256 { - panic("Wrong charset length for NewLenChars()") - } - maxrb := 255 - (256 % clen) - b := make([]byte, length) - r := make([]byte, length+(length/4)) // storage for random bytes. - i := 0 - for { - if _, err := rand.Read(r); err != nil { - panic("Error reading random bytes: " + err.Error()) - } - for _, rb := range r { - c := int(rb) - if c > maxrb { - continue // Skip this number to avoid modulo bias. - } - b[i] = chars[c%clen] - i++ - if i == length { - return string(b) - } - } - } -} - -// GenerateRandomKey20 生成20位随机字符串 -func GenerateRandomKey20() string { - return generateRandString(20, symbol) -} - -// GenerateRandomKey16 生成16为随机字符串 -func GenerateRandomKey16() string { - return generateRandString(16, symbol) -} - -// GenerateRandomKey6 生成6为随机字符串 -func GenerateRandomKey6() string { - return generateRandString(6, letter) -} - -// SetPassword 根据明文密码和加盐值生成密码 -func SetPassword(password string, salt string) (verify string, err error) { - var rb []byte - rb, err = scrypt.Key([]byte(password), []byte(salt), 16384, 8, 1, 32) - if err != nil { - return - } - verify = hex.EncodeToString(rb) - return -} diff --git a/pkg/table/analysis.go b/pkg/table/analysis.go deleted file mode 100644 index cd556fd..0000000 --- a/pkg/table/analysis.go +++ /dev/null @@ -1,39 +0,0 @@ -package table - -import ( - "fmt" - "hash/crc32" - "strconv" - - "gorm.io/gorm" -) - -// Crc32Hash 用于32张分表 -func Crc32Hash(src string) string { - sum := crc32.ChecksumIEEE([]byte(src)) % 32 - return strconv.Itoa(int(sum)) -} - -// Crc16Hash 用于16张分表 -func Crc16Hash(src string) string { - sum := crc32.ChecksumIEEE([]byte(src)) % 16 - return strconv.Itoa(int(sum)) -} - -// Crc8Hash 用于8张分表 -func Crc8Hash(src string) string { - sum := crc32.ChecksumIEEE([]byte(src)) % 8 - return strconv.Itoa(int(sum)) -} - -// e.g. DB.Scopes(DynamicTable(Crc32Hash, "test", "小圈圈")).Find(&tests) -// DynamicTable 设置动态表名scope params: f 分表计算函数 baseTable 基础表名 fieldValue 参与分表字段 -func DynamicTable(f func(string) string, baseTable, fieldValue string) func(db *gorm.DB) *gorm.DB { - return func(db *gorm.DB) *gorm.DB { - return db.Table(fmt.Sprintf("%s_%s", baseTable, f(fieldValue))) - } -} - -func CreateSubTable(f func(string) string) { - -} diff --git a/pkg/utils/file.go b/pkg/utils/file.go deleted file mode 100644 index f6be68c..0000000 --- a/pkg/utils/file.go +++ /dev/null @@ -1,127 +0,0 @@ -package utils - -import ( - "errors" - "io/ioutil" - "log" - "mime/multipart" - "net/http" - "os" - "path" - "strings" - - "github.com/shamsher31/goimgext" -) - -// GetSize 获取文件大小 -func GetSize(f multipart.File) (int, error) { - content, err := ioutil.ReadAll(f) - - return len(content), err -} - -// GetExt 获取文件后缀 -func GetExt(fileName string) string { - return path.Ext(fileName) -} - -// CheckExist 检查文件是否存在 -func CheckExist(src string) bool { - _, err := os.Stat(src) - - return os.IsNotExist(err) -} - -// CheckPermission 检查文件权限 -func CheckPermission(src string) bool { - _, err := os.Stat(src) - - return os.IsPermission(err) -} - -// IsNotExistMkDir 如果不存在则新建文件夹 -func IsNotExistMkDir(src string) error { - if exist := CheckExist(src); exist == false { - if err := MkDir(src); err != nil { - return err - } - } - - return nil -} - -// MkDir 新建文件夹 -func MkDir(src string) error { - err := os.MkdirAll(src, os.ModePerm) - if err != nil { - return err - } - - return nil -} - -// Open 打开文件 -func Open(name string, flag int, perm os.FileMode) (*os.File, error) { - f, err := os.OpenFile(name, flag, perm) - if err != nil { - return nil, err - } - - return f, nil -} - -// GetImgType 获取Img文件类型 -func GetImgType(p string) (string, error) { - file, err := os.Open(p) - - if err != nil { - log.Println(err) - os.Exit(1) - } - - buff := make([]byte, 512) - - _, err = file.Read(buff) - - if err != nil { - log.Println(err) - os.Exit(1) - } - - filetype := http.DetectContentType(buff) - - ext := imgext.Get() - - for i := 0; i < len(ext); i++ { - if strings.Contains(ext[i], filetype[6:len(filetype)]) { - return filetype, nil - } - } - - return "", errors.New("Invalid image type") -} - -// GetType 获取文件类型 -func GetType(p string) (string, error) { - file, err := os.Open(p) - - if err != nil { - log.Println(err) - os.Exit(1) - } - - buff := make([]byte, 512) - - _, err = file.Read(buff) - - if err != nil { - log.Println(err) - } - - filetype := http.DetectContentType(buff) - - //ext := GetExt(p) - //var list = strings.Split(filetype, "/") - //filetype = list[0] + "/" + ext - return filetype, nil -} diff --git a/pkg/utils/json_time.go b/pkg/utils/json_time.go deleted file mode 100644 index 8eb8df1..0000000 --- a/pkg/utils/json_time.go +++ /dev/null @@ -1,42 +0,0 @@ -package utils - -import ( - "database/sql/driver" - "fmt" - "time" -) - -// JSONTime format json time field by myself -type JSONTime struct { - time.Time -} - -// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S -func (t JSONTime) MarshalJSON() ([]byte, error) { - if (t == JSONTime{}) { - formatted := fmt.Sprintf("\"%s\"", "") - return []byte(formatted), nil - } else { - formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05")) - return []byte(formatted), nil - } -} - -// Value insert timestamp into mysql need this function. -func (t JSONTime) Value() (driver.Value, error) { - var zeroTime time.Time - if t.Time.UnixNano() == zeroTime.UnixNano() { - return nil, nil - } - return t.Time, nil -} - -// Scan valueof time.Time -func (t *JSONTime) Scan(v interface{}) error { - value, ok := v.(time.Time) - if ok { - *t = JSONTime{Time: value} - return nil - } - return fmt.Errorf("can not convert %v to timestamp", v) -} diff --git a/pkg/utils/response.go b/pkg/utils/response.go deleted file mode 100644 index 9288b35..0000000 --- a/pkg/utils/response.go +++ /dev/null @@ -1,60 +0,0 @@ -package utils - -import ( - "net/http" - "time" -) - -// api结构体 -type APIException struct { - Code int `json:"code"` - Success bool `json:"success"` - Msg string `json:"msg"` - Timestamp int64 `json:"timestamp"` - Result interface{} `json:"result"` -} - -// 实现接口 -func (e *APIException) Error() string { - return e.Msg -} - -func newAPIException(code int, msg string, data interface{}, success bool) *APIException { - return &APIException{ - Code: code, - Success: success, - Msg: msg, - Timestamp: time.Now().Unix(), - Result: data, - } -} - -// 500 错误处理 -func ServerError() *APIException { - return newAPIException(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError), nil, false) -} - -// 404 错误 -func NotFound() *APIException { - return newAPIException(http.StatusNotFound, http.StatusText(http.StatusNotFound), nil, false) -} - -// 未知错误 -func UnknownError(message string) *APIException { - return newAPIException(http.StatusForbidden, message, nil, false) -} - -// 参数错误 -func ParameterError(message string) *APIException { - return newAPIException(http.StatusBadRequest, message, nil, false) -} - -// 授权错误 -func AuthError(message string) *APIException { - return newAPIException(http.StatusBadRequest, message, nil, false) -} - -// 200 -func ResponseJson(message string, data interface{}, success bool) *APIException { - return newAPIException(http.StatusOK, message, data, success) -} diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go deleted file mode 100644 index fde5af7..0000000 --- a/pkg/utils/utils.go +++ /dev/null @@ -1,91 +0,0 @@ -package utils - -import ( - "crypto/md5" - "encoding/base64" - "encoding/hex" - uuid "github.com/satori/go.uuid" - "io/ioutil" - "os" - "strings" - "time" -) - -func Hmac(data string) string { - h := md5.New() - h.Write([]byte(data)) - return hex.EncodeToString(h.Sum(nil)) -} - -func IsStringEmpty(str string) bool { - return strings.Trim(str, " ") == "" -} - -func GetUUID() string { - u := uuid.NewV4() - return strings.ReplaceAll(u.String(), "-", "") -} - -func PathExists(path string) bool { - _, err := os.Stat(path) - if err == nil { - return true - } - - if os.IsNotExist(err) { - return false - } - - return false -} - -func Base64ToImage(imageBase64 string) ([]byte, error) { - image, err := base64.StdEncoding.DecodeString(imageBase64) - if err != nil { - return nil, err - } - - return image, nil -} - -func GetDirFiles(dir string) ([]string, error) { - dirList, err := ioutil.ReadDir(dir) - if err != nil { - return nil, err - } - - filesRet := make([]string, 0) - - for _, file := range dirList { - if file.IsDir() { - files, err := GetDirFiles(dir + string(os.PathSeparator) + file.Name()) - if err != nil { - return nil, err - } - - filesRet = append(filesRet, files...) - } else { - filesRet = append(filesRet, dir+string(os.PathSeparator)+file.Name()) - } - } - - return filesRet, nil -} - -func GetCurrentTimeStamp() int64 { - return time.Now().UnixNano() / 1e6 -} - -//slice去重 -func RemoveRepByMap(slc []string) []string { - result := []string{} - tempMap := map[string]byte{} - for _, e := range slc { - l := len(tempMap) - tempMap[e] = 0 - if len(tempMap) != l { - result = append(result, e) - } - } - return result -} diff --git a/pkg/ws/ws.go b/pkg/ws/ws.go deleted file mode 100644 index 071e71e..0000000 --- a/pkg/ws/ws.go +++ /dev/null @@ -1,336 +0,0 @@ -package ws - -import ( - "context" - "fmt" - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" - "go-admin/tools" - "go-admin/tools/app" - "log" - "net/http" - "sync" - "time" -) - -// Manager 所有 websocket 信息 -type Manager struct { - Group map[string]map[string]*Client - groupCount, clientCount uint - Lock sync.Mutex - Register, UnRegister chan *Client - Message chan *MessageData - GroupMessage chan *GroupMessageData - BroadCastMessage chan *BroadCastMessageData -} - -// Client 单个 websocket 信息 -type Client struct { - Id, Group string - Context context.Context - CancelFunc context.CancelFunc - Socket *websocket.Conn - Message chan []byte -} - -// messageData 单个发送数据信息 -type MessageData struct { - Id, Group string - Context context.Context - Message []byte -} - -// groupMessageData 组广播数据信息 -type GroupMessageData struct { - Group string - Message []byte -} - -// 广播发送数据信息 -type BroadCastMessageData struct { - Message []byte -} - -// 读信息,从 websocket 连接直接读取数据 -func (c *Client) Read(cxt context.Context) { - defer func(cxt context.Context) { - WebsocketManager.UnRegister <- c - log.Printf("client [%s] disconnect", c.Id) - if err := c.Socket.Close(); err != nil { - log.Printf("client [%s] disconnect err: %s", c.Id, err) - } - }(cxt) - - for { - if cxt.Err() != nil { - break - } - messageType, message, err := c.Socket.ReadMessage() - if err != nil || messageType == websocket.CloseMessage { - break - } - log.Printf("client [%s] receive message: %s", c.Id, string(message)) - c.Message <- message - } -} - -// 写信息,从 channel 变量 Send 中读取数据写入 websocket 连接 -func (c *Client) Write(cxt context.Context) { - defer func(cxt context.Context) { - log.Printf("client [%s] disconnect", c.Id) - if err := c.Socket.Close(); err != nil { - log.Printf("client [%s] disconnect err: %s", c.Id, err) - } - }(cxt) - - for { - if cxt.Err() != nil { - break - } - select { - case message, ok := <-c.Message: - if !ok { - _ = c.Socket.WriteMessage(websocket.CloseMessage, []byte{}) - return - } - log.Printf("client [%s] write message: %s", c.Id, string(message)) - err := c.Socket.WriteMessage(websocket.TextMessage, message) - if err != nil { - log.Printf("client [%s] writemessage err: %s", c.Id, err) - } - case _ = <-c.Context.Done(): - break - } - } -} - -// 启动 websocket 管理器 -func (manager *Manager) Start() { - log.Printf("websocket manage start") - for { - select { - // 注册 - case client := <-manager.Register: - log.Printf("client [%s] connect", client.Id) - log.Printf("register client [%s] to group [%s]", client.Id, client.Group) - - manager.Lock.Lock() - if manager.Group[client.Group] == nil { - manager.Group[client.Group] = make(map[string]*Client) - manager.groupCount += 1 - } - manager.Group[client.Group][client.Id] = client - manager.clientCount += 1 - manager.Lock.Unlock() - - // 注销 - case client := <-manager.UnRegister: - log.Printf("unregister client [%s] from group [%s]", client.Id, client.Group) - manager.Lock.Lock() - if mGroup, ok := manager.Group[client.Group]; ok { - if mClient, ok := mGroup[client.Id]; ok { - close(mClient.Message) - delete(mGroup, client.Id) - manager.clientCount -= 1 - if len(mGroup) == 0 { - //log.Printf("delete empty group [%s]", client.Group) - delete(manager.Group, client.Group) - manager.groupCount -= 1 - } - mClient.CancelFunc() - } - } - manager.Lock.Unlock() - - // 发送广播数据到某个组的 channel 变量 Send 中 - //case data := <-manager.boardCast: - // if groupMap, ok := manager.wsGroup[data.GroupId]; ok { - // for _, conn := range groupMap { - // conn.Send <- data.Data - // } - // } - } - } -} - -// 处理单个 client 发送数据 -func (manager *Manager) SendService() { - for { - select { - case data := <-manager.Message: - if groupMap, ok := manager.Group[data.Group]; ok { - if conn, ok := groupMap[data.Id]; ok { - conn.Message <- data.Message - } - } - } - } -} - -// 处理 group 广播数据 -func (manager *Manager) SendGroupService() { - for { - select { - // 发送广播数据到某个组的 channel 变量 Send 中 - case data := <-manager.GroupMessage: - if groupMap, ok := manager.Group[data.Group]; ok { - for _, conn := range groupMap { - conn.Message <- data.Message - } - } - } - } -} - -// 处理广播数据 -func (manager *Manager) SendAllService() { - for { - select { - case data := <-manager.BroadCastMessage: - for _, v := range manager.Group { - for _, conn := range v { - conn.Message <- data.Message - } - } - } - } -} - -// 向指定的 client 发送数据 -func (manager *Manager) Send(cxt context.Context, id string, group string, message []byte) { - data := &MessageData{ - Id: id, - Context: cxt, - Group: group, - Message: message, - } - manager.Message <- data -} - -// 向指定的 Group 广播 -func (manager *Manager) SendGroup(group string, message []byte) { - data := &GroupMessageData{ - Group: group, - Message: message, - } - manager.GroupMessage <- data -} - -// 广播 -func (manager *Manager) SendAll(message []byte) { - data := &BroadCastMessageData{ - Message: message, - } - manager.BroadCastMessage <- data -} - -// 注册 -func (manager *Manager) RegisterClient(client *Client) { - manager.Register <- client -} - -// 注销 -func (manager *Manager) UnRegisterClient(client *Client) { - manager.UnRegister <- client -} - -// 当前组个数 -func (manager *Manager) LenGroup() uint { - return manager.groupCount -} - -// 当前连接个数 -func (manager *Manager) LenClient() uint { - return manager.clientCount -} - -// 获取 wsManager 管理器信息 -func (manager *Manager) Info() map[string]interface{} { - managerInfo := make(map[string]interface{}) - managerInfo["groupLen"] = manager.LenGroup() - managerInfo["clientLen"] = manager.LenClient() - managerInfo["chanRegisterLen"] = len(manager.Register) - managerInfo["chanUnregisterLen"] = len(manager.UnRegister) - managerInfo["chanMessageLen"] = len(manager.Message) - managerInfo["chanGroupMessageLen"] = len(manager.GroupMessage) - managerInfo["chanBroadCastMessageLen"] = len(manager.BroadCastMessage) - return managerInfo -} - -// 初始化 wsManager 管理器 -var WebsocketManager = Manager{ - Group: make(map[string]map[string]*Client), - Register: make(chan *Client, 128), - UnRegister: make(chan *Client, 128), - GroupMessage: make(chan *GroupMessageData, 128), - Message: make(chan *MessageData, 128), - BroadCastMessage: make(chan *BroadCastMessageData, 128), - groupCount: 0, - clientCount: 0, -} - -// gin 处理 websocket handler -func (manager *Manager) WsClient(c *gin.Context) { - - ctx, cancel := context.WithCancel(context.Background()) - - upGrader := websocket.Upgrader{ - // cross origin domain - CheckOrigin: func(r *http.Request) bool { - return true - }, - // 处理 Sec-WebSocket-Protocol Header - Subprotocols: []string{c.GetHeader("Sec-WebSocket-Protocol")}, - } - - conn, err := upGrader.Upgrade(c.Writer, c.Request, nil) - if err != nil { - log.Printf("websocket connect error: %s", c.Param("channel")) - return - } - - fmt.Println("token: ", c.Query("token")) - - client := &Client{ - Id: c.Param("id"), - Group: c.Param("channel"), - Context: ctx, - CancelFunc: cancel, - Socket: conn, - Message: make(chan []byte, 1024), - } - - manager.RegisterClient(client) - go client.Read(ctx) - go client.Write(ctx) - time.Sleep(time.Second * 15) - - tools.FileMonitoringById(ctx, "temp/logs/job/db-20200820.log", c.Param("id"), c.Param("channel"), SendOne) -} - -func (manager *Manager) UnWsClient(c *gin.Context) { - id := c.Param("id") - group := c.Param("channel") - WsLogout(id, group) - app.OK(c, "ws close success", "success") -} - -func SendGroup(msg []byte) { - WebsocketManager.SendGroup("leffss", []byte("{\"code\":200,\"data\":"+string(msg)+"}")) - fmt.Println(WebsocketManager.Info()) -} - -func SendAll(msg []byte) { - WebsocketManager.SendAll([]byte("{\"code\":200,\"data\":" + string(msg) + "}")) - fmt.Println(WebsocketManager.Info()) -} - -func SendOne(ctx context.Context, id string, group string, msg []byte) { - WebsocketManager.Send(ctx, id, group, []byte("{\"code\":200,\"data\":"+string(msg)+"}")) - fmt.Println(WebsocketManager.Info()) -} - -func WsLogout(id string, group string) { - WebsocketManager.UnRegisterClient(&Client{Id: id, Group: group}) - fmt.Println(WebsocketManager.Info()) -} diff --git a/template/v3/actions/router_check_role.go.template b/template/v3/actions/router_check_role.go.template index 88451bd..ff76ee2 100644 --- a/template/v3/actions/router_check_role.go.template +++ b/template/v3/actions/router_check_role.go.template @@ -7,7 +7,7 @@ import ( "go-admin/app/admin/models" "go-admin/app/admin/service/dto" "go-admin/common/actions" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func init() { diff --git a/template/v3/no_actions/router_check_role.go.template b/template/v3/no_actions/router_check_role.go.template index 6caf11c..6ac60c6 100644 --- a/template/v3/no_actions/router_check_role.go.template +++ b/template/v3/no_actions/router_check_role.go.template @@ -4,7 +4,7 @@ import ( "github.com/gin-gonic/gin" "go-admin/app/admin/apis/{{.ModuleName}}" "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func init() { diff --git a/template/v3/no_actions/router_no_check_role.go.template b/template/v3/no_actions/router_no_check_role.go.template index c74691e..4764e3e 100644 --- a/template/v3/no_actions/router_no_check_role.go.template +++ b/template/v3/no_actions/router_no_check_role.go.template @@ -3,7 +3,7 @@ package router import ( "github.com/gin-gonic/gin" "go-admin/app/admin/apis/{{.ModuleName}}" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func init() { diff --git a/template/v4/actions/router_check_role.go.template b/template/v4/actions/router_check_role.go.template index f2edbcf..af8aee2 100644 --- a/template/v4/actions/router_check_role.go.template +++ b/template/v4/actions/router_check_role.go.template @@ -7,7 +7,7 @@ import ( "go-admin/app/{{.PackageName}}/models" "go-admin/app/{{.PackageName}}/service/dto" "go-admin/common/actions" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func init() { diff --git a/template/v4/dto.go.template b/template/v4/dto.go.template index a10c606..8f51bd3 100644 --- a/template/v4/dto.go.template +++ b/template/v4/dto.go.template @@ -7,7 +7,7 @@ import ( "go-admin/app/{{.PackageName}}/models" "go-admin/common/dto" "go-admin/tools" - "go-admin/pkg/logger" + "github.com/go-admin-team/go-admin-core/sdk/pkg/logger" ) type {{.ClassName}}Search struct { diff --git a/template/v4/no_actions/apis.go.template b/template/v4/no_actions/apis.go.template index f689c92..131c02b 100644 --- a/template/v4/no_actions/apis.go.template +++ b/template/v4/no_actions/apis.go.template @@ -1,15 +1,17 @@ package {{.ModuleName}} import ( - "github.com/gin-gonic/gin" - "go-admin/app/admin/service" "net/http" + "github.com/gin-gonic/gin" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + "github.com/go-admin-team/go-admin-core/sdk/pkg" + "go-admin/app/admin/models" + "go-admin/app/admin/service" "go-admin/app/admin/service/dto" "go-admin/common/actions" "go-admin/common/apis" - "go-admin/tools" ) type {{.ClassName}} struct { @@ -110,7 +112,7 @@ func (e *{{.ClassName}}) Insert{{.ClassName}}(c *gin.Context) { return } // 设置创建人 - object.SetCreateBy(tools.GetUserId(c)) + object.SetCreateBy(user.GetUserId(c)) service{{.ClassName}} := service.{{.ClassName}}{} service{{.ClassName}}.Orm = db @@ -148,7 +150,7 @@ func (e *{{.ClassName}}) Update{{.ClassName}}(c *gin.Context) { e.Error(c, http.StatusInternalServerError, err, "模型生成失败") return } - object.SetUpdateBy(tools.GetUserId(c)) + object.SetUpdateBy(user.GetUserId(c)) //数据权限检查 p := actions.GetPermissionFromContext(c) @@ -184,7 +186,7 @@ func (e *{{.ClassName}}) Delete{{.ClassName}}(c *gin.Context) { } // 设置编辑人 - control.SetUpdateBy(tools.GetUserId(c)) + control.SetUpdateBy(user.GetUserId(c)) // 数据权限检查 p := actions.GetPermissionFromContext(c) diff --git a/template/v4/no_actions/router_check_role.go.template b/template/v4/no_actions/router_check_role.go.template index 6caf11c..6ac60c6 100644 --- a/template/v4/no_actions/router_check_role.go.template +++ b/template/v4/no_actions/router_check_role.go.template @@ -4,7 +4,7 @@ import ( "github.com/gin-gonic/gin" "go-admin/app/admin/apis/{{.ModuleName}}" "go-admin/app/admin/middleware" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func init() { diff --git a/template/v4/no_actions/router_no_check_role.go.template b/template/v4/no_actions/router_no_check_role.go.template index c74691e..4764e3e 100644 --- a/template/v4/no_actions/router_no_check_role.go.template +++ b/template/v4/no_actions/router_no_check_role.go.template @@ -3,7 +3,7 @@ package router import ( "github.com/gin-gonic/gin" "go-admin/app/admin/apis/{{.ModuleName}}" - jwt "go-admin/pkg/jwtauth" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" ) func init() { diff --git a/template/v4/no_actions/service.go.template b/template/v4/no_actions/service.go.template index 65304e5..7ed5ca8 100644 --- a/template/v4/no_actions/service.go.template +++ b/template/v4/no_actions/service.go.template @@ -2,12 +2,14 @@ package service import ( "errors" + + "gorm.io/gorm" + "go-admin/app/admin/models" "go-admin/common/actions" cDto "go-admin/common/dto" "go-admin/app/admin/service/dto" "go-admin/common/service" - "gorm.io/gorm" ) type {{.ClassName}} struct { diff --git a/test/api.go.template b/test/api.go.template index f74a52c..1ae26ca 100644 --- a/test/api.go.template +++ b/test/api.go.template @@ -4,7 +4,7 @@ import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "go-admin/models" -"go-admin/pkg" +"github.com/go-admin-team/go-admin-core/sdk/pkg" "go-admin/utils" "net/http" ) @@ -123,4 +123,4 @@ pkg.HasError(err, "修改失败", 500) var res app.Response res.Msg = "删除成功" c.JSON(http.StatusOK, res.ReturnOK()) -} \ No newline at end of file +} diff --git a/tools/app/adm.go b/tools/app/adm.go deleted file mode 100644 index 73d4f50..0000000 --- a/tools/app/adm.go +++ /dev/null @@ -1,18 +0,0 @@ -package app - -import ( - "github.com/go-admin-team/go-admin-core/tools/runtime" -) - -const ( - // go-admin Version Info - Version = "1.3.0-rc.0" -) - -var Runtime runtime.Runtime = runtime.NewConfig() - -var ( - Source string - Driver string - DBName string -) diff --git a/tools/app/model.go b/tools/app/model.go deleted file mode 100644 index e9ef870..0000000 --- a/tools/app/model.go +++ /dev/null @@ -1,28 +0,0 @@ -package app - -import ( - pbErrors "github.com/go-admin-team/go-admin-core/errors" -) - -type Response struct { - pbErrors.Error - // 数据集 - Data interface{} `json:"data"` -} - -type Page struct { - List interface{} `json:"list"` - Count int `json:"count"` - PageIndex int `json:"pageIndex"` - PageSize int `json:"pageSize"` -} - -func (res *Response) ReturnOK() *Response { - res.Code = 200 - return res -} - -func (res *Response) ReturnError(code int32) *Response { - res.Code = code - return res -} diff --git a/tools/app/msg/message.go b/tools/app/msg/message.go deleted file mode 100644 index f40d18c..0000000 --- a/tools/app/msg/message.go +++ /dev/null @@ -1,11 +0,0 @@ -package msg - -var ( - CreatedSuccess = "创建成功!" - UpdatedSuccess = "更新成功!" - DeletedSuccess = "删除成功!" - DeletedFail = "删除失败!" - GetSuccess = "查询成功!" - NotFound = "未找到相关内容或者数据为空!" - TimeOut = "操作超时!" -) diff --git a/tools/app/return.go b/tools/app/return.go deleted file mode 100644 index 843b164..0000000 --- a/tools/app/return.go +++ /dev/null @@ -1,74 +0,0 @@ -package app - -import ( - "encoding/json" - "net/http" - - "github.com/gin-gonic/gin" - - log "github.com/go-admin-team/go-admin-core/logger" - "go-admin/tools" -) - -// 失败数据处理 -func Error(c *gin.Context, code int32, err error, msg string) { - msgID := tools.GenerateMsgIDFromContext(c) - var res Response - if err != nil { - res.Msg = err.Error() - } - if msg != "" { - res.Msg = msg - } - res.RequestId = tools.GenerateMsgIDFromContext(c) - Return := res.ReturnError(code) - var jsonStr []byte - jsonStr, err = json.Marshal(Return) - if err != nil { - log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error()) - } - c.Set("result", string(jsonStr)) - c.AbortWithStatusJSON(http.StatusOK, Return) -} - -// 通常成功数据处理 -func OK(c *gin.Context, data interface{}, msg string) { - msgID := tools.GenerateMsgIDFromContext(c) - var res Response - res.Data = data - if msg != "" { - res.Msg = msg - } - res.RequestId = tools.GenerateMsgIDFromContext(c) - Return := res.ReturnOK() - var jsonStr []byte - jsonStr, err := json.Marshal(Return) - if err != nil { - log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error()) - } - c.Set("result", string(jsonStr)) - c.AbortWithStatusJSON(http.StatusOK, Return) -} - -// 分页数据处理 -func PageOK(c *gin.Context, result interface{}, count int, pageIndex int, pageSize int, msg string) { - var res Page - res.List = result - res.Count = count - res.PageIndex = pageIndex - res.PageSize = pageSize - OK(c, res, msg) -} - -// 兼容函数 -func Custum(c *gin.Context, data gin.H) { - msgID := tools.GenerateMsgIDFromContext(c) - Return := data - var jsonStr []byte - jsonStr, err := json.Marshal(Return) - if err != nil { - log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error()) - } - c.Set("result", string(jsonStr)) - c.AbortWithStatusJSON(http.StatusOK, Return) -} diff --git a/tools/captcha/captcha.go b/tools/captcha/captcha.go deleted file mode 100644 index 8562e04..0000000 --- a/tools/captcha/captcha.go +++ /dev/null @@ -1,40 +0,0 @@ -package captcha - -import ( - "image/color" - - "github.com/google/uuid" - "github.com/mojocn/base64Captcha" -) - -var store = base64Captcha.DefaultMemStore - -//configJsonBody json request body. -type configJsonBody struct { - Id string - CaptchaType string - VerifyValue string - DriverAudio *base64Captcha.DriverAudio - DriverString *base64Captcha.DriverString - DriverChinese *base64Captcha.DriverChinese - DriverMath *base64Captcha.DriverMath - DriverDigit *base64Captcha.DriverDigit -} - -func DriverStringFunc() (id, b64s string, err error) { - e := configJsonBody{} - e.Id = uuid.New().String() - e.DriverString = base64Captcha.NewDriverString(46, 140, 2, 2, 4, "234567890abcdefghjkmnpqrstuvwxyz", &color.RGBA{240, 240, 246, 246}, []string{"wqy-microhei.ttc"}) - driver := e.DriverString.ConvertFonts() - cap := base64Captcha.NewCaptcha(driver, store) - return cap.Generate() -} - -func DriverDigitFunc() (id, b64s string, err error) { - e := configJsonBody{} - e.Id = uuid.New().String() - e.DriverDigit = base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80) - driver := e.DriverDigit - cap := base64Captcha.NewCaptcha(driver, store) - return cap.Generate() -} diff --git a/tools/config/application.go b/tools/config/application.go deleted file mode 100644 index af1402e..0000000 --- a/tools/config/application.go +++ /dev/null @@ -1,15 +0,0 @@ -package config - -type Application struct { - ReadTimeout int - WriterTimeout int - Host string - Port int64 - Name string - JwtSecret string - Mode string - DemoMsg string - EnableDP bool -} - -var ApplicationConfig = new(Application) diff --git a/tools/config/config.go b/tools/config/config.go deleted file mode 100644 index 6dbb52d..0000000 --- a/tools/config/config.go +++ /dev/null @@ -1,103 +0,0 @@ -package config - -import ( - "fmt" - "github.com/go-admin-team/go-admin-core/config" - "github.com/go-admin-team/go-admin-core/config/source" - "log" -) - -var ( - ExtendConfig interface{} - _watch config.Watcher - _cfg *Settings -) - -// Settings 兼容原先的配置结构 -type Settings struct { - Settings Config `yaml:"settings"` -} - -// Config 配置集合 -type Config struct { - Application *Application `yaml:"application"` - Ssl *Ssl `yaml:"ssl"` - Logger *Logger `yaml:"logger"` - Jwt *Jwt `yaml:"jwt"` - Database *Database `yaml:"database"` - Databases *map[string]*Database `yaml:"databases"` - Gen *Gen `yaml:"gen"` - Extend interface{} `yaml:"extend"` -} - -// 多db改造 -func (e *Config) multiDatabase() { - if len(*e.Databases) == 0 { - *e.Databases = map[string]*Database{ - "*": e.Database, - } - - } -} - -// Setup 载入配置文件 -func Setup(f func(opts ...source.Option) source.Source, options ...source.Option) { - c, err := config.NewConfig() - if err != nil { - log.Fatal(fmt.Sprintf("New config object fail: %s", err.Error())) - } - err = c.Load( - f(options...), - ) - if err != nil { - log.Fatal(fmt.Sprintf("Load config source fail: %s", err.Error())) - } - - _cfg = &Settings{Config{ - Application: ApplicationConfig, - Ssl: SslConfig, - Logger: LoggerConfig, - Jwt: JwtConfig, - Database: DatabaseConfig, - Databases: &DatabasesConfig, - Gen: GenConfig, - Extend: ExtendConfig, - }} - err = c.Scan(_cfg) - if err != nil { - log.Fatal(fmt.Sprintf("Scan config fail: %s", err.Error())) - } - _cfg.Settings.multiDatabase() - - _watch, err = c.Watch() - if err != nil { - log.Fatal(fmt.Sprintf("Watch config source fail: %s", err.Error())) - } -} - -// Watch 配置监听, 重载时报错,不影响运行 fixme 数据连接 redis连接还没支持动态配置 -func Watch() { - for { - v, err := _watch.Next() - if err != nil { - if err.Error() != "watch stopped" { - log.Println(fmt.Sprintf("Next config fail: %s", err.Error())) - } - break - } - err = v.Scan(_cfg) - if err != nil { - log.Println(fmt.Sprintf("Scan config fail: %s", err.Error())) - break - } - _cfg.Settings.multiDatabase() - } -} - -// Stop 停止监听 -func Stop() { - err := _watch.Stop() - if err != nil { - log.Println(err) - } -} diff --git a/tools/config/database.go b/tools/config/database.go deleted file mode 100644 index f6f1dfa..0000000 --- a/tools/config/database.go +++ /dev/null @@ -1,23 +0,0 @@ -package config - -type Database struct { - Driver string - Source string - ConnMaxIdleTime int - ConnMaxLifetime int - MaxIdleConns int - MaxOpenConns int - Registers []DBResolverConfig -} - -type DBResolverConfig struct { - Sources []string - Replicas []string - Policy string - Tables []string -} - -var ( - DatabaseConfig = new(Database) - DatabasesConfig = make(map[string]*Database) -) diff --git a/tools/config/gen.go b/tools/config/gen.go deleted file mode 100644 index 0a95003..0000000 --- a/tools/config/gen.go +++ /dev/null @@ -1,8 +0,0 @@ -package config - -type Gen struct { - DBName string - FrontPath string -} - -var GenConfig = new(Gen) diff --git a/tools/config/jwt.go b/tools/config/jwt.go deleted file mode 100644 index 811a30e..0000000 --- a/tools/config/jwt.go +++ /dev/null @@ -1,8 +0,0 @@ -package config - -type Jwt struct { - Secret string - Timeout int64 -} - -var JwtConfig = new(Jwt) diff --git a/tools/config/logger.go b/tools/config/logger.go deleted file mode 100644 index 590e5cb..0000000 --- a/tools/config/logger.go +++ /dev/null @@ -1,11 +0,0 @@ -package config - -type Logger struct { - Type string - Path string - Level string - Stdout string - EnabledDB bool -} - -var LoggerConfig = new(Logger) diff --git a/tools/config/ssl.go b/tools/config/ssl.go deleted file mode 100644 index 0f4a828..0000000 --- a/tools/config/ssl.go +++ /dev/null @@ -1,10 +0,0 @@ -package config - -type Ssl struct { - KeyStr string - Pem string - Enable bool - Domain string -} - -var SslConfig = new(Ssl) diff --git a/tools/env.go b/tools/env.go deleted file mode 100644 index 612ff82..0000000 --- a/tools/env.go +++ /dev/null @@ -1,17 +0,0 @@ -package tools - -type ( - Mode string -) - -const ( - ModeDev Mode = "dev" //开发模式 - ModeTest Mode = "test" //测试模式 - ModeProd Mode = "prod" //生产模式 - Mysql = "mysql" //mysql数据库标识 - Sqlite = "sqlite3" //sqlite -) - -func (e Mode) String() string { - return string(e) -} diff --git a/tools/file.go b/tools/file.go deleted file mode 100644 index 505395b..0000000 --- a/tools/file.go +++ /dev/null @@ -1,130 +0,0 @@ -package tools - -import ( - "bufio" - "bytes" - "context" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - "strings" - "time" -) - -func PathCreate(dir string) error { - return os.MkdirAll(dir, os.ModePerm) -} - -// PathExist 判断目录是否存在 -func PathExist(addr string) bool { - s, err := os.Stat(addr) - if err != nil { - log.Println(err) - return false - } - return s.IsDir() -} - -func FileCreate(content bytes.Buffer, name string) { - file, err := os.Create(name) - if err != nil { - log.Println(err) - } - _, err = file.WriteString(content.String()) - if err != nil { - log.Println(err) - } - file.Close() -} - -type ReplaceHelper struct { - Root string //路径 - OldText string //需要替换的文本 - NewText string //新的文本 -} - -func (h *ReplaceHelper) DoWrok() error { - - return filepath.Walk(h.Root, h.walkCallback) - -} - -func (h ReplaceHelper) walkCallback(path string, f os.FileInfo, err error) error { - - if err != nil { - return err - } - if f == nil { - return nil - } - if f.IsDir() { - log.Println("DIR:", path) - return nil - } - - //文件类型需要进行过滤 - - buf, err := ioutil.ReadFile(path) - if err != nil { - //err - return err - } - content := string(buf) - log.Printf("h.OldText: %s \n", h.OldText) - log.Printf("h.NewText: %s \n", h.NewText) - - //替换 - newContent := strings.Replace(content, h.OldText, h.NewText, -1) - - //重新写入 - ioutil.WriteFile(path, []byte(newContent), 0) - - return err -} - -func FileMonitoringById(ctx context.Context, filePth string, id string, group string, hookfn func(context.Context, string, string, []byte)) { - f, err := os.Open(filePth) - if err != nil { - log.Fatalln(err) - } - defer f.Close() - - rd := bufio.NewReader(f) - f.Seek(0, 2) - for { - if ctx.Err() != nil { - break - } - line, err := rd.ReadBytes('\n') - // 如果是文件末尾不返回 - if err == io.EOF { - time.Sleep(500 * time.Millisecond) - continue - } else if err != nil { - log.Fatalln(err) - } - go hookfn(ctx, id, group, line) - } -} - -// 获取文件大小 -func GetFileSize(filename string) int64 { - var result int64 - filepath.Walk(filename, func(path string, f os.FileInfo, err error) error { - result = f.Size() - return nil - }) - return result -} - -//获取当前路径,比如:E:/abc/data/test -func GetCurrentPath() string { - dir, err := os.Getwd() - if err != nil { - fmt.Println(err) - } - return strings.Replace(dir, "\\", "/", -1) -} diff --git a/tools/int.go b/tools/int.go deleted file mode 100644 index 3e5a63e..0000000 --- a/tools/int.go +++ /dev/null @@ -1,23 +0,0 @@ -package tools - -import ( - "math" - "strconv" -) - -func IntToString(e int) string { - return strconv.Itoa(e) -} - -func UIntToString(e uint) string { - return strconv.Itoa(int(e)) -} - -func Int64ToString(e int64) string { - return strconv.FormatInt(e, 10) -} - -func Round(f float64, n int) float64 { - pow10_n := math.Pow10(n) - return math.Trunc((f+0.5/pow10_n)*pow10_n) / pow10_n // TODO +0.5 是为了四舍五入,如果不希望这样去掉这个 -} diff --git a/tools/ip.go b/tools/ip.go deleted file mode 100644 index c120bef..0000000 --- a/tools/ip.go +++ /dev/null @@ -1,59 +0,0 @@ -package tools - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" -) - -// 获取外网ip地址 -func GetLocation(ip string) string { - if ip == "127.0.0.1" || ip == "localhost" { - return "内部IP" - } - resp, err := http.Get("https://restapi.amap.com/v3/ip?ip=" + ip + "&key=3fabc36c20379fbb9300c79b19d5d05e") - if err != nil { - panic(err) - - } - defer resp.Body.Close() - s, err := ioutil.ReadAll(resp.Body) - fmt.Printf(string(s)) - - m := make(map[string]string) - - err = json.Unmarshal(s, &m) - if err != nil { - fmt.Println("Umarshal failed:", err) - } - if m["province"] == "" { - return "未知位置" - } - return m["province"] + "-" + m["city"] -} - -// 获取局域网ip地址 -func GetLocaHonst() string { - netInterfaces, err := net.Interfaces() - if err != nil { - fmt.Println("net.Interfaces failed, err:", err.Error()) - } - - for i := 0; i < len(netInterfaces); i++ { - if (netInterfaces[i].Flags & net.FlagUp) != 0 { - addrs, _ := netInterfaces[i].Addrs() - - for _, address := range addrs { - if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ipnet.IP.To4() != nil { - return ipnet.IP.String() - } - } - } - } - - } - return "" -} diff --git a/tools/string.go b/tools/string.go deleted file mode 100644 index f0a71d4..0000000 --- a/tools/string.go +++ /dev/null @@ -1,27 +0,0 @@ -package tools - -import ( - "encoding/json" - "strconv" - "time" -) - -func StringToInt(e string) (int, error) { - return strconv.Atoi(e) -} - -func GetCurrentTimeStr() string { - return time.Now().Format("2006-01-02 15:04:05") -} - -func GetCurrentTime() time.Time { - return time.Now() -} - -func StructToJsonStr(e interface{}) (string, error) { - if b, err := json.Marshal(e); err == nil { - return string(b), err - } else { - return "", err - } -} \ No newline at end of file diff --git a/tools/textcolor.go b/tools/textcolor.go deleted file mode 100644 index d5862c4..0000000 --- a/tools/textcolor.go +++ /dev/null @@ -1,72 +0,0 @@ -package tools - -import ( - "fmt" -) - -// 前景 背景 颜色 -// --------------------------------------- -// 30 40 黑色 -// 31 41 红色 -// 32 42 绿色 -// 33 43 黄色 -// 34 44 蓝色 -// 35 45 紫红色 -// 36 46 青蓝色 -// 37 47 白色 -// -// 代码 意义 -// ------------------------- -// 0 终端默认设置 -// 1 高亮显示 -// 4 使用下划线 -// 5 闪烁 -// 7 反白显示 -// 8 不可见 - -const ( - TextBlack = iota + 30 - TextRed - TextGreen - TextYellow - TextBlue - TextMagenta - TextCyan - TextWhite -) - -func Black(msg string) string { - return SetColor(msg, 0, 0, TextBlack) -} - -func Red(msg string) string { - return SetColor(msg, 0, 0, TextRed) -} - -func Green(msg string) string { - return SetColor(msg, 0, 0, TextGreen) -} - -func Yellow(msg string) string { - return SetColor(msg, 0, 0, TextYellow) -} - -func Blue(msg string) string { - return SetColor(msg, 0, 0, TextBlue) -} - -func Magenta(msg string) string { - return SetColor(msg, 0, 0, TextMagenta) -} - -func Cyan(msg string) string { - return SetColor(msg, 0, 0, TextCyan) -} - -func White(msg string) string { - return SetColor(msg, 0, 0, TextWhite) -} - -func SetColor(msg string, conf, bg, text int) string { - return fmt.Sprintf("%c[%d;%d;%dm%s%c[0m", 0x1B, conf, bg, text, msg, 0x1B) -} diff --git a/tools/trace/trace.go b/tools/trace/trace.go deleted file mode 100644 index 3f1d0d0..0000000 --- a/tools/trace/trace.go +++ /dev/null @@ -1,81 +0,0 @@ -package trace - -import ( - "context" - "fmt" - "log" - "net" - "net/http" - "net/url" - "os" - "os/signal" - - "github.com/opentracing/opentracing-go" - "sourcegraph.com/sourcegraph/appdash" - appdashot "sourcegraph.com/sourcegraph/appdash/opentracing" - "sourcegraph.com/sourcegraph/appdash/traceapp" - - "go-admin/tools" -) - -var _server = &http.Server{} - -// Start 启动 -func Start() { - store := appdash.NewMemoryStore() - - // Listen on any available TCP port locally. - l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}) - if err != nil { - log.Fatal(err) - } - collectorPort := l.Addr().(*net.TCPAddr).Port - collectorAdd := fmt.Sprintf(":%d", collectorPort) - - // Start an Appdash collection server that will listen for spans and - // annotations and add them to the local collector (stored in-memory). - cs := appdash.NewServer(l, appdash.NewLocalCollector(store)) - go cs.Start() - - // Print the URL at which the web UI will be running. - appdashPort := 8700 - appdashURLStr := fmt.Sprintf("http://%s:%d", tools.GetLocaHonst(), appdashPort) - appdashURL, err := url.Parse(appdashURLStr) - if err != nil { - log.Fatalf("Error parsing %s: %s", appdashURLStr, err) - } - - // Start the web UI in a separate goroutine. - tapp, err := traceapp.New(nil, appdashURL) - if err != nil { - log.Fatal(err) - } - tapp.Store = store - tapp.Queryer = store - _server.Addr = fmt.Sprintf(":%d", appdashPort) - _server.Handler = tapp - go func() { - err := _server.ListenAndServe() - if err != nil { - log.Fatalf("Trace server start error: %s", err.Error()) - } - }() - fmt.Println(tools.Green("Trace server run at:")) - fmt.Printf("- Local: %s/traces\n", fmt.Sprintf("http://localhost:%d", appdashPort)) - fmt.Printf("- Network: %s/traces\n", fmt.Sprintf("http://%s:%d", tools.GetLocaHonst(), appdashPort)) - - tracer := appdashot.NewTracer(appdash.NewRemoteCollector(collectorAdd)) - opentracing.InitGlobalTracer(tracer) -} - -// Stop 停止 -func Stop(ctx context.Context) { - quit := make(chan os.Signal) - signal.Notify(quit, os.Interrupt) - fmt.Printf("%s Shutdown Server ... \r\n", tools.GetCurrentTimeStr()) - err := _server.Shutdown(ctx) - if err != nil { - log.Fatalf("Trace server shutdown error: %s", err.Error()) - } - log.Println("Trace server shutdown success") -} diff --git a/tools/url.go b/tools/url.go deleted file mode 100644 index 3f31f1c..0000000 --- a/tools/url.go +++ /dev/null @@ -1,26 +0,0 @@ -package tools - -import ( - "strings" - - "github.com/gin-gonic/gin" -) - -//获取URL中批量id并解析 -func IdsStrToIdsIntGroup(key string, c *gin.Context) []int { - return IdsStrToIdsIntGroupStr(c.Param(key)) -} - -type Ids struct { - Ids []int -} - -func IdsStrToIdsIntGroupStr(keys string) []int { - IDS := make([]int, 0) - ids := strings.Split(keys, ",") - for i := 0; i < len(ids); i++ { - ID, _ := StringToInt(ids[i]) - IDS = append(IDS, ID) - } - return IDS -} diff --git a/tools/user.go b/tools/user.go deleted file mode 100644 index 5d4e778..0000000 --- a/tools/user.go +++ /dev/null @@ -1,65 +0,0 @@ -package tools - -import ( - "fmt" - - "github.com/gin-gonic/gin" - - jwt "go-admin/pkg/jwtauth" -) - -func ExtractClaims(c *gin.Context) jwt.MapClaims { - claims, exists := c.Get(jwt.JwtPayloadKey) - if !exists { - return make(jwt.MapClaims) - } - - return claims.(jwt.MapClaims) -} - - -func GetUserId(c *gin.Context) int { - data := ExtractClaims(c) - if data["identity"] != nil { - return int((data["identity"]).(float64)) - } - fmt.Println(GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserId 缺少identity") - return 0 -} - -func GetUserIdStr(c *gin.Context) string { - data := ExtractClaims(c) - if data["identity"] != nil { - return Int64ToString(int64((data["identity"]).(float64))) - } - fmt.Println(GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserIdStr 缺少identity") - return "" -} - -func GetUserName(c *gin.Context) string { - data := ExtractClaims(c) - if data["nice"] != nil { - return (data["nice"]).(string) - } - fmt.Println(GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserName 缺少nice") - return "" -} - -func GetRoleName(c *gin.Context) string { - data := ExtractClaims(c) - if data["rolekey"] != nil { - return (data["rolekey"]).(string) - } - fmt.Println(GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetRoleName 缺少rolekey") - return "" -} - -func GetRoleId(c *gin.Context) int { - data := ExtractClaims(c) - if data["roleid"] != nil { - i := int((data["roleid"]).(float64)) - return i - } - fmt.Println(GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetRoleId 缺少roleid") - return 0 -} diff --git a/tools/utils.go b/tools/utils.go deleted file mode 100644 index 439cb2c..0000000 --- a/tools/utils.go +++ /dev/null @@ -1,83 +0,0 @@ -package tools - -import ( - "errors" - "log" - "runtime" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/google/uuid" - "golang.org/x/crypto/bcrypt" - "gorm.io/gorm" -) - -const ( - TrafficKey = "X-Request-Id" - LoggerKey = "_go-admin-logger-request" -) - -func CompareHashAndPassword(e string, p string) (bool, error) { - err := bcrypt.CompareHashAndPassword([]byte(e), []byte(p)) - if err != nil { - return false, err - } - return true, nil -} - -// Assert 条件断言 -// 当断言条件为 假 时触发 panic -// 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码 -func Assert(condition bool, msg string, code ...int) { - if !condition { - statusCode := 200 - if len(code) > 0 { - statusCode = code[0] - } - panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg) - } -} - -// HasError 错误断言 -// 当 error 不为 nil 时触发 panic -// 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码 -// 若 msg 为空,则默认为 error 中的内容 -func HasError(err error, msg string, code ...int) { - if err != nil { - statusCode := 200 - if len(code) > 0 { - statusCode = code[0] - } - if msg == "" { - msg = err.Error() - } - _, file, line, _ := runtime.Caller(1) - log.Printf("%s:%v error: %#v", file, line, err) - panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg) - } -} - -// GenerateMsgIDFromContext 生成msgID -func GenerateMsgIDFromContext(c *gin.Context) string { - requestId := c.GetHeader(TrafficKey) - if requestId == "" { - requestId = uuid.New().String() - c.Header(TrafficKey, requestId) - } - return requestId -} - -// GetOrm 获取orm连接 -func GetOrm(c *gin.Context) (*gorm.DB, error) { - idb, exist := c.Get("db") - if !exist { - return nil, errors.New("db connect not exist") - } - switch idb.(type) { - case *gorm.DB: - //新增操作 - return idb.(*gorm.DB), nil - default: - return nil, errors.New("db connect not exist") - } -}