This commit is contained in:
zhangwenjian committed 2020-09-29 08:41:20 +08:00
1 parent 677cdb7821
commit bc648c3f2f
60 files changed
+2319 -550

No files matched your search

+1 -1
View File
@@ -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/*
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+211
View File
@@ -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(), "删除成功")
}
+212
View File
@@ -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(), "删除成功")
}
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
-58
View File
@@ -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)
}
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+114
View File
@@ -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"
-19
View File
@@ -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",
})
}
-166
View File
@@ -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,
})
}
-2
View File
@@ -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())
}
-26
View File
@@ -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()
}
}
+27
View File
@@ -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
}
+26
View File
@@ -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
}
+1 -1
View File
@@ -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;"` // 任务类型
+25
View File
@@ -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)
}
}
+25
View File
@@ -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)
}
}
+1 -6
View File
@@ -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)
+89
View File
@@ -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
}
+87
View File
@@ -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:姓名"` //
}
+2 -2
View File
@@ -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"` // 任务类型
+119
View File
@@ -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
}
+121
View File
@@ -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
}
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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),
+1 -1
View File
@@ -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(
+14 -9
View File
@@ -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)
}
+1 -1
View File
@@ -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),
+1 -1
View File
@@ -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),
+42
View File
@@ -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)
}
-7
View File
@@ -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
}
+5 -5
View File
@@ -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 {
+30
View File
@@ -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
}
@@ -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)))
}
}
@@ -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)))
}
}
+116
View File
@@ -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
}
+47
View File
@@ -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
})
}
+37
View File
@@ -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}}
}
+211
View File
@@ -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(), "删除成功")
}
@@ -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}})
}
}
@@ -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}})
}
}
+121
View File
@@ -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
}
+472
View File
@@ -0,0 +1,472 @@
{{$tableComment:=.TableComment}}
<template>
<BasicLayout>
<template #wrapper>
<el-card class="box-card">
<el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
{{range .Columns}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
<el-form-item label="{{.ColumnComment}}" prop="{{.JsonField}}">
{{- if ne .FkTableName "" -}}
<el-select v-model="form.{{.JsonField}}"
placeholder="请选择" {{if eq .IsEdit "false" -}} :disabled="isEdit" {{- end }}>
<el-option
v-for="dict in {{.JsonField}}Options"
:key="dict.key"
:label="dict.value"
:value="dict.key"
/>
</el-select>
{{- else -}}
{{if eq .DictType "" -}}
<el-input v-model="queryParams.{{.JsonField}}" placeholder="请输入{{.ColumnComment}}" clearable
size="small" @keyup.enter.native="handleQuery"/>
{{- else -}}
<el-select v-model="queryParams.{{.JsonField}}"
placeholder="{{$tableComment}}{{.ColumnComment}}" clearable size="small">
<el-option
v-for="dict in {{.JsonField}}Options"
:key="dict.dictValue"
:label="dict.dictLabel"
:value="dict.dictValue"
/>
</el-select>
{{- end}}
{{- end}}
</el-form-item>
{{end}}
{{- end }}
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:add']"
type="primary"
icon="el-icon-plus"
size="mini"
@click="handleAdd"
>新增
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:edit']"
type="success"
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
>修改
</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:remove']"
type="danger"
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
>删除
</el-button>
</el-col>
</el-row>
<el-table v-loading="loading" :data="{{.ModuleName}}List" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center"/>
{{- range .Columns -}}
{{- $x := .IsList -}}
{{- if (eq $x "1") }}
{{- if ne .FkTableName "" -}}
<el-table-column label="{{.ColumnComment}}" align="center" prop="{{.JsonField}}" :formatter="{{.JsonField}}Format" width="100">
<template slot-scope="scope">
{{ "{{" }} {{.JsonField}}Format(scope.row) {{"}}"}}
</template>
</el-table-column>
{{- else -}}
{{- if ne .DictType "" -}}
<el-table-column label="{{.ColumnComment}}" align="center" prop="{{.JsonField}}"
:formatter="{{.JsonField}}Format" width="100">
<template slot-scope="scope">
{{ "{{" }} {{.JsonField}}Format(scope.row) {{"}}"}}
</template>
</el-table-column>
{{- end -}}
{{- if eq .DictType "" -}}
<el-table-column label="{{.ColumnComment}}" align="center" prop="{{.JsonField}}"
:show-overflow-tooltip="true"/>
{{- end -}}
{{- end -}}
{{- end }}
{{- end }}
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:edit']"
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
>修改
</el-button>
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:remove']"
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
>删除
</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageIndex"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px">
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
{{ 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 }}
<el-form-item label="{{.ColumnComment}}" prop="{{.JsonField}}">
{{ if eq "input" .HtmlType -}}
<el-input v-model="form.{{.JsonField}}" placeholder="{{.ColumnComment}}"
{{if eq .IsEdit "false" -}}:disabled="isEdit" {{- end}}/>
{{- else if eq "select" .HtmlType -}}
{{- if ne .FkTableName "" -}}
<el-select v-model="form.{{.JsonField}}"
placeholder="请选择" {{if eq .IsEdit "false" -}} :disabled="isEdit" {{- end }}>
<el-option
v-for="dict in {{.JsonField}}Options"
:key="dict.key"
:label="dict.value"
:value="dict.key"
/>
</el-select>
{{- else -}}
<el-select v-model="form.{{.JsonField}}"
placeholder="请选择" {{if eq .IsEdit "false" -}} :disabled="isEdit" {{- end }}>
<el-option
v-for="dict in {{.JsonField}}Options"
:key="dict.dictValue"
:label="dict.dictLabel"
:value="dict.dictValue"
/>
</el-select>
{{- end -}}
{{- else if eq "radio" .HtmlType -}}
<el-radio-group v-model="form.{{.JsonField}}">
<el-radio
v-for="dict in {{.JsonField}}Options"
:key="dict.dictValue"
:label="dict.dictValue"
>{{"{{"}} dict.dictLabel {{"}}"}}</el-radio>
</el-radio-group>
{{- else if eq "file" .HtmlType -}}
<el-input
v-model="form.{{.JsonField}}"
placeholder="图片"
/>
<el-button type="primary" @click="fileShow{{.GoField}}">选择文件</el-button>
{{- else if eq "datetime" .HtmlType -}}
<el-date-picker
v-model="form.{{.JsonField}}"
type="datetime"
placeholder="选择日期">
</el-date-picker>
{{- else if eq "textarea" .HtmlType -}}
<el-input
v-model="form.{{.JsonField}}"
type="textarea"
:rows="2"
placeholder="请输入内容">
</el-input>
{{- end }}
</el-form-item>
{{- end }}
{{- end }}
{{- end }}
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
<FileChoose ref="fileChoose" :dialog-form-visible="fileOpen" @confirm="getImgList" @close="fileClose" />
</el-card>
</template>
</BasicLayout>
</template>
<script>
import {add{{.ClassName}}, del{{.ClassName}}, get{{.ClassName}}, list{{.ClassName}}, update{{.ClassName}}} from '@/api/{{ .BusinessName}}'
{{range .Columns}}
{{- if ne .FkTableName "" -}}
import {list{{.FkTableNameClass}} } from '@/api/{{ .FkTableNamePackage}}'
{{ end -}}
{{- end -}}
import FileChoose from '@/components/FileChoose'
export default {
name: '{{.ClassName}}',
components: {
FileChoose
},
data() {
return {
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 总条数
total: 0,
// 弹出层标题
title: '',
// 是否显示弹出层
open: false,
isEdit: false,
fileOpen: false,
fileIndex: undefined,
// 类型数据字典
typeOptions: [],
{{.ModuleName}}List: [],
{{range .Columns}}
{{- if ne .DictType "" -}}
{{.JsonField}}Options: [],
{{- end -}}
{{- end }}
// 关系表类型
{{range .Columns}}
{{- if ne .FkTableName "" -}}
{{.JsonField}}Options :[],
{{ end -}}
{{- end }}
// 查询参数
queryParams: {
pageIndex: 1,
pageSize: 10,
{{ range .Columns }}
{{- if (.IsQuery) -}}
{{.JsonField}}:undefined,
{{ end -}}
{{- end }}
},
// 表单参数
form: {
},
// 表单校验
rules: {
{{- range .Columns -}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
{{.JsonField}}:
[
{required: true, message: '{{.ColumnComment}}不能为空', trigger: 'blur'}
],
{{ end }}
{{- end -}}
}
}
},
created() {
this.getList()
{{range .Columns}}
{{- if ne .DictType "" -}}
this.getDicts('{{.DictType}}').then(response => {
this.{{.JsonField}}Options = response.data
})
{{ end -}}
{{- if ne .FkTableName "" -}}
this.get{{.FkTableNameClass}}Items()
{{ end -}}
{{- end -}}
},
methods: {
/** 查询参数列表 */
getList() {
this.loading = true
list{{.ClassName}}(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
this.{{.ModuleName}}List = response.data.list
this.total = response.data.count
this.loading = false
}
)
},
// 取消按钮
cancel() {
this.open = false
this.reset()
},
// 表单重置
reset() {
this.form = {
{{ range .Columns}}
{{- $x := .IsInsert -}}
{{- if ($x) -}}
{{- 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 }}
{{.JsonField}}: undefined,
{{- end }}
{{- end -}}
{{- end }}
}
this.resetForm('form')
},
getImgList: function() {
this.form[this.fileIndex] = this.$refs['fileChoose'].resultList[0].fullUrl
},
fileClose: function() {
this.fileOpen = false
},
{{range .Columns}}
{{- if ne .DictType "" -}}
{{.JsonField}}Format(row) {
return this.selectDictLabel(this.{{.JsonField}}Options, row.{{.JsonField}})
},
{{ end -}}
{{- if ne .FkTableName "" -}}
{{.JsonField}}Format(row) {
return this.selectItemsLabel(this.{{.JsonField}}Options, row.{{.JsonField}})
},
{{ end -}}
{{- end -}}
// 关系
{{range .Columns}}
{{- if ne .FkTableName "" -}}
get{{.FkTableNameClass}}Items() {
this.getItems(list{{.FkTableNameClass}}, undefined).then(res => {
this.{{.JsonField}}Options = this.setItems(res, '{{.FkLabelId}}', '{{.FkLabelName}}')
})
},
{{ end -}}
{{- end -}}
// 文件
{{range .Columns}}
{{- if eq .HtmlType "file" -}}
fileShow{{.GoField}}: function() {
this.fileOpen = true
this.fileIndex = '{{.JsonField}}'
},
{{ end -}}
{{- end -}}
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageIndex = 1
this.getList()
},
/** 重置按钮操作 */
resetQuery() {
this.dateRange = []
this.resetForm('queryForm')
this.handleQuery()
},
/** 新增按钮操作 */
handleAdd() {
this.reset()
this.open = true
this.title = '添加{{.TableComment}}'
this.isEdit = false
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.{{.PkJsonField}})
this.single = selection.length !== 1
this.multiple = !selection.length
},
/** 修改按钮操作 */
handleUpdate(row) {
this.reset()
const {{.PkJsonField}} =
row.{{.PkJsonField}} || this.ids
get{{.ClassName}}({{.PkJsonField}}).then(response => {
this.form = response.data
this.open = true
this.title = '修改{{.TableComment}}'
this.isEdit = true
})
},
/** 提交按钮 */
submitForm: function () {
this.$refs['form'].validate(valid => {
if (valid) {
if (this.form.{{.PkJsonField}} !== undefined) {
update{{.ClassName}}(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess('修改成功')
this.open = false
this.getList()
} else {
this.msgError(response.msg)
}
})
} else {
add{{.ClassName}}(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess('新增成功')
this.open = false
this.getList()
} else {
this.msgError(response.msg)
}
})
}
}
})
},
/** 删除按钮操作 */
handleDelete(row) {
var Ids = (row.{{.PkJsonField}} && [row.{{.PkJsonField}}]) || this.ids
if (this.ids.length === 0) {
Ids = [Ids]
}
this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function () {
return del{{.ClassName}}( { 'ids': Ids })
}).then(() => {
this.getList()
this.msgSuccess('删除成功')
}).catch(function () {
})
}
}
}
</script>
+10 -113
View File
@@ -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)
}
-15
View File
@@ -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 是为了四舍五入,如果不希望这样去掉这个
}
+13 -1
View File
@@ -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 是为了四舍五入,如果不希望这样去掉这个
}
-7
View File
@@ -1,7 +0,0 @@
package tools
import "strconv"
func Int64ToString(e int64) string {
return strconv.FormatInt(e, 10)
}
-16
View File
@@ -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)
}
+1 -51
View File
@@ -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
}
}
-6
View File
@@ -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, ",")
-10
View File
@@ -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 {