diff --git a/.gitignore b/.gitignore
index 4286a32..d3f12f8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,4 +14,4 @@ config/settings.dev.*.yml.log
temp/logs
config/settings.dev.yml.log
config/settings.b.dev.yml
-cmd/migrate/migration/version-local/*
+cmd/migrate/migration/version_local/*
diff --git a/app/admin/apis/log/loginlog.go b/app/admin/apis/log/loginlog.go
index cfcb78a..6f36f40 100644
--- a/app/admin/apis/log/loginlog.go
+++ b/app/admin/apis/log/loginlog.go
@@ -30,12 +30,12 @@ func GetLoginLogList(c *gin.Context) {
size := c.Request.FormValue("pageSize")
if size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
index := c.Request.FormValue("pageIndex")
if index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.Username = c.Request.FormValue("username")
diff --git a/app/admin/apis/log/operlog.go b/app/admin/apis/log/operlog.go
index 3df538c..2e5a8dd 100644
--- a/app/admin/apis/log/operlog.go
+++ b/app/admin/apis/log/operlog.go
@@ -30,12 +30,12 @@ func GetOperLogList(c *gin.Context) {
size := c.Request.FormValue("pageSize")
if size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
index := c.Request.FormValue("pageIndex")
if index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.OperName = c.Request.FormValue("operName")
diff --git a/app/admin/apis/scol/scol.go b/app/admin/apis/scol/scol.go
new file mode 100644
index 0000000..6f56d61
--- /dev/null
+++ b/app/admin/apis/scol/scol.go
@@ -0,0 +1,211 @@
+package scol
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/service"
+ common "go-admin/common/models"
+ "net/http"
+
+ "go-admin/app/admin/models"
+ "go-admin/app/admin/service/dto"
+ "go-admin/common/actions"
+ "go-admin/common/apis"
+ "go-admin/common/log"
+ "go-admin/tools"
+)
+
+type Scol struct {
+ apis.Api
+}
+
+func (e *Scol) GetScolList(c *gin.Context) {
+ msgID := tools.GenerateMsgIDFromContext(c)
+ d := new(dto.ScolSearch)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ req := d.Generate()
+
+ //查询列表
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ list := make([]models.Scol, 0)
+ var count int64
+ serviceStudent := service.Scol{}
+ serviceStudent.MsgID = msgID
+ serviceStudent.Orm = db
+ err = serviceStudent.GetScolPage(req, p, &list, &count)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
+ return
+ }
+
+ e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
+}
+
+func (e *Scol) GetScol(c *gin.Context) {
+ control := new(dto.ScolById)
+ db, err := tools.GetOrm(c)
+
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //查看详情
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = control.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ serviceScol := service.Scol{}
+ serviceScol.MsgID = msgID
+ serviceScol.Orm = db
+ err = serviceScol.GetScol(req, p, &object)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
+ return
+ }
+
+ e.OK(c, object, "查看成功")
+}
+
+func (e *Scol) InsertScol(c *gin.Context) {
+ control := new(dto.ScolControl)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //新增操作
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+ // 设置创建人
+ object.SetCreateBy(tools.GetUserIdUint(c))
+
+ serviceScol := service.Scol{}
+ serviceScol.Orm = db
+ serviceScol.MsgID = msgID
+ err = serviceScol.InsertScol(object)
+ if err != nil {
+ log.Error(err)
+ e.Error(c, http.StatusInternalServerError, err, "创建失败")
+ return
+ }
+
+ e.OK(c, object.GetId(), "创建成功")
+}
+
+func (e *Scol) UpdateScol(c *gin.Context) {
+ control := new(dto.ScolControl)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ req := control.Generate()
+ //更新操作
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+ object.SetUpdateBy(tools.GetUserIdUint(c))
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ serviceScol := service.Scol{}
+ serviceScol.Orm = db
+ serviceScol.MsgID = msgID
+ err = serviceScol.UpdateScol(object, p)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+ e.OK(c, object.GetId(), "更新成功")
+}
+
+func (e *Scol) DeleteScol(c *gin.Context) {
+ control := new(dto.ScolById)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //删除操作
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+
+ // 设置编辑人
+ object.SetUpdateBy(tools.GetUserIdUint(c))
+
+ // 数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ serviceScol := service.Scol{}
+ serviceScol.Orm = db
+ serviceScol.MsgID = msgID
+
+ err = serviceScol.RemoveScol(req, object, p)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+ e.OK(c, object.GetId(), "删除成功")
+}
diff --git a/app/admin/apis/student/student.go b/app/admin/apis/student/student.go
new file mode 100644
index 0000000..039db7d
--- /dev/null
+++ b/app/admin/apis/student/student.go
@@ -0,0 +1,212 @@
+package student
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/service"
+ common "go-admin/common/models"
+ "net/http"
+
+ "go-admin/app/admin/models"
+ "go-admin/app/admin/service/dto"
+ "go-admin/common/actions"
+ "go-admin/common/apis"
+ "go-admin/common/log"
+ "go-admin/tools"
+ "go-admin/tools/app"
+)
+
+type Student struct {
+ apis.Api
+}
+
+func (e *Student) GetStudentList(c *gin.Context) {
+ msgID := tools.GenerateMsgIDFromContext(c)
+ d := new(dto.StudentSearch)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ req := d.Generate()
+
+ //查询列表
+ err = req.Bind(c)
+ if err != nil {
+ app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ list := make([]models.Student, 0)
+ var count int64
+ serviceStudent := service.Student{}
+ serviceStudent.MsgID = msgID
+ serviceStudent.Orm = db
+ err = serviceStudent.GetStudentPage(req, p, &list, &count)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
+ return
+ }
+
+ e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
+}
+
+func (e *Student) GetStudent(c *gin.Context) {
+ control := new(dto.StudentById)
+ d := new(dto.StudentSearch)
+ db, err := tools.GetOrm(c)
+
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //查看详情
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ serviceStudent := service.Student{}
+ serviceStudent.MsgID = msgID
+ serviceStudent.Orm = db
+ err = serviceStudent.GetStudent(d, p, &object)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
+ return
+ }
+
+ e.OK(c, object, "查看成功")
+}
+
+func (e *Student) InsertStudent(c *gin.Context) {
+ control := new(dto.StudentControl)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //新增操作
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+ // 设置创建人
+ object.SetCreateBy(tools.GetUserIdUint(c))
+
+ serviceStudent := service.Student{}
+ serviceStudent.Orm = db
+ serviceStudent.MsgID = msgID
+ err = serviceStudent.InsertStudent(object)
+ if err != nil {
+ log.Error(err)
+ e.Error(c, http.StatusInternalServerError, err, "创建失败")
+ return
+ }
+
+ e.OK(c, object.GetId(), "创建成功")
+}
+
+func (e *Student) UpdateStudent(c *gin.Context) {
+ control := new(dto.StudentControl)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ req := control.Generate()
+ //更新操作
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+ object.SetUpdateBy(tools.GetUserIdUint(c))
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ serviceStudent := service.Student{}
+ serviceStudent.Orm = db
+ serviceStudent.MsgID = msgID
+ err = serviceStudent.UpdateStudent(object, p)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+ e.OK(c, object.GetId(), "更新成功")
+}
+
+func (e *Student) DeleteStudent(c *gin.Context) {
+ control := new(dto.StudentById)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //删除操作
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+
+ // 设置编辑人
+ object.SetUpdateBy(tools.GetUserIdUint(c))
+
+ // 数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ serviceStudent := service.Student{}
+ serviceStudent.Orm = db
+ serviceStudent.MsgID = msgID
+ err = serviceStudent.RemoveStudent(object, p)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+ e.OK(c, object.GetId(), "删除成功")
+}
diff --git a/app/admin/apis/syscategory/syscategory.go b/app/admin/apis/syscategory/syscategory.go
index 05d2485..03181de 100644
--- a/app/admin/apis/syscategory/syscategory.go
+++ b/app/admin/apis/syscategory/syscategory.go
@@ -17,10 +17,10 @@ func GetSysCategoryList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.Name = c.Request.FormValue("name")
diff --git a/app/admin/apis/syscontent/syscontent.go b/app/admin/apis/syscontent/syscontent.go
index fd313ab..ceb851c 100644
--- a/app/admin/apis/syscontent/syscontent.go
+++ b/app/admin/apis/syscontent/syscontent.go
@@ -17,10 +17,10 @@ func GetSysContentList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.CateId = c.Request.FormValue("cateId")
diff --git a/app/admin/apis/sysjob/sysjob.go b/app/admin/apis/sysjob/sysjob.go
index 7267517..c0067b4 100644
--- a/app/admin/apis/sysjob/sysjob.go
+++ b/app/admin/apis/sysjob/sysjob.go
@@ -1,19 +1,14 @@
package sysjob
import (
- "time"
-
"github.com/gin-gonic/gin"
- "go-admin/app/admin/models"
"go-admin/app/admin/service"
- "go-admin/app/jobs"
"go-admin/common/apis"
"go-admin/common/dto"
"go-admin/common/log"
"go-admin/tools"
"go-admin/tools/app"
- "go-admin/tools/app/msg"
)
type SysJob struct {
@@ -73,56 +68,3 @@ func (e *SysJob) StartJobForService(c *gin.Context) {
}
app.OK(c, nil, s.Msg)
}
-
-func RemoveJob(c *gin.Context) {
- var data models.SysJob
- var v dto.GeneralDelDto
- err := c.BindUri(&v)
- tools.HasError(err, "", 500)
- data.JobId = v.Id
- err = data.Get(data.JobId)
- tools.HasError(err, "", 500)
- cn := jobs.Remove(data.EntryId)
-
- select {
- case res := <-cn:
- if res {
- _, _ = data.RemoveEntryID(data.EntryId)
- app.OK(c, nil, msg.DeletedSuccess)
- }
- case <-time.After(time.Second * 1):
- app.OK(c, nil, msg.TimeOut)
- }
-
-}
-
-func StartJob(c *gin.Context) {
- var data models.SysJob
- var v dto.GeneralGetDto
- err := c.BindUri(&v)
- tools.HasError(err, "", 500)
- data.JobId = v.Id
- err = data.Get(data.JobId)
- tools.HasError(err, "", 500)
- if data.JobType == 1 {
- var j = &jobs.HttpJob{}
- j.InvokeTarget = data.InvokeTarget
- j.CronExpression = data.CronExpression
- j.JobId = data.JobId
- j.Name = data.JobName
- data.EntryId, err = jobs.AddJob(j)
- } else {
- var j = &jobs.ExecJob{}
- j.InvokeTarget = data.InvokeTarget
- j.CronExpression = data.CronExpression
- j.JobId = data.JobId
- j.Name = data.JobName
- j.Args = data.Args
- data.EntryId, err = jobs.AddJob(j)
- }
-
- tools.HasError(err, "", 500)
- err = data.Update(data.JobId)
- tools.HasError(err, "", 500)
- app.OK(c, nil, msg.DeletedSuccess)
-}
diff --git a/app/admin/apis/system/config.go b/app/admin/apis/system/config.go
index 210925b..9a07a63 100644
--- a/app/admin/apis/system/config.go
+++ b/app/admin/apis/system/config.go
@@ -30,11 +30,11 @@ func GetConfigList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.ConfigKey = c.Request.FormValue("configKey")
diff --git a/app/admin/apis/system/dict/dictdata.go b/app/admin/apis/system/dict/dictdata.go
index 571420a..bd58b90 100644
--- a/app/admin/apis/system/dict/dictdata.go
+++ b/app/admin/apis/system/dict/dictdata.go
@@ -29,11 +29,11 @@ func GetDictDataList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.DictLabel = c.Request.FormValue("dictLabel")
diff --git a/app/admin/apis/system/dict/dicttype.go b/app/admin/apis/system/dict/dicttype.go
index 8a612e2..bf9fe50 100644
--- a/app/admin/apis/system/dict/dicttype.go
+++ b/app/admin/apis/system/dict/dicttype.go
@@ -29,11 +29,11 @@ func GetDictTypeList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.DictName = c.Request.FormValue("dictName")
diff --git a/app/admin/apis/system/post.go b/app/admin/apis/system/post.go
index bd7aba6..9569ed1 100644
--- a/app/admin/apis/system/post.go
+++ b/app/admin/apis/system/post.go
@@ -25,11 +25,11 @@ func GetPostList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
id := c.Request.FormValue("postId")
diff --git a/app/admin/apis/system/role.go b/app/admin/apis/system/role.go
index 94ecb31..8b42af2 100644
--- a/app/admin/apis/system/role.go
+++ b/app/admin/apis/system/role.go
@@ -27,11 +27,11 @@ func GetRoleList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.RoleKey = c.Request.FormValue("roleKey")
diff --git a/app/admin/apis/system/sysuser.go b/app/admin/apis/system/sysuser.go
index 7c0b5ac..9748ef5 100644
--- a/app/admin/apis/system/sysuser.go
+++ b/app/admin/apis/system/sysuser.go
@@ -27,12 +27,12 @@ func GetSysUserList(c *gin.Context) {
size := c.Request.FormValue("pageSize")
if size != "" {
- pageSize = tools.StrToInt(err, size)
+ pageSize, err = tools.StringToInt(size)
}
index := c.Request.FormValue("pageIndex")
if index != "" {
- pageIndex = tools.StrToInt(err, index)
+ pageIndex, err = tools.StringToInt(index)
}
data.Username = c.Request.FormValue("username")
diff --git a/app/admin/apis/tools/dbcolumns.go b/app/admin/apis/tools/dbcolumns.go
index 57f711b..c2d1966 100644
--- a/app/admin/apis/tools/dbcolumns.go
+++ b/app/admin/apis/tools/dbcolumns.go
@@ -25,11 +25,11 @@ func GetDBColumnList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools2.StrToInt(err, size)
+ pageSize, err = tools2.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools2.StrToInt(err, index)
+ pageIndex, err = tools2.StringToInt(index)
}
data.TableName = c.Request.FormValue("tableName")
diff --git a/app/admin/apis/tools/dbtables.go b/app/admin/apis/tools/dbtables.go
index 361fb04..dbe62a9 100644
--- a/app/admin/apis/tools/dbtables.go
+++ b/app/admin/apis/tools/dbtables.go
@@ -32,11 +32,11 @@ func GetDBTableList(c *gin.Context) {
}
if size := c.Request.FormValue("pageSize"); size != "" {
- pageSize = tools2.StrToInt(err, size)
+ pageSize, err = tools2.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
- pageIndex = tools2.StrToInt(err, index)
+ pageIndex, err = tools2.StringToInt(index)
}
data.TableName = c.Request.FormValue("tableName")
diff --git a/app/admin/apis/tools/gen.go b/app/admin/apis/tools/gen.go
index 6770a0d..838c43e 100644
--- a/app/admin/apis/tools/gen.go
+++ b/app/admin/apis/tools/gen.go
@@ -151,6 +151,120 @@ func GenCodeV2(c *gin.Context) {
app.OK(c, "", "Code generated successfully!")
}
+func GenCodeV3(c *gin.Context) {
+ table := tools.SysTables{}
+ id, err := tools2.StringToInt(c.Param("tableId"))
+ tools2.HasError(err, "", -1)
+ table.TableId = id
+ tab, _ := table.Get()
+
+ if tab.IsActions == 1 {
+ ActionsGenV3(tab)
+ } else {
+ NOActionsGenV3(tab)
+ }
+
+ app.OK(c, "", "Code generated successfully!")
+}
+
+func NOActionsGenV3(tab tools.SysTables) {
+
+ basePath := "template/v3/"
+ routerFile := basePath + "no_actions/router_check_role.go.template"
+
+ if tab.IsAuth == 2 {
+ routerFile = basePath + "no_actions/router_no_check_role.go.template"
+ }
+
+ t1, err := template.ParseFiles(basePath + "model.go.template")
+ tools2.HasError(err, "", -1)
+ t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template")
+ tools2.HasError(err, "", -1)
+ t3, err := template.ParseFiles(routerFile)
+ tools2.HasError(err, "", -1)
+ t4, err := template.ParseFiles(basePath + "js.go.template")
+ tools2.HasError(err, "", -1)
+ t5, err := template.ParseFiles(basePath + "vue.go.template")
+ tools2.HasError(err, "", -1)
+ t6, err := template.ParseFiles(basePath + "dto.go.template")
+ tools2.HasError(err, "", -1)
+ t7, err := template.ParseFiles(basePath + "no_actions/service.go.template")
+ tools2.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)
+
+ var b1 bytes.Buffer
+ err = t1.Execute(&b1, tab)
+ var b2 bytes.Buffer
+ err = t2.Execute(&b2, tab)
+ var b3 bytes.Buffer
+ err = t3.Execute(&b3, tab)
+ var b4 bytes.Buffer
+ err = t4.Execute(&b4, tab)
+ var b5 bytes.Buffer
+ err = t5.Execute(&b5, tab)
+ var b6 bytes.Buffer
+ 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")
+
+}
+
+func ActionsGenV3(tab tools.SysTables) {
+ basePath := "template/v3/"
+ routerFile := basePath + "actions/router_check_role.go.template"
+
+ if tab.IsAuth == 2 {
+ routerFile = basePath + "actions/router_no_check_role.go.template"
+ }
+
+ t1, err := template.ParseFiles(basePath + "model.go.template")
+ tools2.HasError(err, "", -1)
+ t3, err := template.ParseFiles(routerFile)
+ tools2.HasError(err, "", -1)
+ t4, err := template.ParseFiles(basePath + "js.go.template")
+ tools2.HasError(err, "", -1)
+ t5, err := template.ParseFiles(basePath + "vue.go.template")
+ tools2.HasError(err, "", -1)
+ t6, err := template.ParseFiles(basePath + "dto.go.template")
+ tools2.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)
+
+ var b1 bytes.Buffer
+ err = t1.Execute(&b1, tab)
+ var b3 bytes.Buffer
+ err = t3.Execute(&b3, tab)
+ var b4 bytes.Buffer
+ err = t4.Execute(&b4, tab)
+ var b5 bytes.Buffer
+ err = t5.Execute(&b5, tab)
+ 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")
+}
+
func NOActionsGen(tab tools.SysTables) {
routerfile := "template/routercheckrole.go.template"
diff --git a/app/admin/middleware/handler/nofound.go b/app/admin/middleware/handler/nofound.go
deleted file mode 100644
index a7092a3..0000000
--- a/app/admin/middleware/handler/nofound.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package handler
-
-import (
- "log"
- "net/http"
-
- "github.com/gin-gonic/gin"
-
- jwt "go-admin/pkg/jwtauth"
-)
-
-func NoFound(c *gin.Context) {
- claims := jwt.ExtractClaims(c)
- log.Printf("NoRoute claims: %#v\n", claims)
- c.JSON(http.StatusOK, gin.H{
- "code": "404",
- "message": "not found",
- })
-}
diff --git a/app/admin/middleware/handler/sd/check.go b/app/admin/middleware/handler/sd/check.go
deleted file mode 100644
index d082c5b..0000000
--- a/app/admin/middleware/handler/sd/check.go
+++ /dev/null
@@ -1,166 +0,0 @@
-package sd
-
-import (
- "fmt"
- "net/http"
- "runtime"
- "time"
-
- "github.com/gin-gonic/gin"
- "github.com/shirou/gopsutil/cpu"
- "github.com/shirou/gopsutil/disk"
- "github.com/shirou/gopsutil/load"
- "github.com/shirou/gopsutil/mem"
-
- "go-admin/tools/app"
-)
-
-const (
- B = 1
- KB = 1024 * B
- MB = 1024 * KB
- GB = 1024 * MB
-)
-
-// 健康状况
-// @Summary 健康状况 HealthCheck shows OK as the ping-pong result.
-// @Description 健康状况
-// @Accept text/html
-// @Produce text/html
-// @Success 200 {string} string "OK"
-// @Router /sd/health [get]
-// @BasePath
-func HealthCheck(c *gin.Context) {
- app.OK(c, "", "OK")
-}
-
-// @Summary 服务器硬盘使用量
-// @Description 服务器硬盘使用量 DiskCheck checks the disk usage.
-// @Accept text/html
-// @Produce text/html
-// @Success 200 {string} string "OK - Free space: 16321MB (15GB) / 51200MB (50GB) | Used: 31%"
-// @Failure 500 {string} string "CRITICAL"
-// @Failure 429 {string} string "WARNING"
-// @Router /sd/disk [get]
-// @BasePath
-func DiskCheck(c *gin.Context) {
- u, _ := disk.Usage("/")
-
- usedMB := int(u.Used) / MB
- usedGB := int(u.Used) / GB
- totalMB := int(u.Total) / MB
- totalGB := int(u.Total) / GB
- usedPercent := int(u.UsedPercent)
-
- status := http.StatusOK
- text := "OK"
-
- if usedPercent >= 95 {
- status = http.StatusOK
- text = "CRITICAL"
- } else if usedPercent >= 90 {
- status = http.StatusTooManyRequests
- text = "WARNING"
- }
-
- message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
- c.String(status, "\n"+message)
-}
-
-// @Summary OS
-// @Description Os
-// @Accept text/html
-// @Produce text/html
-// @Success 200 {string} string ""
-// @Router /sd/os [get]
-// @BasePath
-func OSCheck(c *gin.Context) {
- status := http.StatusOK
- app.Custum(c, gin.H{
- "code": 200,
- "status": status,
- "goOs": runtime.GOOS,
- "compiler": runtime.Compiler,
- "numCpu": runtime.NumCPU(),
- "version": runtime.Version(),
- "numGoroutine": runtime.NumGoroutine(),
- })
-}
-
-// @Summary CPU 使用量
-// @Description CPU 使用量 DiskCheck checks the disk usage.
-// @Accept text/html
-// @Produce text/html
-// @Success 200 {string} string ""
-// @Router /sd/cpu [get]
-// @BasePath
-func CPUCheck(c *gin.Context) {
- cores, _ := cpu.Counts(false)
-
- cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true)
- if err == nil {
- for i, c := range cpus {
- fmt.Printf("cpu%d : %f%%\n", i, c)
- }
- }
-
- a, _ := load.Avg()
- l1 := a.Load1
- l5 := a.Load5
- l15 := a.Load15
-
- status := http.StatusOK
- text := "OK"
-
- if l5 >= float64(cores-1) {
- status = http.StatusInternalServerError
- text = "CRITICAL"
- } else if l5 >= float64(cores-2) {
- status = http.StatusTooManyRequests
- text = "WARNING"
- }
- app.Custum(c, gin.H{
- "code": 200,
- "msg": text,
- "status": status,
- "cores": cores,
- "load1": l1,
- "load5": l5,
- "load15": l15,
- })
-}
-
-// @Summary 内存使用量
-// @Description 内存使用量 RAMCheck checks the disk usage.
-// @Accept text/html
-// @Produce text/html
-// @Success 200 {string} string ""
-// @Router /sd/ram [get]
-// @BasePath
-func RAMCheck(c *gin.Context) {
- u, _ := mem.VirtualMemory()
-
- usedMB := int(u.Used) / MB
- totalMB := int(u.Total) / MB
- usedPercent := int(u.UsedPercent)
-
- status := http.StatusOK
- text := "OK"
-
- if usedPercent >= 95 {
- status = http.StatusInternalServerError
- text = "CRITICAL"
- } else if usedPercent >= 90 {
- status = http.StatusTooManyRequests
- text = "WARNING"
- }
-
- app.Custum(c, gin.H{
- "code": 200,
- "msg": text,
- "status": status,
- "used": usedMB,
- "total": totalMB,
- "usedPercent": usedPercent,
- })
-}
diff --git a/app/admin/middleware/init.go b/app/admin/middleware/init.go
index 950a2ab..f2a9575 100644
--- a/app/admin/middleware/init.go
+++ b/app/admin/middleware/init.go
@@ -15,6 +15,4 @@ func InitMiddleware(r *gin.Engine) {
r.Use(Options)
// Secure is a middleware function that appends security
r.Use(Secure)
- // Set X-Request-Id header
- r.Use(RequestId())
}
diff --git a/app/admin/middleware/requestid.go b/app/admin/middleware/requestid.go
deleted file mode 100644
index 7ab5f7a..0000000
--- a/app/admin/middleware/requestid.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package middleware
-
-import (
- "github.com/gin-gonic/gin"
- "github.com/satori/go.uuid"
-)
-
-func RequestId() gin.HandlerFunc {
- return func(c *gin.Context) {
- // Check for incoming header, use it if exists
- requestId := c.Request.Header.Get("X-Request-Id")
-
- // Create request id with UUID4
- if requestId == "" {
- u4 := uuid.NewV4()
- requestId = u4.String()
- }
-
- // Expose it for use in the application
- c.Set("X-Request-Id", requestId)
-
- // Set X-Request-Id header
- c.Writer.Header().Set("X-Request-Id", requestId)
- c.Next()
- }
-}
diff --git a/app/admin/models/scol.go b/app/admin/models/scol.go
new file mode 100644
index 0000000..8e9a1bf
--- /dev/null
+++ b/app/admin/models/scol.go
@@ -0,0 +1,27 @@
+package models
+
+import (
+ "gorm.io/gorm"
+
+ "go-admin/common/models"
+)
+
+type Scol struct {
+ gorm.Model
+ models.ControlBy
+
+ Name string `json:"name" gorm:"type:varchar(255);comment:名称"` //
+}
+
+func (Scol) TableName() string {
+ return "scol"
+}
+
+func (e *Scol) Generate() models.ActiveRecord {
+ o := *e
+ return &o
+}
+
+func (e *Scol) GetId() interface{} {
+ return e.ID
+}
diff --git a/app/admin/models/student.go b/app/admin/models/student.go
new file mode 100644
index 0000000..25c4994
--- /dev/null
+++ b/app/admin/models/student.go
@@ -0,0 +1,26 @@
+package models
+
+import (
+ "gorm.io/gorm"
+ "go-admin/common/models"
+)
+
+type Student struct {
+ gorm.Model
+ models.ControlBy
+
+ Name string `json:"name" gorm:"type:varchar(255);comment:姓名"` //
+}
+
+func (Student) TableName() string {
+ return "student"
+}
+
+func (e *Student) Generate() models.ActiveRecord {
+ o := *e
+ return &o
+}
+
+func (e *Student) GetId() interface{} {
+ return e.ID
+}
diff --git a/app/admin/models/sysjob.go b/app/admin/models/sysjob.go
index 703d4c2..b32f86e 100644
--- a/app/admin/models/sysjob.go
+++ b/app/admin/models/sysjob.go
@@ -9,7 +9,7 @@ import (
)
type SysJob struct {
- JobId int `json:"jobId" gorm:"primary_key;AUTO_INCREMENT"` // 编码
+ JobId uint `json:"jobId" gorm:"primary_key;AUTO_INCREMENT"` // 编码
JobName string `json:"jobName" gorm:"size:255;"` // 名称
JobGroup string `json:"jobGroup" gorm:"size:255;"` // 任务分组
JobType int `json:"jobType" gorm:"size:1;"` // 任务类型
diff --git a/app/admin/router/scol.go b/app/admin/router/scol.go
new file mode 100644
index 0000000..ec5d45a
--- /dev/null
+++ b/app/admin/router/scol.go
@@ -0,0 +1,25 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/apis/scol"
+ "go-admin/app/admin/middleware"
+ jwt "go-admin/pkg/jwtauth"
+)
+
+func init() {
+ routerCheckRole = append(routerCheckRole, registerScolRouter)
+}
+
+// 需认证的路由代码
+func registerScolRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
+ api := &scol.Scol{}
+ r := v1.Group("/scol").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
+ {
+ r.GET("", api.GetScolList)
+ r.GET("/:id", api.GetScol)
+ r.POST("", api.InsertScol)
+ r.PUT("/:id", api.UpdateScol)
+ r.DELETE("", api.DeleteScol)
+ }
+}
diff --git a/app/admin/router/student.go b/app/admin/router/student.go
new file mode 100644
index 0000000..5fdc1e4
--- /dev/null
+++ b/app/admin/router/student.go
@@ -0,0 +1,25 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/apis/student"
+ "go-admin/app/admin/middleware"
+ jwt "go-admin/pkg/jwtauth"
+)
+
+func init() {
+ routerCheckRole = append(routerCheckRole, registerStudentRouter)
+}
+
+// 需认证的路由代码
+func registerStudentRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
+ stu := &student.Student{}
+ r := v1.Group("/student").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
+ {
+ r.GET("", stu.GetStudentList)
+ r.GET("/:id", stu.GetStudent)
+ r.POST("", stu.InsertStudent)
+ r.PUT("/:id", stu.UpdateStudent)
+ r.DELETE("", stu.DeleteStudent)
+ }
+}
diff --git a/app/admin/router/sysrouter.go b/app/admin/router/sysrouter.go
index a836a4f..04c48aa 100644
--- a/app/admin/router/sysrouter.go
+++ b/app/admin/router/sysrouter.go
@@ -25,15 +25,12 @@ func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Rou
sysBaseRouter(g)
// 静态文件
sysStaticFileRouter(g)
-
// swagger;注意:生产环境可以注释掉
sysSwaggerRouter(g)
-
// 无需认证
sysNoCheckRoleRouter(g)
// 需要认证
sysCheckRoleRouterInit(g, authMiddleware)
-
return g
}
@@ -44,13 +41,11 @@ func sysBaseRouter(r *gin.RouterGroup) {
go ws.WebsocketManager.SendAllService()
r.GET("/", system.HelloWorld)
-
r.GET("/info", handler.Ping)
}
func sysStaticFileRouter(r *gin.RouterGroup) {
mime.AddExtensionType(".js", "application/javascript")
-
r.Static("/static", "./static")
r.Static("/form-generator", "./static/form-generator")
}
@@ -65,7 +60,7 @@ func sysNoCheckRoleRouter(r *gin.RouterGroup) {
v1.GET("/monitor/server", monitor.ServerInfo)
v1.GET("/getCaptcha", system.GenerateCaptchaHandler)
v1.GET("/gen/preview/:tableId", Preview)
- v1.GET("/gen/toproject/:tableId", GenCodeV2)
+ v1.GET("/gen/toproject/:tableId", GenCodeV3)
v1.GET("/gen/todb/:tableId", GenMenuAndApi)
v1.GET("/gen/tabletree", GetSysTablesTree)
v1.GET("/menuTreeselect", system.GetMenuTreeelect)
diff --git a/app/admin/service/dto/scol.go b/app/admin/service/dto/scol.go
new file mode 100644
index 0000000..0b68374
--- /dev/null
+++ b/app/admin/service/dto/scol.go
@@ -0,0 +1,89 @@
+package dto
+
+import (
+ "github.com/gin-gonic/gin"
+ "gorm.io/gorm"
+
+ "go-admin/app/admin/models"
+ "go-admin/common/dto"
+ "go-admin/common/log"
+ common "go-admin/common/models"
+ "go-admin/tools"
+)
+
+type ScolSearch struct {
+ dto.Pagination `search:"-"`
+ Name string `form:"name" search:"type:contains;column:name;table:scol" comment:"名称"`
+
+
+}
+
+func (m *ScolSearch) GetNeedSearch() interface{} {
+ return *m
+}
+
+func (m *ScolSearch) Bind(ctx *gin.Context) error {
+ msgID := tools.GenerateMsgIDFromContext(ctx)
+ err := ctx.ShouldBind(m)
+ if err != nil {
+ log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
+ }
+ return err
+}
+
+func (m *ScolSearch) Generate() dto.Index {
+ o := *m
+ return &o
+}
+
+type ScolControl struct {
+
+ ID uint `uri:"ID" comment:""` //
+
+ Name string `json:"name" comment:"名称"`
+
+}
+
+func (s *ScolControl) Bind(ctx *gin.Context) error {
+ msgID := tools.GenerateMsgIDFromContext(ctx)
+ err := ctx.ShouldBindUri(s)
+ if err != nil {
+ log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
+ return err
+ }
+ err = ctx.ShouldBind(s)
+ if err != nil {
+ log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
+ }
+ return err
+}
+
+func (s *ScolControl) Generate() dto.Control {
+ cp := *s
+ return &cp
+}
+
+func (s *ScolControl) GenerateM() (common.ActiveRecord, error) {
+ return &models.Scol{
+
+ Model: gorm.Model{ID: s.ID},
+ Name: s.Name,
+ }, nil
+}
+
+func (s *ScolControl) GetId() interface{} {
+ return s.ID
+}
+
+type ScolById struct {
+ dto.ObjectById
+}
+
+func (s *ScolById) Generate() dto.Control {
+ cp := *s
+ return &cp
+}
+
+func (s *ScolById) GenerateM() (common.ActiveRecord, error) {
+ return &models.Scol{}, nil
+}
diff --git a/app/admin/service/dto/student.go b/app/admin/service/dto/student.go
new file mode 100644
index 0000000..1a578d5
--- /dev/null
+++ b/app/admin/service/dto/student.go
@@ -0,0 +1,87 @@
+package dto
+
+import (
+ "github.com/gin-gonic/gin"
+ "gorm.io/gorm"
+
+ "go-admin/app/admin/models"
+ "go-admin/common/dto"
+ "go-admin/common/log"
+ common "go-admin/common/models"
+)
+
+type StudentSearch struct {
+ dto.Pagination `search:"-"`
+ Name string `form:"name" search:"type:exact;column:name;table:student" comment:"姓名"`
+}
+
+func (m *StudentSearch) GetNeedSearch() interface{} {
+ return *m
+}
+
+func (m *StudentSearch) Bind(ctx *gin.Context) error {
+ err := ctx.Bind(m)
+ if err != nil {
+ log.Errorf("MsgID[%s] Bind error: %#v", err)
+ }
+ return err
+}
+
+func (m *StudentSearch) Generate() dto.Index {
+ o := *m
+ return &o
+}
+
+type StudentControl struct {
+ ID uint `uri:"ID" comment:""` //
+ Name string `json:"name" comment:"姓名"`
+}
+
+func (s *StudentControl) Bind(ctx *gin.Context) error {
+ err := ctx.BindUri(s)
+ if err != nil {
+ log.Errorf("MsgID[%s] Bind error: %#v", err)
+ return err
+ }
+ err = ctx.Bind(s)
+ if err != nil {
+ log.Errorf("MsgID[%s] Bind error: %#v", err)
+ }
+ return err
+}
+
+func (s *StudentControl) Generate() dto.Control {
+ cp := *s
+ return &cp
+}
+
+func (s *StudentControl) GenerateM() (common.ActiveRecord, error) {
+ return &models.Student{
+
+ Model: gorm.Model{ID: s.ID},
+ Name: s.Name,
+ }, nil
+}
+
+func (s *StudentControl) GetId() interface{} {
+ return s.ID
+}
+
+type StudentById struct {
+ dto.ObjectById
+}
+
+func (s *StudentById) Generate() dto.Control {
+ cp := *s
+ return &cp
+}
+
+func (s *StudentById) GenerateM() (common.ActiveRecord, error) {
+ return &models.Student{}, nil
+}
+
+type StudentItem struct {
+ gorm.Model
+ common.ControlBy
+ Name string `json:"name" gorm:"type:varchar(255);comment:姓名"` //
+}
diff --git a/app/admin/service/dto/sysjob.go b/app/admin/service/dto/sysjob.go
index 32d29ba..7ae6fd9 100644
--- a/app/admin/service/dto/sysjob.go
+++ b/app/admin/service/dto/sysjob.go
@@ -37,7 +37,7 @@ func (m *SysJobSearch) Generate() dto.Index {
}
type SysJobControl struct {
- JobId int `json:"jobId"`
+ JobId uint `json:"jobId"`
JobName string `json:"jobName" validate:"required"` // 名称
JobGroup string `json:"jobGroup"` // 任务分组
JobType int `json:"jobType"` // 任务类型
@@ -93,7 +93,7 @@ func (s *SysJobById) GenerateM() (common.ActiveRecord, error) {
}
type SysJobItem struct {
- JobId int `json:"jobId"`
+ JobId uint `json:"jobId"`
JobName string `json:"jobName" validate:"required"` // 名称
JobGroup string `json:"jobGroup"` // 任务分组
JobType int `json:"jobType"` // 任务类型
diff --git a/app/admin/service/scol.go b/app/admin/service/scol.go
new file mode 100644
index 0000000..32e5926
--- /dev/null
+++ b/app/admin/service/scol.go
@@ -0,0 +1,119 @@
+package service
+
+import (
+ "errors"
+ "go-admin/app/admin/models"
+ "go-admin/common/actions"
+ cDto "go-admin/common/dto"
+ "go-admin/common/log"
+ common "go-admin/common/models"
+ "go-admin/common/service"
+ "gorm.io/gorm"
+)
+
+type Scol struct {
+ service.Service
+}
+
+// GetScolPage 获取Scol列表
+func (e *Scol) GetScolPage(c cDto.Index, p *actions.DataPermission, list *[]models.Scol, count *int64) error {
+ var err error
+ var data models.Scol
+ msgID := e.MsgID
+
+ err = e.Orm.Table(data.TableName()).
+ Scopes(
+ cDto.MakeCondition(c.GetNeedSearch()),
+ cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
+ actions.Permission(data.TableName(), p),
+ ).
+ Find(list).Limit(-1).Offset(-1).
+ Count(count).Error
+ if err != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// GetScol 获取Scol对象
+func (e *Scol) GetScol(c cDto.Control, p *actions.DataPermission, m *common.ActiveRecord) error {
+ var err error
+ var data models.Scol
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(c.GetId()).First(m)
+ err = db.Error
+
+ if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
+ err = errors.New("查看对象不存在或无权查看")
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ if db.Error != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// InsertScol 创建Scol对象
+func (e *Scol) InsertScol(model common.ActiveRecord) error {
+ var err error
+ var data models.Scol
+ msgID := e.MsgID
+
+ err = e.Orm.Table(data.TableName()).
+ Create(model).Error
+ if err != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// UpdateScol 修改Scol对象
+func (e *Scol) UpdateScol(c common.ActiveRecord, p *actions.DataPermission) error {
+ var err error
+ var data models.Scol
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(c.GetId()).Updates(c)
+ if db.Error != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ if db.RowsAffected == 0 {
+ return errors.New("无权更新该数据")
+
+ }
+ return nil
+}
+
+// RemoveScol 删除Scol
+func (e *Scol) RemoveScol(d cDto.Control, c common.ActiveRecord, p *actions.DataPermission) error {
+ var err error
+ var data models.Scol
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(d.GetId()).Delete(c)
+ if db.Error != nil {
+ err = db.Error
+ log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
+ return err
+ }
+ if db.RowsAffected == 0 {
+ err = errors.New("无权删除该数据")
+ return err
+ }
+ return nil
+}
diff --git a/app/admin/service/student.go b/app/admin/service/student.go
new file mode 100644
index 0000000..aa15a3a
--- /dev/null
+++ b/app/admin/service/student.go
@@ -0,0 +1,121 @@
+package service
+
+import (
+ "errors"
+ "go-admin/app/admin/models"
+ "go-admin/app/admin/service/dto"
+ "go-admin/common/actions"
+ cDto "go-admin/common/dto"
+ "go-admin/common/log"
+ common "go-admin/common/models"
+ "go-admin/common/service"
+ "gorm.io/gorm"
+)
+
+type Student struct {
+ service.Service
+}
+
+// GetStudentPage 获取student列表
+func (e *Student) GetStudentPage(c cDto.Index, p *actions.DataPermission, list *[]models.Student, count *int64) error {
+ var err error
+ var data models.Student
+ msgID := e.MsgID
+
+ err = e.Orm.Table(data.TableName()).
+ Scopes(
+ cDto.MakeCondition(c.GetNeedSearch()),
+ cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
+ actions.Permission(data.TableName(), p),
+ ).
+ Find(list).Limit(-1).Offset(-1).
+ Count(count).Error
+ if err != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// GetStudent 获取student对象
+func (e *Student) GetStudent(c *dto.StudentSearch, p *actions.DataPermission, model *common.ActiveRecord) error {
+ var err error
+ var data models.Student
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ cDto.MakeCondition(c.GetNeedSearch()),
+ actions.Permission(data.TableName(), p),
+ ).
+ First(model)
+ err = db.Error
+ if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
+ err = errors.New("查看对象不存在或无权查看")
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ if db.Error != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// InsertStudent 创建student对象
+func (e *Student) InsertStudent(model common.ActiveRecord) error {
+ var err error
+ var data models.Student
+ msgID := e.MsgID
+
+ err = e.Orm.Table(data.TableName()).
+ Create(model).Error
+ if err != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// UpdateStudent 修改student对象
+func (e *Student) UpdateStudent(c common.ActiveRecord, p *actions.DataPermission) error {
+ var err error
+ var data models.Student
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(c.GetId()).Updates(c)
+ if db.Error != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ if db.RowsAffected == 0 {
+ return errors.New("无权更新该数据")
+
+ }
+ return nil
+}
+
+// RemoveStudent 删除student
+func (e *Student) RemoveStudent(c common.ActiveRecord, p *actions.DataPermission) error {
+ var err error
+ var data models.Student
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(c.GetId()).Delete(c)
+ if db.Error != nil {
+ err = db.Error
+ log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
+ return err
+ }
+ if db.RowsAffected == 0 {
+ err = errors.New("无权删除该数据")
+ return err
+ }
+ return nil
+}
diff --git a/app/jobs/jobbase.go b/app/jobs/jobbase.go
index 08846bd..2555dc8 100644
--- a/app/jobs/jobbase.go
+++ b/app/jobs/jobbase.go
@@ -22,7 +22,7 @@ var lock sync.Mutex
type JobCore struct {
InvokeTarget string
Name string
- JobId int
+ JobId uint
EntryId int
CronExpression string
Args string
diff --git a/common/actions/delete.go b/common/actions/delete.go
index 27d0c0a..f8c3a5f 100644
--- a/common/actions/delete.go
+++ b/common/actions/delete.go
@@ -40,7 +40,7 @@ func DeleteAction(control dto.Control) gin.HandlerFunc {
object.SetUpdateBy(tools.GetUserIdUint(c))
//数据权限检查
- p := getPermissionFromContext(c)
+ p := GetPermissionFromContext(c)
db = db.WithContext(c).Scopes(
Permission(object.TableName(), p),
diff --git a/common/actions/index.go b/common/actions/index.go
index 208e8a7..3f8f7fa 100644
--- a/common/actions/index.go
+++ b/common/actions/index.go
@@ -37,7 +37,7 @@ func IndexAction(m models.ActiveRecord, d dto.Index, f func() interface{}) gin.H
}
//数据权限检查
- p := getPermissionFromContext(c)
+ p := GetPermissionFromContext(c)
err = db.WithContext(c).Model(object).
Scopes(
diff --git a/common/actions/permission.go b/common/actions/permission.go
index 8a9365f..92df643 100644
--- a/common/actions/permission.go
+++ b/common/actions/permission.go
@@ -13,7 +13,7 @@ import (
"go-admin/tools/config"
)
-type dataPermission struct {
+type DataPermission struct {
DataScope string
UserId int
DeptId int
@@ -29,7 +29,7 @@ func PermissionAction() gin.HandlerFunc {
}
msgID := tools.GenerateMsgIDFromContext(c)
- var p = new(dataPermission)
+ var p = new(DataPermission)
if userId := tools.GetUserIdStr(c); userId != "" {
p, err = newDataPermission(db, userId)
if err != nil {
@@ -44,9 +44,9 @@ func PermissionAction() gin.HandlerFunc {
}
}
-func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error) {
+func newDataPermission(tx *gorm.DB, userId interface{}) (*DataPermission, error) {
var err error
- p := &dataPermission{}
+ p := &DataPermission{}
err = tx.Table("sys_user").
Select("sys_user.user_id", "sys_role.role_id", "sys_user.dept_id", "sys_role.data_scope").
@@ -60,7 +60,7 @@ func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error)
return p, nil
}
-func Permission(tableName string, p *dataPermission) func(db *gorm.DB) *gorm.DB {
+func Permission(tableName string, p *DataPermission) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if !config.ApplicationConfig.EnableDP {
return db
@@ -80,13 +80,18 @@ func Permission(tableName string, p *dataPermission) func(db *gorm.DB) *gorm.DB
}
}
-func getPermissionFromContext(c *gin.Context) *dataPermission {
- p := new(dataPermission)
+func getPermissionFromContext(c *gin.Context) *DataPermission {
+ p := new(DataPermission)
if pm, ok := c.Get(PermissionKey); ok {
switch pm.(type) {
- case *dataPermission:
- p = pm.(*dataPermission)
+ case *DataPermission:
+ p = pm.(*DataPermission)
}
}
return p
}
+
+// PermissionForNoAction 提供非action写法数据范围约束
+func GetPermissionFromContext(c *gin.Context) *DataPermission {
+ return getPermissionFromContext(c)
+}
\ No newline at end of file
diff --git a/common/actions/update.go b/common/actions/update.go
index 7c89e8b..ac788c8 100644
--- a/common/actions/update.go
+++ b/common/actions/update.go
@@ -38,7 +38,7 @@ func UpdateAction(control dto.Control) gin.HandlerFunc {
object.SetUpdateBy(tools.GetUserIdUint(c))
//数据权限检查
- p := getPermissionFromContext(c)
+ p := GetPermissionFromContext(c)
db = db.WithContext(c).Scopes(
Permission(object.TableName(), p),
diff --git a/common/actions/view.go b/common/actions/view.go
index e975ae7..015d54b 100644
--- a/common/actions/view.go
+++ b/common/actions/view.go
@@ -46,7 +46,7 @@ func ViewAction(control dto.Control, f func() interface{}) gin.HandlerFunc {
}
//数据权限检查
- p := getPermissionFromContext(c)
+ p := GetPermissionFromContext(c)
err = db.Model(object).WithContext(c).Scopes(
Permission(object.TableName(), p),
diff --git a/common/apis/api.go b/common/apis/api.go
index 11d3577..db4868d 100644
--- a/common/apis/api.go
+++ b/common/apis/api.go
@@ -3,13 +3,55 @@ package apis
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
+ "net/http"
+ "go-admin/common/models"
"go-admin/tools"
)
type Api struct {
}
+// GetOrm 获取Orm DB
func (e *Api) GetOrm(c *gin.Context) (*gorm.DB, error) {
return tools.GetOrm(c)
}
+
+// Error 通常错误数据处理
+func (e *Api) Error(c *gin.Context, code int, err error, msg string) {
+ var res models.Response
+ if err != nil {
+ res.Msg = err.Error()
+ }
+ if msg != "" {
+ res.Msg = msg
+ }
+ res.RequestId = tools.GenerateMsgIDFromContext(c)
+ c.JSON(http.StatusOK, res.ReturnError(code))
+}
+
+// OK 通常成功数据处理
+func (e *Api) OK(c *gin.Context, data interface{}, msg string) {
+ var res models.Response
+ res.Data = data
+ if msg != "" {
+ res.Msg = msg
+ }
+ res.RequestId = tools.GenerateMsgIDFromContext(c)
+ c.JSON(http.StatusOK, res.ReturnOK())
+}
+
+// PageOK 分页数据处理
+func (e *Api) PageOK(c *gin.Context, result interface{}, count int, pageIndex int, pageSize int, msg string) {
+ var res models.Page
+ res.List = result
+ res.Count = count
+ res.PageIndex = pageIndex
+ res.PageSize = pageSize
+ e.OK(c, res, msg)
+}
+
+// Custom 兼容函数
+func (e *Api) Custom(c *gin.Context, data gin.H) {
+ c.JSON(http.StatusOK, data)
+}
diff --git a/common/dto/generate.go b/common/dto/generate.go
index d3b9919..f8f7d6c 100644
--- a/common/dto/generate.go
+++ b/common/dto/generate.go
@@ -27,13 +27,6 @@ func (s *ObjectById) Bind(ctx *gin.Context) error {
func (s *ObjectById) GetId() interface{} {
if len(s.Ids) > 0 {
return s.Ids
- //ids := make([]int64, 0)
- //var i int64
- //for _, id := range s.Ids {
- // i, _ = id.Int64()
- // ids = append(ids, i)
- //}
- //return ids
}
return s.Id
}
diff --git a/common/dto/search.go b/common/dto/search.go
index ea34ccb..e73dacc 100644
--- a/common/dto/search.go
+++ b/common/dto/search.go
@@ -8,12 +8,12 @@ import (
)
type GeneralDelDto struct {
- Id int `uri:"id" json:"id" validate:"required"`
- Ids []int `json:"ids"`
+ Id uint `uri:"id" json:"id" validate:"required"`
+ Ids []uint `json:"ids"`
}
-func (g GeneralDelDto) GetIds() []int {
- ids := make([]int, 0)
+func (g GeneralDelDto) GetIds() []uint {
+ ids := make([]uint, 0)
if g.Id != 0 {
ids = append(ids, g.Id)
}
@@ -36,7 +36,7 @@ func (g GeneralDelDto) GetIds() []int {
}
type GeneralGetDto struct {
- Id int `uri:"id" json:"id" validate:"required"`
+ Id uint `uri:"id" json:"id" validate:"required"`
}
func MakeCondition(q interface{}) func(db *gorm.DB) *gorm.DB {
diff --git a/common/models/response.go b/common/models/response.go
new file mode 100644
index 0000000..2bf6f72
--- /dev/null
+++ b/common/models/response.go
@@ -0,0 +1,30 @@
+package models
+
+type Response struct {
+ // 代码
+ Code int `json:"code" example:"200"`
+ // 数据集
+ Data interface{} `json:"data"`
+ // 消息
+ Msg string `json:"msg"`
+ RequestId string `json:"requestId"`
+}
+
+type Page struct {
+ List interface{} `json:"list"`
+ Count int `json:"count"`
+ PageIndex int `json:"pageIndex"`
+ PageSize int `json:"pageSize"`
+}
+
+// ReturnOK 正常返回
+func (res *Response) ReturnOK() *Response {
+ res.Code = 200
+ return res
+}
+
+// ReturnError 错误返回
+func (res *Response) ReturnError(code int) *Response {
+ res.Code = code
+ return res
+}
\ No newline at end of file
diff --git a/template/v3/actions/router_check_role.go.template b/template/v3/actions/router_check_role.go.template
new file mode 100644
index 0000000..bfad129
--- /dev/null
+++ b/template/v3/actions/router_check_role.go.template
@@ -0,0 +1,31 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+
+ "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"
+)
+
+func init() {
+ routerCheckRole = append(routerCheckRole, register{{.ClassName}}Router)
+}
+
+// 需认证的路由代码
+func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
+ r := v1.Group("/{{.ModuleName}}").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
+ {
+ model := &models.{{.ClassName}}{}
+ r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.{{.ClassName}}Search), func() interface{} {
+ list := make([]models.{{.ClassName}}, 0)
+ return &list
+ }))
+ r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.{{.ClassName}}ById), nil))
+ r.POST("", actions.CreateAction(new(dto.{{.ClassName}}Control)))
+ r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.{{.ClassName}}Control)))
+ r.DELETE("/:id", actions.PermissionAction(), actions.DeleteAction(new(dto.{{.ClassName}}ById)))
+ }
+}
diff --git a/template/v3/actions/router_no_check_role.go.template b/template/v3/actions/router_no_check_role.go.template
new file mode 100644
index 0000000..1a583d4
--- /dev/null
+++ b/template/v3/actions/router_no_check_role.go.template
@@ -0,0 +1,30 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+
+ "go-admin/app/admin/middleware"
+ "go-admin/app/admin/models"
+ "go-admin/app/admin/service/dto"
+ "go-admin/common/actions"
+)
+
+func init() {
+ routerNoCheckRole = append(routerNoCheckRole, register{{.ClassName}}Router)
+}
+
+// 无需认证的路由代码
+func register{{.ClassName}}Router(v1 *gin.RouterGroup) {
+ r := v1.Group("/{{.ModuleName}}")
+ {
+ model := &models.{{.ClassName}}{}
+ r.GET("", actions.IndexAction(model, new(dto.{{.ClassName}}Search), func() interface{} {
+ list := make([]models.{{.ClassName}}, 0)
+ return &list
+ }))
+ r.GET("/:id", actions.ViewAction(new(dto.{{.ClassName}}ById), nil))
+ r.POST("", actions.CreateAction(new(dto.{{.ClassName}}Control)))
+ r.PUT("/:id", actions.UpdateAction(new(dto.{{.ClassName}}Control)))
+ r.DELETE("/:id", actions.DeleteAction(new(dto.{{.ClassName}}ById)))
+ }
+}
diff --git a/template/v3/dto.go.template b/template/v3/dto.go.template
new file mode 100644
index 0000000..33b2c54
--- /dev/null
+++ b/template/v3/dto.go.template
@@ -0,0 +1,116 @@
+package dto
+
+import (
+ "github.com/gin-gonic/gin"
+ "gorm.io/gorm"
+
+ "go-admin/app/admin/models"
+ "go-admin/common/dto"
+ "go-admin/common/log"
+ common "go-admin/common/models"
+ "go-admin/tools"
+)
+
+type {{.ClassName}}Search struct {
+ dto.Pagination `search:"-"`
+ {{ $tablename := .TBName -}}
+ {{ range .Columns -}}
+ {{$z := .IsQuery}}
+ {{- if ($z) -}}
+ {{.GoField}} {{.GoType}} `form:"{{.JsonField}}" search:"type:{{if eq .QueryType "EQ"}}exact{{ else if eq .QueryType "NE"}}iexact{{ else if eq .QueryType "LIKE"}}contains{{ else if eq .QueryType "GT"}}gt{{ else if eq .QueryType "GTE"}}gte{{ else if eq .QueryType "LT"}}lt{{ else if eq .QueryType "LTE"}}lte{{- end }};column:{{.ColumnName}};table:{{$tablename}}" comment:"{{.ColumnComment}}"`
+
+ {{ end -}}
+ {{- end }}
+}
+
+func (m *{{.ClassName}}Search) GetNeedSearch() interface{} {
+ return *m
+}
+
+func (m *{{.ClassName}}Search) Bind(ctx *gin.Context) error {
+ msgID := tools.GenerateMsgIDFromContext(ctx)
+ err := ctx.ShouldBind(m)
+ if err != nil {
+ log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
+ }
+ return err
+}
+
+func (m *{{.ClassName}}Search) Generate() dto.Index {
+ o := *m
+ return &o
+}
+
+type {{.ClassName}}Control struct {
+ {{ range .Columns -}}
+ {{$x := .Pk}}
+ {{- if ($x) }}
+ {{.GoField}} uint `uri:"{{.JsonField}}" comment:"{{.ColumnComment}}"` // {{.ColumnComment}}
+ {{- else if eq .GoField "CreatedAt" -}}
+ {{- else if eq .GoField "UpdatedAt" -}}
+ {{- else if eq .GoField "DeletedAt" -}}
+ {{- else if eq .GoField "CreateBy" -}}
+ {{- else if eq .GoField "UpdateBy" -}}
+
+ {{- else }}
+
+ {{.GoField}} {{.GoType}} `json:"{{.JsonField}}" comment:"{{.ColumnComment}}"`
+ {{end -}}
+ {{- end }}
+}
+
+func (s *{{.ClassName}}Control) Bind(ctx *gin.Context) error {
+ msgID := tools.GenerateMsgIDFromContext(ctx)
+ err := ctx.ShouldBindUri(s)
+ if err != nil {
+ log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
+ return err
+ }
+ err = ctx.ShouldBind(s)
+ if err != nil {
+ log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
+ }
+ return err
+}
+
+func (s *{{.ClassName}}Control) Generate() dto.Control {
+ cp := *s
+ return &cp
+}
+
+func (s *{{.ClassName}}Control) GenerateM() (common.ActiveRecord, error) {
+ return &models.{{.ClassName}}{
+ {{ range .Columns -}}
+ {{$x := .Pk}}
+ {{- if ($x) }}
+ Model: gorm.Model{ID: s.ID},
+ {{- else if eq .GoField "CreatedAt" -}}
+ {{- else if eq .GoField "UpdatedAt" -}}
+ {{- else if eq .GoField "DeletedAt" -}}
+ {{- else if eq .GoField "CreateBy" -}}
+
+
+ {{- else if eq .GoField "UpdateBy" -}}
+ {{- else }}
+ {{.GoField}}: s.{{.GoField}},
+ {{- end }}
+ {{- end }}
+ }, nil
+}
+
+func (s *{{.ClassName}}Control) GetId() interface{} {
+ return s.{{.PkGoField}}
+}
+
+type {{.ClassName}}ById struct {
+ dto.ObjectById
+}
+
+func (s *{{.ClassName}}ById) Generate() dto.Control {
+ cp := *s
+ return &cp
+}
+
+func (s *{{.ClassName}}ById) GenerateM() (common.ActiveRecord, error) {
+ return &models.{{.ClassName}}{}, nil
+}
diff --git a/template/v3/js.go.template b/template/v3/js.go.template
new file mode 100644
index 0000000..db3d4a2
--- /dev/null
+++ b/template/v3/js.go.template
@@ -0,0 +1,47 @@
+import request from '@/utils/request'
+
+// 查询{{.ClassName}}列表
+export function list{{.ClassName}}(query) {
+ return request({
+ url: '/api/v1/{{.ModuleName}}',
+ method: 'get',
+ params: query
+ })
+}
+
+// 查询{{.ClassName}}详细
+export function get{{.ClassName}} ({{.PkJsonField}}) {
+ return request({
+ url: '/api/v1/{{.ModuleName}}/' + {{.PkJsonField}},
+ method: 'get'
+ })
+}
+
+
+// 新增{{.ClassName}}
+export function add{{.ClassName}}(data) {
+ return request({
+ url: '/api/v1/{{.ModuleName}}',
+ method: 'post',
+ data: data
+ })
+}
+
+// 修改{{.ClassName}}
+export function update{{.ClassName}}(data) {
+ return request({
+ url: '/api/v1/{{.ModuleName}}/'+data.{{.PkJsonField}},
+ method: 'put',
+ data: data
+ })
+}
+
+// 删除{{.ClassName}}
+export function del{{.ClassName}}(data) {
+ return request({
+ url: '/api/v1/{{.ModuleName}}',
+ method: 'delete',
+ data: data
+ })
+}
+
diff --git a/template/v3/model.go.template b/template/v3/model.go.template
new file mode 100644
index 0000000..80d5f8c
--- /dev/null
+++ b/template/v3/model.go.template
@@ -0,0 +1,37 @@
+package models
+
+import (
+ "gorm.io/gorm"
+
+ "go-admin/common/models"
+)
+
+type {{.ClassName}} struct {
+ gorm.Model
+ models.ControlBy
+ {{ range .Columns -}}
+ {{$x := .Pk}}
+ {{- if ($x) }}
+
+ {{- else if eq .GoField "CreatedAt" -}}
+ {{- else if eq .GoField "UpdatedAt" -}}
+ {{- else if eq .GoField "DeletedAt" -}}
+ {{- else if eq .GoField "CreateBy" -}}
+ {{- else if eq .GoField "UpdateBy" -}}
+ {{- else }}
+ {{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};comment:{{- if eq .ColumnComment "" -}}{{.GoField}}{{- else -}}{{.ColumnComment}}{{end -}}"` // {{end -}}
+ {{- end }}
+}
+
+func ({{.ClassName}}) TableName() string {
+ return "{{.TBName}}"
+}
+
+func (e *{{.ClassName}}) Generate() models.ActiveRecord {
+ o := *e
+ return &o
+}
+
+func (e *{{.ClassName}}) GetId() interface{} {
+ return e.{{.PkGoField}}
+}
diff --git a/template/v3/no_actions/apis.go.template b/template/v3/no_actions/apis.go.template
new file mode 100644
index 0000000..c8efda8
--- /dev/null
+++ b/template/v3/no_actions/apis.go.template
@@ -0,0 +1,211 @@
+package {{.ModuleName}}
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/service"
+ common "go-admin/common/models"
+ "net/http"
+
+ "go-admin/app/admin/models"
+ "go-admin/app/admin/service/dto"
+ "go-admin/common/actions"
+ "go-admin/common/apis"
+ "go-admin/common/log"
+ "go-admin/tools"
+)
+
+type {{.ClassName}} struct {
+ apis.Api
+}
+
+func (e *{{.ClassName}}) Get{{.ClassName}}List(c *gin.Context) {
+ msgID := tools.GenerateMsgIDFromContext(c)
+ d := new(dto.{{.ClassName}}Search)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ req := d.Generate()
+
+ //查询列表
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ list := make([]models.{{.ClassName}}, 0)
+ var count int64
+ serviceStudent := service.{{.ClassName}}{}
+ serviceStudent.MsgID = msgID
+ serviceStudent.Orm = db
+ err = serviceStudent.Get{{.ClassName}}Page(req, p, &list, &count)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
+ return
+ }
+
+ e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
+}
+
+func (e *{{.ClassName}}) Get{{.ClassName}}(c *gin.Context) {
+ control := new(dto.{{.ClassName}}ById)
+ d := new(dto.{{.ClassName}}Search)
+ db, err := tools.GetOrm(c)
+
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //查看详情
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ service{{.ClassName}} := service.{{.ClassName}}{}
+ service{{.ClassName}}.MsgID = msgID
+ service{{.ClassName}}.Orm = db
+ err = service{{.ClassName}}.Get{{.ClassName}}(d, p, &object)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
+ return
+ }
+
+ e.OK(c, object, "查看成功")
+}
+
+func (e *{{.ClassName}}) Insert{{.ClassName}}(c *gin.Context) {
+ control := new(dto.{{.ClassName}}Control)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //新增操作
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+ // 设置创建人
+ object.SetCreateBy(tools.GetUserIdUint(c))
+
+ service{{.ClassName}} := service.{{.ClassName}}{}
+ service{{.ClassName}}.Orm = db
+ service{{.ClassName}}.MsgID = msgID
+ err = service{{.ClassName}}.Insert{{.ClassName}}(object)
+ if err != nil {
+ log.Error(err)
+ e.Error(c, http.StatusInternalServerError, err, "创建失败")
+ return
+ }
+
+ e.OK(c, object.GetId(), "创建成功")
+}
+
+func (e *{{.ClassName}}) Update{{.ClassName}}(c *gin.Context) {
+ control := new(dto.{{.ClassName}}Control)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ req := control.Generate()
+ //更新操作
+ err = req.Bind(c)
+ if err != nil {
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+ object.SetUpdateBy(tools.GetUserIdUint(c))
+
+ //数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ service{{.ClassName}} := service.{{.ClassName}}{}
+ service{{.ClassName}}.Orm = db
+ service{{.ClassName}}.MsgID = msgID
+ err = service{{.ClassName}}.Update{{.ClassName}}(object, p)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+ e.OK(c, object.GetId(), "更新成功")
+}
+
+func (e *{{.ClassName}}) Delete{{.ClassName}}(c *gin.Context) {
+ control := new(dto.{{.ClassName}}ById)
+ db, err := tools.GetOrm(c)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+
+ msgID := tools.GenerateMsgIDFromContext(c)
+ //删除操作
+ req := control.Generate()
+ err = req.Bind(c)
+ if err != nil {
+ log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
+ e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
+ return
+ }
+ var object common.ActiveRecord
+ object, err = req.GenerateM()
+ if err != nil {
+ e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
+ return
+ }
+
+ // 设置编辑人
+ object.SetUpdateBy(tools.GetUserIdUint(c))
+
+ // 数据权限检查
+ p := actions.GetPermissionFromContext(c)
+
+ service{{.ClassName}} := service.{{.ClassName}}{}
+ service{{.ClassName}}.Orm = db
+ service{{.ClassName}}.MsgID = msgID
+ err = service{{.ClassName}}.Remove{{.ClassName}}(req, object, p)
+ if err != nil {
+ log.Error(err)
+ return
+ }
+ e.OK(c, object.GetId(), "删除成功")
+}
diff --git a/template/v3/no_actions/router_check_role.go.template b/template/v3/no_actions/router_check_role.go.template
new file mode 100644
index 0000000..b58bf47
--- /dev/null
+++ b/template/v3/no_actions/router_check_role.go.template
@@ -0,0 +1,25 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/apis/{{.ModuleName}}"
+ "go-admin/app/admin/middleware"
+ jwt "go-admin/pkg/jwtauth"
+)
+
+func init() {
+ routerCheckRole = append(routerCheckRole, register{{.ClassName}}Router)
+}
+
+// 需认证的路由代码
+func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
+ api := &{{.ModuleName}}.{{.ClassName}}{}
+ r := v1.Group("/{{.ModuleName}}").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
+ {
+ r.GET("", api.Get{{.ClassName}}List)
+ r.GET("/:id", api.Get{{.ClassName}})
+ r.POST("", api.Insert{{.ClassName}})
+ r.PUT("/:id", api.Update{{.ClassName}})
+ r.DELETE("/:id", api.Delete{{.ClassName}})
+ }
+}
diff --git a/template/v3/no_actions/router_no_check_role.go.template b/template/v3/no_actions/router_no_check_role.go.template
new file mode 100644
index 0000000..1494ab6
--- /dev/null
+++ b/template/v3/no_actions/router_no_check_role.go.template
@@ -0,0 +1,24 @@
+package router
+
+import (
+ "github.com/gin-gonic/gin"
+ "go-admin/app/admin/apis/{{.ModuleName}}"
+ jwt "go-admin/pkg/jwtauth"
+)
+
+func init() {
+ routerCheckRole = append(routerCheckRole, register{{.ClassName}}Router)
+}
+
+// 需认证的路由代码
+func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
+ api := &{{.ModuleName}}.{{.ClassName}}{}
+ r := v1.Group("/{{.ModuleName}}").Use(authMiddleware.MiddlewareFunc())
+ {
+ r.GET("", api.Get{{.ClassName}}List)
+ r.GET("/:id", api.Get{{.ClassName}})
+ r.POST("", api.Insert{{.ClassName}})
+ r.PUT("/:id", api.Update{{.ClassName}})
+ r.DELETE("/:id", api.Delete{{.ClassName}})
+ }
+}
diff --git a/template/v3/no_actions/service.go.template b/template/v3/no_actions/service.go.template
new file mode 100644
index 0000000..6a03411
--- /dev/null
+++ b/template/v3/no_actions/service.go.template
@@ -0,0 +1,121 @@
+package service
+
+import (
+ "errors"
+ "go-admin/app/admin/models"
+ "go-admin/app/admin/service/dto"
+ "go-admin/common/actions"
+ cDto "go-admin/common/dto"
+ "go-admin/common/log"
+ common "go-admin/common/models"
+ "go-admin/common/service"
+ "gorm.io/gorm"
+)
+
+type {{.ClassName}} struct {
+ service.Service
+}
+
+// Get{{.ClassName}}Page 获取{{.ClassName}}列表
+func (e *{{.ClassName}}) Get{{.ClassName}}Page(c cDto.Index, p *actions.DataPermission, list *[]models.{{.ClassName}}, count *int64) error {
+ var err error
+ var data models.{{.ClassName}}
+ msgID := e.MsgID
+
+ err = e.Orm.Table(data.TableName()).
+ Scopes(
+ cDto.MakeCondition(c.GetNeedSearch()),
+ cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
+ actions.Permission(data.TableName(), p),
+ ).
+ Find(list).Limit(-1).Offset(-1).
+ Count(count).Error
+ if err != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// Get{{.ClassName}} 获取{{.ClassName}}对象
+func (e *{{.ClassName}}) Get{{.ClassName}}(c *dto.{{.ClassName}}Search, p *actions.DataPermission, model *common.ActiveRecord) error {
+ var err error
+ var data models.{{.ClassName}}
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ cDto.MakeCondition(c.GetNeedSearch()),
+ actions.Permission(data.TableName(), p),
+ ).
+ First(model)
+ err = db.Error
+ if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
+ err = errors.New("查看对象不存在或无权查看")
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ if db.Error != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// Insert{{.ClassName}} 创建{{.ClassName}}对象
+func (e *{{.ClassName}}) Insert{{.ClassName}}(model common.ActiveRecord) error {
+ var err error
+ var data models.{{.ClassName}}
+ msgID := e.MsgID
+
+ err = e.Orm.Table(data.TableName()).
+ Create(model).Error
+ if err != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ return nil
+}
+
+// Update{{.ClassName}} 修改{{.ClassName}}对象
+func (e *{{.ClassName}}) Update{{.ClassName}}(c common.ActiveRecord, p *actions.DataPermission) error {
+ var err error
+ var data models.{{.ClassName}}
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(c.GetId()).Updates(c)
+ if db.Error != nil {
+ log.Errorf("msgID[%s] db error:%s", msgID, err)
+ return err
+ }
+ if db.RowsAffected == 0 {
+ return errors.New("无权更新该数据")
+
+ }
+ return nil
+}
+
+// Remove{{.ClassName}} 删除{{.ClassName}}
+func (e *{{.ClassName}}) Remove{{.ClassName}}(d cDto.Control, c common.ActiveRecord, p *actions.DataPermission) error {
+ var err error
+ var data models.{{.ClassName}}
+ msgID := e.MsgID
+
+ db := e.Orm.Table(data.TableName()).
+ Scopes(
+ actions.Permission(data.TableName(), p),
+ ).Where(d.GetId()).Delete(c)
+ if db.Error != nil {
+ err = db.Error
+ log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
+ return err
+ }
+ if db.RowsAffected == 0 {
+ err = errors.New("无权删除该数据")
+ return err
+ }
+ return nil
+}
\ No newline at end of file
diff --git a/template/v3/vue.go.template b/template/v3/vue.go.template
new file mode 100644
index 0000000..0aa3a2b
--- /dev/null
+++ b/template/v3/vue.go.template
@@ -0,0 +1,472 @@
+{{$tableComment:=.TableComment}}
+
+
+
+
+
+ {{range .Columns}}
+ {{- $x := .IsQuery -}}
+ {{- if ($x) -}}
+
+ {{- if ne .FkTableName "" -}}
+
+
+
+ {{- else -}}
+ {{if eq .DictType "" -}}
+
+ {{- else -}}
+
+
+
+ {{- end}}
+ {{- end}}
+
+ {{end}}
+ {{- end }}
+
+ 搜索
+ 重置
+
+
+
+
+
+ 新增
+
+
+
+ 修改
+
+
+
+ 删除
+
+
+
+
+
+
+ {{- range .Columns -}}
+ {{- $x := .IsList -}}
+ {{- if (eq $x "1") }}
+ {{- if ne .FkTableName "" -}}
+
+
+ {{ "{{" }} {{.JsonField}}Format(scope.row) {{"}}"}}
+
+
+
+ {{- else -}}
+ {{- if ne .DictType "" -}}
+
+
+ {{ "{{" }} {{.JsonField}}Format(scope.row) {{"}}"}}
+
+
+
+ {{- end -}}
+ {{- if eq .DictType "" -}}
+
+
+ {{- end -}}
+ {{- end -}}
+ {{- end }}
+ {{- end }}
+
+
+ 修改
+
+ 删除
+
+
+
+
+
+
+
+
+
+
+ {{ range .Columns }}
+ {{- $x := .IsInsert -}}
+ {{- if (eq $x "1") -}}
+ {{- if (.Pk) }}
+ {{- else if eq .GoField "CreatedAt" -}}
+ {{- else if eq .GoField "UpdatedAt" -}}
+ {{- else if eq .GoField "DeletedAt" -}}
+ {{- else if eq .GoField "UpdateBy" -}}
+ {{- else if eq .GoField "CreateBy" -}}
+ {{- else }}
+
+ {{ if eq "input" .HtmlType -}}
+
+ {{- else if eq "select" .HtmlType -}}
+ {{- if ne .FkTableName "" -}}
+
+
+
+ {{- else -}}
+
+
+
+ {{- end -}}
+ {{- else if eq "radio" .HtmlType -}}
+
+ {{"{{"}} dict.dictLabel {{"}}"}}
+
+ {{- else if eq "file" .HtmlType -}}
+
+ 选择文件
+ {{- else if eq "datetime" .HtmlType -}}
+
+
+ {{- else if eq "textarea" .HtmlType -}}
+
+
+ {{- end }}
+
+ {{- end }}
+ {{- end }}
+ {{- end }}
+
+
+
+
+
+
+
+
+
+
diff --git a/tools/file.go b/tools/file.go
index d7e73d2..94309ed 100644
--- a/tools/file.go
+++ b/tools/file.go
@@ -1,10 +1,10 @@
package tools
import (
- "archive/zip"
"bufio"
"bytes"
"context"
+ "fmt"
"io"
"io/ioutil"
"log"
@@ -14,17 +14,6 @@ import (
"time"
)
-func PathExists(path string) (bool, error) {
- _, err := os.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
func PathCreate(dir string) error {
return os.MkdirAll(dir, os.ModePerm)
}
@@ -38,88 +27,9 @@ func FileCreate(content bytes.Buffer, name string) {
if err != nil {
log.Println(err)
}
- //for i := 0; i < len(content); i++ {
- // //写入byte的slice数据
- // file.Write(content)
- // //写入字符串
- // //
- //}
file.Close()
}
-func PathRemove(name string) {
- err := os.RemoveAll(name)
- if err != nil {
- log.Println(err)
- }
-}
-
-func FileRemove(name string) {
- err := os.Remove(name)
- if err != nil {
- log.Println(err)
- }
-}
-
-func FileZip(dst, src string, notContPath string) (err error) {
- //创建准备写入的文件
- fw, err := os.Create(dst)
- defer fw.Close()
- if err != nil {
- return err
- }
-
- // 通过 fw 来创建 zip.Write
- zw := zip.NewWriter(fw)
- defer func() {
- // 检测一下是否成功关闭
- if err := zw.Close(); err != nil {
- log.Fatalln(err)
- }
- }()
- return filepath.Walk(src, func(path string, fi os.FileInfo, errBack error) (err error) {
- if errBack != nil {
- return errBack
- }
-
- fh, err := zip.FileInfoHeader(fi)
- if err != nil {
- return
- }
-
- fh.Name = strings.TrimPrefix(path, string(filepath.Separator))
-
- if fi.IsDir() {
- fh.Name += "/"
- }
- fh.Name = strings.Replace(fh.Name, notContPath, "", -1)
-
- w, err := zw.CreateHeader(fh)
- if err != nil {
- return
- }
-
- if !fh.Mode().IsRegular() {
- return nil
- }
-
- fr, err := os.Open(path)
- defer fr.Close()
- if err != nil {
- return
- }
-
- n, err := io.Copy(w, fr)
- if err != nil {
- return
- }
-
- log.Printf("成功压缩文件: %s, 共写入了 %d 个字符的数据\n", path, n)
-
- return nil
- })
-}
-
type ReplaceHelper struct {
Root string //路径
OldText string //需要替换的文本
@@ -165,28 +75,6 @@ func (h ReplaceHelper) walkCallback(path string, f os.FileInfo, err error) error
return err
}
-func FileMonitoring(filePth string, hookfn func([]byte)) {
- f, err := os.Open(filePth)
- if err != nil {
- log.Fatalln(err)
- }
- defer f.Close()
-
- rd := bufio.NewReader(f)
- f.Seek(0, 2)
- for {
- line, err := rd.ReadBytes('\n')
- // 如果是文件末尾不返回
- if err == io.EOF {
- time.Sleep(500 * time.Millisecond)
- continue
- } else if err != nil {
- log.Fatalln(err)
- }
- go hookfn(line)
- }
-}
-
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 {
@@ -221,3 +109,12 @@ func GetFileSize(filename string) int64 {
})
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/float64.go b/tools/float64.go
deleted file mode 100644
index 583ff9f..0000000
--- a/tools/float64.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package tools
-
-import (
- "math"
- "strconv"
-)
-
-func Float64ToString(e float64) string {
- return strconv.FormatFloat(e, 'E', -1, 64)
-}
-
-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/int.go b/tools/int.go
index c62cfa8..d519056 100644
--- a/tools/int.go
+++ b/tools/int.go
@@ -1,7 +1,19 @@
package tools
-import "strconv"
+import (
+ "math"
+ "strconv"
+)
func IntToString(e int) string {
return strconv.Itoa(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/int64.go b/tools/int64.go
deleted file mode 100644
index 843c167..0000000
--- a/tools/int64.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package tools
-
-import "strconv"
-
-func Int64ToString(e int64) string {
- return strconv.FormatInt(e, 10)
-}
diff --git a/tools/projectDir.go b/tools/projectDir.go
deleted file mode 100644
index 912ad6b..0000000
--- a/tools/projectDir.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package tools
-
-import (
- "fmt"
- "os"
- "strings"
-)
-
-//获取当前路径,比如: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/string.go b/tools/string.go
index 7eaa9b6..f0a71d4 100644
--- a/tools/string.go
+++ b/tools/string.go
@@ -2,26 +2,14 @@ package tools
import (
"encoding/json"
- "fmt"
- "io/ioutil"
"strconv"
"time"
-
- "github.com/gin-gonic/gin"
)
-func StringToInt64(e string) (int64, error) {
- return strconv.ParseInt(e, 10, 64)
-}
-
func StringToInt(e string) (int, error) {
return strconv.Atoi(e)
}
-func StringToBool(e string) (bool, error) {
- return strconv.ParseBool(e)
-}
-
func GetCurrentTimeStr() string {
return time.Now().Format("2006-01-02 15:04:05")
}
@@ -30,48 +18,10 @@ func GetCurrentTime() time.Time {
return time.Now()
}
-func FormatTimeStr(timeStr string) (string, error) {
- loc, _ := time.LoadLocation("Local")
- theTime, err := time.ParseInLocation("2006-01-02T15:04:05.000Z", timeStr, loc)
- return theTime.Format("2006/01/02 15:04:05"), err
-}
-
func StructToJsonStr(e interface{}) (string, error) {
if b, err := json.Marshal(e); err == nil {
return string(b), err
} else {
return "", err
}
-}
-
-func GetBodyString(c *gin.Context) (string, error) {
- body, err := ioutil.ReadAll(c.Request.Body)
- if err != nil {
- fmt.Printf("read body err, %v\n", err)
- return string(body), nil
- } else {
- return "", err
- }
-}
-
-func JsonStrToMap(e string) (map[string]interface{}, error) {
- var dict map[string]interface{}
- if err := json.Unmarshal([]byte(e), &dict); err == nil {
- return dict, err
- } else {
- return nil, err
- }
-}
-
-func StructToMap(data interface{}) (map[string]interface{}, error) {
- dataBytes, err := json.Marshal(data)
- if err != nil {
- return nil, err
- }
- mapData := make(map[string]interface{})
- err = json.Unmarshal(dataBytes, &mapData)
- if err != nil {
- return nil, err
- }
- return mapData, nil
-}
+}
\ No newline at end of file
diff --git a/tools/url.go b/tools/url.go
index 6562430..3f31f1c 100644
--- a/tools/url.go
+++ b/tools/url.go
@@ -15,12 +15,6 @@ type Ids struct {
Ids []int
}
-func GetDeleteIds(c *gin.Context) []int {
- var ids = new(Ids)
- c.Bind(ids)
- return ids.Ids
-}
-
func IdsStrToIdsIntGroupStr(keys string) []int {
IDS := make([]int, 0)
ids := strings.Split(keys, ",")
diff --git a/tools/utils.go b/tools/utils.go
index 392eefb..3313e30 100644
--- a/tools/utils.go
+++ b/tools/utils.go
@@ -14,16 +14,6 @@ import (
"golang.org/x/crypto/bcrypt"
)
-// 不建议使用的方法(即将过时)
-// Deprecated method (out of date)
-func StrToInt(err error, index string) int {
- result, err := strconv.Atoi(index)
- if err != nil {
- HasError(err, "string to int error"+err.Error(), -1)
- }
- return result
-}
-
func CompareHashAndPassword(e string, p string) (bool, error) {
err := bcrypt.CompareHashAndPassword([]byte(e), []byte(p))
if err != nil {