mirror of
https://github.com/go-admin-team/go-admin.git
synced 2026-09-24 19:17:43 +00:00
Compare commits
87
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4b87c78a7 | ||
|
|
b8f8bfd400 | ||
|
|
2d15f91f2e | ||
|
|
3a6a06f52a | ||
|
|
317d417824 | ||
|
|
8a7a9db7fd | ||
|
|
fa07a57d22 | ||
|
|
aaba20d42a | ||
|
|
4466482ad9 | ||
|
|
4140cad9dd | ||
|
|
0c64d8b927 | ||
|
|
3bd3656d15 | ||
|
|
77dfe418df | ||
|
|
8a3ee2e7af | ||
|
|
01ea376015 | ||
|
|
41b06c806a | ||
|
|
0ae41f247c | ||
|
|
560e650070 | ||
|
|
3a9831fc8c | ||
|
|
4b8c372038 | ||
|
|
d3622c93fc | ||
|
|
f0fde7f77c | ||
|
|
c93f3f01b3 | ||
|
|
4e39e915ea | ||
|
|
b98997a69f | ||
|
|
cb06f596e9 | ||
|
|
638e5b8311 | ||
|
|
b646ce9335 | ||
|
|
abc8b271c4 | ||
|
|
61451d149a | ||
|
|
671291d024 | ||
|
|
562e61cf4f | ||
|
|
d53ba4ed7a | ||
|
|
78417c2d33 | ||
|
|
5b9225ac3a | ||
|
|
05b53c0710 | ||
|
|
ca98fd873c | ||
|
|
55496078f0 | ||
|
|
c210d2301c | ||
|
|
77499b50cc | ||
|
|
3063386ec6 | ||
|
|
58c7b43759 | ||
|
|
ce80857d5f | ||
|
|
a1e0b6cc5e | ||
|
|
09e3c4f51d | ||
|
|
dc9bec2c22 | ||
|
|
8817f02038 | ||
|
|
33b462217c | ||
|
|
486a77762c | ||
|
|
87edf1099c | ||
|
|
1dffcb7199 | ||
|
|
c69a7d9fd9 | ||
|
|
5db1495985 | ||
|
|
65c4cfd684 | ||
|
|
de67c5dc46 | ||
|
|
6877e1324c | ||
|
|
60c7496f7b | ||
|
|
93cfe443d6 | ||
|
|
ffbacea589 | ||
|
|
7373536d36 | ||
|
|
9f0ceda347 | ||
|
|
22f5d39209 | ||
|
|
d3376acc34 | ||
|
|
aca9e19551 | ||
|
|
d27583421b | ||
|
|
7215f7c236 | ||
|
|
c2742e5f96 | ||
|
|
7b4ff44360 | ||
|
|
87aa013cf7 | ||
|
|
5a793b9e34 | ||
|
|
128e34ab04 | ||
|
|
b9d3483ba3 | ||
|
|
2c8c7688b4 | ||
|
|
a2f1721ee1 | ||
|
|
b26258c8ab | ||
|
|
242902d2bc | ||
|
|
2d11163ce5 | ||
|
|
7140ff8a3a | ||
|
|
cc6c333372 | ||
|
|
77bfc07826 | ||
|
|
a33b0d036a | ||
|
|
729154212f | ||
|
|
e345ffe9af | ||
|
|
afb98f5e81 | ||
|
|
826eef40a3 | ||
|
|
589a9b7d9c | ||
|
|
7889e49633 |
+2
-1
@@ -7,8 +7,9 @@ temp/
|
||||
vendor
|
||||
config/settings.dev.yml
|
||||
go-admin
|
||||
middleware/demo.go
|
||||
common/middleware/demo.go
|
||||
config/settings.dev.b.yml
|
||||
temp/logs
|
||||
config/settings.dev.yml.log
|
||||
config/settings.b.dev.yml
|
||||
cmd/migrate/migration/version-local/*
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package public
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"go-admin/pkg/utils"
|
||||
"go-admin/tools/app"
|
||||
"io/ioutil"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// @Summary 上传图片
|
||||
// @Description 获取JSON
|
||||
// @Tags 公共接口
|
||||
// @Accept multipart/form-data
|
||||
// @Param type query string true "type" (1:单图,2:多图, 3:base64图片)
|
||||
// @Param file formData file true "file"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/public/uploadFile [post]
|
||||
|
||||
|
||||
|
||||
func UploadFile(c *gin.Context) {
|
||||
tag,_ := c.GetPostForm("type")
|
||||
urlPerfix := fmt.Sprintf("http://%s/",c.Request.Host)
|
||||
if tag == ""{
|
||||
app.Error(c,200,errors.New(""),"缺少标识")
|
||||
return
|
||||
} else {
|
||||
switch tag {
|
||||
case "1": // 单图
|
||||
files,err := c.FormFile("file")
|
||||
if err != nil {
|
||||
app.Error(c,200,errors.New(""),"图片不能为空")
|
||||
return
|
||||
}
|
||||
// 上传文件至指定目录
|
||||
guid := uuid.New().String()
|
||||
|
||||
singleFile := "static/uploadfile/" + guid + utils.GetExt(files.Filename)
|
||||
_ = c.SaveUploadedFile(files, singleFile)
|
||||
app.OK(c, urlPerfix + singleFile, "上传成功")
|
||||
return
|
||||
case "2": // 多图
|
||||
files := c.Request.MultipartForm.File["file"]
|
||||
multipartFile := make([]string, len(files))
|
||||
for _, f := range files {
|
||||
guid := uuid.New().String()
|
||||
multipartFileName := "static/uploadfile/" + guid + utils.GetExt(f.Filename)
|
||||
_ = c.SaveUploadedFile(f, multipartFileName)
|
||||
multipartFile = append(multipartFile, urlPerfix + multipartFileName)
|
||||
}
|
||||
app.OK(c, multipartFile, "上传成功")
|
||||
return
|
||||
case "3": // base64
|
||||
files,_ := c.GetPostForm("file")
|
||||
ddd, _ := base64.StdEncoding.DecodeString(files)
|
||||
guid := uuid.New().String()
|
||||
_ = ioutil.WriteFile("static/uploadfile/" + guid+ ".jpg", ddd, 0666)
|
||||
app.OK(c, urlPerfix + "static/uploadfile/" + guid+ ".jpg", "上传成功")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package sysjob
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/jobs"
|
||||
"go-admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetSysJobList(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.JobId, _ = tools.StringToInt(c.Request.FormValue("jobId"))
|
||||
data.JobName = c.Request.FormValue("jobName")
|
||||
data.JobGroup = c.Request.FormValue("jobGroup")
|
||||
data.CronExpression = c.Request.FormValue("cronExpression")
|
||||
data.InvokeTarget = c.Request.FormValue("invokeTarget")
|
||||
data.Status, _ = tools.StringToInt(c.Request.FormValue("status"))
|
||||
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.PageOK(c, result, count, pageIndex, pageSize, "")
|
||||
}
|
||||
|
||||
func GetSysJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
data.JobId, _ = tools.StringToInt(c.Param("jobId"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func InsertSysJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func UpdateSysJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
err := c.ShouldBindJSON(&data)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.JobId)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func DeleteSysJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("jobId", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, msg.DeletedFail, 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
|
||||
func RemoveJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
data.JobId, _ = tools.StringToInt(c.Param("jobId"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "", 500)
|
||||
cn := jobs.Remove(result.EntryId)
|
||||
|
||||
select {
|
||||
case res := <-cn:
|
||||
if res {
|
||||
_, _ = data.RemoveEntryID(result.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
|
||||
data.JobId, _ = tools.StringToInt(c.Param("jobId"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "", 500)
|
||||
j := &jobs.ExecJob{}
|
||||
j.InvokeTarget = result.InvokeTarget
|
||||
j.CronExpression = result.CronExpression
|
||||
j.JobId = result.JobId
|
||||
j.Name = result.JobName
|
||||
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)
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 登录日志列表
|
||||
@@ -1,12 +1,14 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 登录日志列表
|
||||
@@ -1,14 +1,15 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/disk"
|
||||
"github.com/shirou/gopsutil/mem"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -54,9 +55,9 @@ func ServerInfo(c *gin.Context) {
|
||||
memDic["usage"] = memUsedPercent
|
||||
|
||||
cpuDic := make(map[string]interface{}, 0)
|
||||
cpuDic["cpuInfo"],_ = cpu.Info()
|
||||
percent,_ := cpu.Percent(0,false)
|
||||
cpuDic["Percent"] = fmt.Sprintf("%.2f",percent[0])
|
||||
cpuDic["cpuInfo"], _ = cpu.Info()
|
||||
percent, _ := cpu.Percent(0, false)
|
||||
cpuDic["Percent"] = tools.Round(percent[0], 2)
|
||||
cpuDic["cpuNum"], _ = cpu.Counts(false)
|
||||
|
||||
app.Custum(c, gin.H{
|
||||
@@ -0,0 +1,104 @@
|
||||
package public
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
imgType "github.com/shamsher31/goimgtype"
|
||||
|
||||
"go-admin/pkg/utils"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
type FileResponse struct {
|
||||
Size int64 `json:"size"`
|
||||
Path string `json:"path"`
|
||||
FullPath string `json:"full_path"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// @Summary 上传图片
|
||||
// @Description 获取JSON
|
||||
// @Tags 公共接口
|
||||
// @Accept multipart/form-data
|
||||
// @Param type query string true "type" (1:单图,2:多图, 3:base64图片)
|
||||
// @Param file formData file true "file"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/public/uploadFile [post]
|
||||
func UploadFile(c *gin.Context) {
|
||||
tag, _ := c.GetPostForm("type")
|
||||
urlPerfix := fmt.Sprintf("http://%s/", c.Request.Host)
|
||||
var fileResponse FileResponse
|
||||
if tag == "" {
|
||||
app.Error(c, 200, errors.New(""), "缺少标识")
|
||||
return
|
||||
} else {
|
||||
switch tag {
|
||||
case "1": // 单图
|
||||
files, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
app.Error(c, 200, errors.New(""), "图片不能为空")
|
||||
return
|
||||
}
|
||||
// 上传文件至指定目录
|
||||
guid := uuid.New().String()
|
||||
|
||||
singleFile := "static/uploadfile/" + guid + utils.GetExt(files.Filename)
|
||||
_ = c.SaveUploadedFile(files, singleFile)
|
||||
fileType, _ := imgType.Get(singleFile)
|
||||
fileResponse = FileResponse{
|
||||
Size: tools.GetFileSize(singleFile),
|
||||
Path: singleFile,
|
||||
FullPath: urlPerfix + singleFile,
|
||||
Name: files.Filename,
|
||||
Type: fileType,
|
||||
}
|
||||
app.OK(c, fileResponse, "上传成功")
|
||||
return
|
||||
case "2": // 多图
|
||||
files := c.Request.MultipartForm.File["file"]
|
||||
var multipartFile []FileResponse
|
||||
for _, f := range files {
|
||||
guid := uuid.New().String()
|
||||
multipartFileName := "static/uploadfile/" + guid + utils.GetExt(f.Filename)
|
||||
e := c.SaveUploadedFile(f, multipartFileName)
|
||||
fileType, _ := imgType.Get(multipartFileName)
|
||||
if e == nil {
|
||||
multipartFile = append(multipartFile, FileResponse{
|
||||
Size: tools.GetFileSize(multipartFileName),
|
||||
Path: multipartFileName,
|
||||
FullPath: urlPerfix + multipartFileName,
|
||||
Name: f.Filename,
|
||||
Type: fileType,
|
||||
})
|
||||
}
|
||||
}
|
||||
app.OK(c, multipartFile, "上传成功")
|
||||
return
|
||||
case "3": // base64
|
||||
files, _ := c.GetPostForm("file")
|
||||
file2list := strings.Split(files, ",")
|
||||
ddd, _ := base64.StdEncoding.DecodeString(file2list[1])
|
||||
guid := uuid.New().String()
|
||||
base64File := "static/uploadfile/" + guid + ".jpg"
|
||||
_ = ioutil.WriteFile(base64File, ddd, 0666)
|
||||
typeStr := strings.Replace(strings.Replace(file2list[0], "data:", "", -1), ";base64", "", -1)
|
||||
fileResponse = FileResponse{
|
||||
Size: tools.GetFileSize(base64File),
|
||||
Path: base64File,
|
||||
FullPath: urlPerfix + base64File,
|
||||
Name: "",
|
||||
Type: typeStr,
|
||||
}
|
||||
app.OK(c, fileResponse, "上传成功")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package syscategory
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
func GetSysCategoryList(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.Name = c.Request.FormValue("name")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.PageOK(c, result, count, pageIndex, pageSize, "")
|
||||
}
|
||||
|
||||
func GetSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
data.Id, _ = tools.StringToInt(c.Param("id"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 添加分类
|
||||
// @Description 获取JSON
|
||||
// @Tags 分类
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysCategory true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/syscategory [post]
|
||||
func InsertSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func UpdateSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.Id)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func DeleteSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("id", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, msg.DeletedFail, 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package syscontent
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
func GetSysContentList(c *gin.Context) {
|
||||
var data models.SysContent
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.CateId = c.Request.FormValue("cateId")
|
||||
data.Name = c.Request.FormValue("name")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.PageOK(c, result, count, pageIndex, pageSize, "")
|
||||
}
|
||||
|
||||
func GetSysContent(c *gin.Context) {
|
||||
var data models.SysContent
|
||||
data.Id, _ = tools.StringToInt(c.Param("id"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 添加内容管理
|
||||
// @Description 获取JSON
|
||||
// @Tags 内容管理
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysContent true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/syscontent [post]
|
||||
func InsertSysContent(c *gin.Context) {
|
||||
var data models.SysContent
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func UpdateSysContent(c *gin.Context) {
|
||||
var data models.SysContent
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.Id)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func DeleteSysContent(c *gin.Context) {
|
||||
var data models.SysContent
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("id", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, msg.DeletedFail, 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package sysfiledir
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
func GetSysFileDirList(c *gin.Context) {
|
||||
var SysFileDir models.SysFileDir
|
||||
SysFileDir.Label = c.Request.FormValue("label")
|
||||
SysFileDir.PId, _ = tools.StringToInt(c.Request.FormValue("pid"))
|
||||
SysFileDir.Id, _ = tools.StringToInt(c.Request.FormValue("id"))
|
||||
SysFileDir.DataScope = tools.GetUserIdStr(c)
|
||||
result, err := SysFileDir.SetSysFileDir()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func GetSysFileDir(c *gin.Context) {
|
||||
var data models.SysFileDir
|
||||
data.Id, _ = tools.StringToInt(c.Param("id"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 添加SysFileDir
|
||||
// @Description 获取JSON
|
||||
// @Tags SysFileDir
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysFileDir true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/sysfiledir [post]
|
||||
func InsertSysFileDir(c *gin.Context) {
|
||||
var data models.SysFileDir
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func UpdateSysFileDir(c *gin.Context) {
|
||||
var data models.SysFileDir
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.Id)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func DeleteSysFileDir(c *gin.Context) {
|
||||
var data models.SysFileDir
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("id", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, msg.DeletedFail, 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package sysfileinfo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
func GetSysFileInfoList(c *gin.Context) {
|
||||
var data models.SysFileInfo
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
tools.HasError(err, "", -1)
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
tools.HasError(err, "", -1)
|
||||
if pid := c.Request.FormValue("pId"); pid != "" {
|
||||
data.PId, err = tools.StringToInt(pid)
|
||||
}
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.PageOK(c, result, count, pageIndex, pageSize, "")
|
||||
}
|
||||
|
||||
func GetSysFileInfo(c *gin.Context) {
|
||||
var data models.SysFileInfo
|
||||
data.Id, _ = tools.StringToInt(c.Param("id"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func InsertSysFileInfo(c *gin.Context) {
|
||||
var data models.SysFileInfo
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func UpdateSysFileInfo(c *gin.Context) {
|
||||
var data models.SysFileInfo
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.Id)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func DeleteSysFileInfo(c *gin.Context) {
|
||||
var data models.SysFileInfo
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("id", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, msg.DeletedFail, 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package sysjob
|
||||
|
||||
import (
|
||||
"go-admin/common/dto"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/jobs"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/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,6 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/captcha"
|
||||
@@ -1,13 +1,15 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 配置列表数据
|
||||
@@ -3,7 +3,8 @@ package system
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
@@ -1,12 +1,14 @@
|
||||
package dict
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 字典数据列表
|
||||
@@ -103,7 +105,7 @@ func GetDictDataByDictType(c *gin.Context) {
|
||||
// @Security Bearer
|
||||
func InsertDictData(c *gin.Context) {
|
||||
var data models.DictData
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
@@ -1,12 +1,14 @@
|
||||
package dict
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 字典类型列表数据
|
||||
@@ -17,7 +19,7 @@ import (
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Success 200 {object} app.PageResponse "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type/list [get]
|
||||
// @Security Bearer
|
||||
func GetDictTypeList(c *gin.Context) {
|
||||
@@ -42,15 +44,7 @@ func GetDictTypeList(c *gin.Context) {
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
var mp = make(map[string]interface{}, 3)
|
||||
mp["list"] = result
|
||||
mp["count"] = count
|
||||
mp["pageIndex"] = pageIndex
|
||||
mp["pageSize"] = pageSize
|
||||
|
||||
var res app.Response
|
||||
res.Data = mp
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
app.PageOK(c, result, count, pageIndex, pageSize, "")
|
||||
}
|
||||
|
||||
// @Summary 通过字典id获取字典类型
|
||||
@@ -2,7 +2,8 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -3,7 +3,8 @@ package system
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -2,7 +2,8 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -2,8 +2,8 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -75,14 +75,17 @@ func GetRole(c *gin.Context) {
|
||||
func InsertRole(c *gin.Context) {
|
||||
var data models.SysRole
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", 500)
|
||||
err := c.Bind(&data)
|
||||
tools.HasError(err, "数据解析失败", 500)
|
||||
id, err := data.Insert()
|
||||
tools.HasError(err, "", -1)
|
||||
data.RoleId = id
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
var t models.RoleMenu
|
||||
_, err = t.Insert(id, data.MenuIds)
|
||||
tools.HasError(err, "", -1)
|
||||
if len(data.MenuIds) > 0 {
|
||||
_, err = t.Insert(id, data.MenuIds)
|
||||
tools.HasError(err, "", -1)
|
||||
}
|
||||
app.OK(c, data, "添加成功")
|
||||
}
|
||||
|
||||
@@ -104,10 +107,11 @@ func UpdateRole(c *gin.Context) {
|
||||
tools.HasError(err, "", -1)
|
||||
var t models.RoleMenu
|
||||
_, err = t.DeleteRoleMenu(data.RoleId)
|
||||
tools.HasError(err, "添加失败1", -1)
|
||||
_, err2 := t.Insert(data.RoleId, data.MenuIds)
|
||||
tools.HasError(err2, "添加失败2", -1)
|
||||
|
||||
tools.HasError(err, "修改失败(delete rm)", -1)
|
||||
if len(data.MenuIds) > 0 {
|
||||
_, err2 := t.Insert(data.RoleId, data.MenuIds)
|
||||
tools.HasError(err2, "修改失败(insert)", -1)
|
||||
}
|
||||
app.OK(c, result, "修改成功")
|
||||
}
|
||||
|
||||
@@ -141,9 +145,6 @@ func DeleteRole(c *gin.Context) {
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("roleId", c)
|
||||
_, err := Role.BatchDelete(IDS)
|
||||
tools.HasError(err, "删除失败1", -1)
|
||||
var t models.RoleMenu
|
||||
_, err = t.BatchDeleteRoleMenu(IDS)
|
||||
tools.HasError(err, "删除失败1", -1)
|
||||
tools.HasError(err, "删除失败", -1)
|
||||
app.OK(c, "", "删除成功")
|
||||
}
|
||||
@@ -2,10 +2,12 @@ package system
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// @Summary RoleMenu列表数据
|
||||
@@ -3,11 +3,13 @@ package system
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// @Summary 查询系统信息
|
||||
@@ -4,8 +4,9 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/google/uuid"
|
||||
"go-admin/global"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -1,11 +1,13 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models/tools"
|
||||
|
||||
"go-admin/app/admin/models/tools"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 分页列表数据 / page list data
|
||||
@@ -1,12 +1,14 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models/tools"
|
||||
|
||||
"go-admin/app/admin/models/tools"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/config"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 分页列表数据 / page list data
|
||||
@@ -2,15 +2,17 @@ package tools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"text/template"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/global"
|
||||
"go-admin/models"
|
||||
"go-admin/models/tools"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
"go-admin/common/global"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/config"
|
||||
"net/http"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
func Preview(c *gin.Context) {
|
||||
@@ -28,6 +30,8 @@ func Preview(c *gin.Context) {
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/router.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
tab, _ := table.Get()
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
@@ -39,6 +43,8 @@ func Preview(c *gin.Context) {
|
||||
err = t4.Execute(&b4, tab)
|
||||
var b5 bytes.Buffer
|
||||
err = t5.Execute(&b5, tab)
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
|
||||
mp := make(map[string]interface{})
|
||||
mp["template/model.go.template"] = b1.String()
|
||||
@@ -46,6 +52,7 @@ func Preview(c *gin.Context) {
|
||||
mp["template/js.go.template"] = b3.String()
|
||||
mp["template/vue.go.template"] = b4.String()
|
||||
mp["template/router.go.template"] = b5.String()
|
||||
mp["template/dto.go.template"] = b6.String()
|
||||
var res app.Response
|
||||
res.Data = mp
|
||||
|
||||
@@ -58,21 +65,13 @@ func GenCode(c *gin.Context) {
|
||||
tools2.HasError(err, "", -1)
|
||||
table.TableId = id
|
||||
tab, _ := table.Get()
|
||||
ischeckrole := true
|
||||
|
||||
routerfile := "template/routercheckrole.go.template"
|
||||
|
||||
if c.Request.FormValue("ischeckrole") != "" {
|
||||
ischeckrole, err = tools2.StringToBool(c.Request.FormValue("ischeckrole"))
|
||||
if err != nil {
|
||||
ischeckrole = true
|
||||
}
|
||||
}
|
||||
|
||||
oldTest := "// {{认证路由自动补充在此处请勿删除}}"
|
||||
newText := "// {{认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1,authMiddleware)"
|
||||
|
||||
if !ischeckrole {
|
||||
if tab.IsAuth == 2 {
|
||||
oldTest = "// {{无需认证路由自动补充在此处请勿删除}}"
|
||||
newText = "// {{无需认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1)"
|
||||
routerfile = "template/routernocheckrole.go.template"
|
||||
@@ -88,10 +87,13 @@ func GenCode(c *gin.Context) {
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
|
||||
_ = tools2.PathCreate("./apis/" + tab.ModuleName + "/")
|
||||
_ = tools2.PathCreate("./models/")
|
||||
_ = tools2.PathCreate("./router/")
|
||||
_ = tools2.PathCreate("./dto/")
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/api/")
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.PackageName)
|
||||
|
||||
@@ -105,11 +107,14 @@ func GenCode(c *gin.Context) {
|
||||
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, "./models/"+tab.PackageName+".go")
|
||||
tools2.FileCreate(b2, "./apis/"+tab.ModuleName+"/"+tab.PackageName+".go")
|
||||
tools2.FileCreate(b3, "./router/"+tab.PackageName+".go")
|
||||
tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.PackageName+".js")
|
||||
tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.PackageName+"/index.vue")
|
||||
tools2.FileCreate(b6, "./dto/"+tab.PackageName+".go")
|
||||
|
||||
helper := tools2.ReplaceHelper{
|
||||
Root: "./router/router.go",
|
||||
@@ -130,6 +135,117 @@ func GenCode(c *gin.Context) {
|
||||
app.OK(c, "", "Code generated successfully!")
|
||||
}
|
||||
|
||||
func GenCodeV2(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 {
|
||||
ActionsGen(tab)
|
||||
} else {
|
||||
NOActionsGen(tab)
|
||||
}
|
||||
|
||||
app.OK(c, "", "Code generated successfully!")
|
||||
}
|
||||
|
||||
func NOActionsGen(tab tools.SysTables) {
|
||||
routerfile := "template/routercheckrole.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerfile = "template/routernocheckrole.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles("template/model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t2, err := template.ParseFiles("template/api.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerfile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.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)
|
||||
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")
|
||||
|
||||
}
|
||||
|
||||
func ActionsGen(tab tools.SysTables) {
|
||||
routerfile := "template/v2/routercheckrole.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerfile = "template/v2/routernocheckrole.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles("template/v2/model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
//t2, err := template.ParseFiles("template/v2/router.go.template")
|
||||
//tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerfile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/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 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)
|
||||
|
||||
tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
|
||||
//tools2.FileCreate(b2, "./app/"+tab.PackageName+"/router/"+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 GenMenuAndApi(c *gin.Context) {
|
||||
|
||||
table := tools.SysTables{}
|
||||
@@ -139,7 +255,7 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
table.TableId = id
|
||||
tab, _ := table.Get()
|
||||
Mmenu := models.Menu{}
|
||||
Mmenu.MenuName = tab.TBName + "管理"
|
||||
Mmenu.MenuName = tab.TBName + "Manage"
|
||||
Mmenu.Title = tab.TableComment
|
||||
Mmenu.Icon = "pass"
|
||||
Mmenu.Path = "/" + tab.TBName
|
||||
@@ -158,16 +274,16 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
Mmenu.MenuId, err = Mmenu.Create()
|
||||
|
||||
Cmenu := models.Menu{}
|
||||
Cmenu.MenuName = tab.TBName + "管理"
|
||||
Cmenu.MenuName = tab.TBName
|
||||
Cmenu.Title = tab.TableComment
|
||||
Cmenu.Icon = "pass"
|
||||
Cmenu.Path = tab.TBName
|
||||
Cmenu.MenuType = "C"
|
||||
Cmenu.Action = "无"
|
||||
Cmenu.Permission = tab.PackageName + ":" + tab.ModuleName + ":list"
|
||||
Cmenu.Permission = tab.ModuleName + ":" + tab.BusinessName + ":list"
|
||||
Cmenu.ParentId = Mmenu.MenuId
|
||||
Cmenu.NoCache = false
|
||||
Cmenu.Component = "/" + tab.ModuleName + "/index"
|
||||
Cmenu.Component = "/" + tab.BusinessName + "/index"
|
||||
Cmenu.Sort = 0
|
||||
Cmenu.Visible = "0"
|
||||
Cmenu.IsFrame = "0"
|
||||
@@ -178,13 +294,13 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
Cmenu.MenuId, err = Cmenu.Create()
|
||||
|
||||
MList := models.Menu{}
|
||||
MList.MenuName = tab.TBName
|
||||
MList.MenuName = ""
|
||||
MList.Title = "分页获取" + tab.TableComment
|
||||
MList.Icon = "pass"
|
||||
MList.Icon = ""
|
||||
MList.Path = tab.TBName
|
||||
MList.MenuType = "F"
|
||||
MList.Action = "无"
|
||||
MList.Permission = tab.PackageName + ":" + tab.ModuleName + ":query"
|
||||
MList.Permission = tab.ModuleName + ":" + tab.BusinessName + ":query"
|
||||
MList.ParentId = Cmenu.MenuId
|
||||
MList.NoCache = false
|
||||
MList.Sort = 0
|
||||
@@ -197,13 +313,13 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
MList.MenuId, err = MList.Create()
|
||||
|
||||
MCreate := models.Menu{}
|
||||
MCreate.MenuName = tab.TBName
|
||||
MCreate.MenuName = ""
|
||||
MCreate.Title = "创建" + tab.TableComment
|
||||
MCreate.Icon = "pass"
|
||||
MCreate.Icon = ""
|
||||
MCreate.Path = tab.TBName
|
||||
MCreate.MenuType = "F"
|
||||
MCreate.Action = "无"
|
||||
MCreate.Permission = tab.PackageName + ":" + tab.ModuleName + ":add"
|
||||
MCreate.Permission = tab.ModuleName + ":" + tab.BusinessName + ":add"
|
||||
MCreate.ParentId = Cmenu.MenuId
|
||||
MCreate.NoCache = false
|
||||
MCreate.Sort = 0
|
||||
@@ -216,13 +332,13 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
MCreate.MenuId, err = MCreate.Create()
|
||||
|
||||
MUpdate := models.Menu{}
|
||||
MUpdate.MenuName = tab.TBName
|
||||
MUpdate.MenuName = ""
|
||||
MUpdate.Title = "修改" + tab.TableComment
|
||||
MUpdate.Icon = "pass"
|
||||
MUpdate.Icon = ""
|
||||
MUpdate.Path = tab.TBName
|
||||
MUpdate.MenuType = "F"
|
||||
MUpdate.Action = "无"
|
||||
MUpdate.Permission = tab.PackageName + ":" + tab.ModuleName + ":edit"
|
||||
MUpdate.Permission = tab.ModuleName + ":" + tab.BusinessName + ":edit"
|
||||
MUpdate.ParentId = Cmenu.MenuId
|
||||
MUpdate.NoCache = false
|
||||
MUpdate.Sort = 0
|
||||
@@ -235,13 +351,13 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
MUpdate.MenuId, err = MUpdate.Create()
|
||||
|
||||
MDelete := models.Menu{}
|
||||
MDelete.MenuName = tab.TBName
|
||||
MDelete.MenuName = ""
|
||||
MDelete.Title = "删除" + tab.TableComment
|
||||
MDelete.Icon = "pass"
|
||||
MDelete.Icon = ""
|
||||
MDelete.Path = tab.TBName
|
||||
MDelete.MenuType = "F"
|
||||
MDelete.Action = "无"
|
||||
MDelete.Permission = tab.PackageName + ":" + tab.ModuleName + ":remove"
|
||||
MDelete.Permission = tab.ModuleName + ":" + tab.BusinessName + ":remove"
|
||||
MDelete.ParentId = Cmenu.MenuId
|
||||
MDelete.NoCache = false
|
||||
MDelete.Sort = 0
|
||||
@@ -273,10 +389,10 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
Amenu.MenuId, err = Amenu.Create()
|
||||
|
||||
AList := models.Menu{}
|
||||
AList.MenuName = tab.TBName
|
||||
AList.MenuName = ""
|
||||
AList.Title = "分页获取" + tab.TableComment
|
||||
AList.Icon = "bug"
|
||||
AList.Path = "/api/v1/" + tab.ModuleName + "List"
|
||||
AList.Path = "/api/v1/" + tab.ModuleName
|
||||
AList.MenuType = "A"
|
||||
AList.Action = "GET"
|
||||
AList.ParentId = Amenu.MenuId
|
||||
@@ -291,7 +407,7 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
AList.MenuId, err = AList.Create()
|
||||
|
||||
AGet := models.Menu{}
|
||||
AGet.MenuName = tab.TBName
|
||||
AGet.MenuName = ""
|
||||
AGet.Title = "根据id获取" + tab.TableComment
|
||||
AGet.Icon = "bug"
|
||||
AGet.Path = "/api/v1/" + tab.ModuleName + "/:id"
|
||||
@@ -309,7 +425,7 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
AGet.MenuId, err = AGet.Create()
|
||||
|
||||
ACreate := models.Menu{}
|
||||
ACreate.MenuName = tab.TBName
|
||||
ACreate.MenuName = ""
|
||||
ACreate.Title = "创建" + tab.TableComment
|
||||
ACreate.Icon = "bug"
|
||||
ACreate.Path = "/api/v1/" + tab.ModuleName
|
||||
@@ -327,10 +443,10 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
ACreate.MenuId, err = ACreate.Create()
|
||||
|
||||
AUpdate := models.Menu{}
|
||||
AUpdate.MenuName = tab.TBName
|
||||
AUpdate.MenuName = ""
|
||||
AUpdate.Title = "修改" + tab.TableComment
|
||||
AUpdate.Icon = "bug"
|
||||
AUpdate.Path = "/api/v1/" + tab.ModuleName
|
||||
AUpdate.Path = "/api/v1/" + tab.ModuleName + "/:id"
|
||||
AUpdate.MenuType = "A"
|
||||
AUpdate.Action = "PUT"
|
||||
AUpdate.ParentId = Amenu.MenuId
|
||||
@@ -345,10 +461,10 @@ func GenMenuAndApi(c *gin.Context) {
|
||||
AUpdate.MenuId, err = AUpdate.Create()
|
||||
|
||||
ADelete := models.Menu{}
|
||||
ADelete.MenuName = tab.TBName
|
||||
ADelete.MenuName = ""
|
||||
ADelete.Title = "删除" + tab.TableComment
|
||||
ADelete.Icon = "bug"
|
||||
ADelete.Path = "/api/v1/" + tab.ModuleName + "/:id"
|
||||
ADelete.Path = "/api/v1/" + tab.ModuleName
|
||||
ADelete.MenuType = "A"
|
||||
ADelete.Action = "DELETE"
|
||||
ADelete.ParentId = Amenu.MenuId
|
||||
@@ -1,12 +1,14 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/models/tools"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models/tools"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// @Summary 分页列表数据
|
||||
@@ -64,12 +66,39 @@ func GetSysTables(c *gin.Context) {
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
mp := make(map[string]interface{})
|
||||
mp["rows"] = result.Columns
|
||||
mp["list"] = result.Columns
|
||||
mp["info"] = result
|
||||
res.Data = mp
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
func GetSysTablesInfo(c *gin.Context) {
|
||||
var data tools.SysTables
|
||||
if c.Request.FormValue("tableName") != "" {
|
||||
data.TBName = c.Request.FormValue("tableName")
|
||||
}
|
||||
result, err := data.Get()
|
||||
tools2.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
mp := make(map[string]interface{})
|
||||
mp["list"] = result.Columns
|
||||
mp["info"] = result
|
||||
res.Data = mp
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
func GetSysTablesTree(c *gin.Context) {
|
||||
var data tools.SysTables
|
||||
result, err := data.GetTree()
|
||||
tools2.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 添加表结构
|
||||
// @Description 添加表结构
|
||||
// @Tags 工具 - 生成表
|
||||
@@ -200,7 +229,7 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
func UpdateSysTable(c *gin.Context) {
|
||||
var data tools.SysTables
|
||||
err := c.Bind(&data)
|
||||
tools2.HasError(err, "数据解析失败", -1)
|
||||
tools2.HasError(err, "数据解析失败", 500)
|
||||
data.UpdateBy = tools2.GetUserIdStr(c)
|
||||
result, err := data.Update()
|
||||
tools2.HasError(err, "", -1)
|
||||
@@ -1,10 +1,11 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"go-admin/handler"
|
||||
"time"
|
||||
|
||||
"go-admin/app/admin/middleware/handler"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools/config"
|
||||
"time"
|
||||
)
|
||||
|
||||
func AuthInit() (*jwt.GinJWTMiddleware, error) {
|
||||
@@ -2,11 +2,12 @@ package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func CustomError(c *gin.Context) {
|
||||
@@ -0,0 +1,58 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"go-admin/common/config"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
var WithContextDb = middleware.WithContextDb
|
||||
|
||||
func getGormFromDb(driver string, db *sql.DB, config *gorm.Config) (*gorm.DB, error) {
|
||||
switch driver {
|
||||
case "mysql":
|
||||
return gorm.Open(mysql.New(mysql.Config{Conn: db}), config)
|
||||
case "postgres":
|
||||
return gorm.Open(postgres.New(postgres.Config{Conn: db}), config)
|
||||
default:
|
||||
return nil, errors.New("not support this db driver")
|
||||
}
|
||||
}
|
||||
|
||||
func GetGormFromConfig(cfg config.Conf) map[string]*gorm.DB {
|
||||
gormDB := make(map[string]*gorm.DB)
|
||||
if cfg.GetSaas() {
|
||||
var err error
|
||||
for k, v := range cfg.GetDbs() {
|
||||
gormDB[k], err = getGormFromDb(v.Driver, v.DB, &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
SingularTable: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
global.Logger.Fatal(tools.Red(k+" connect error :"), err)
|
||||
}
|
||||
}
|
||||
return gormDB
|
||||
}
|
||||
c := cfg.GetDb()
|
||||
db, err := getGormFromDb(c.Driver, c.DB, &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
SingularTable: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
global.Logger.Fatal(tools.Red(c.Driver+" connect error :"), err)
|
||||
}
|
||||
gormDB["*"] = db
|
||||
return gormDB
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/mojocn/base64Captcha"
|
||||
"github.com/mssola/user_agent"
|
||||
"go-admin/global"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/global"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var store = base64Captcha.DefaultMemStore
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/unrolled/secure"
|
||||
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func NoFound(c *gin.Context) {
|
||||
@@ -2,15 +2,17 @@ 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"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -1,9 +1,10 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// NoCache is a middleware function that appends headers
|
||||
@@ -2,10 +2,8 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
)
|
||||
|
||||
|
||||
func InitMiddleware(r *gin.Engine) {
|
||||
// 日志处理
|
||||
r.Use(LoggerToFile())
|
||||
@@ -19,4 +17,4 @@ func InitMiddleware(r *gin.Engine) {
|
||||
r.Use(Secure)
|
||||
// Set X-Request-Id header
|
||||
r.Use(RequestId())
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,15 @@ package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/global"
|
||||
"go-admin/models"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
)
|
||||
|
||||
// 日志记录到文件
|
||||
@@ -2,18 +2,19 @@ package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/pkg/jwtauth"
|
||||
_ "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//权限检查中间件
|
||||
func AuthCheckRole() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
data, _ := c.Get("JWT_PAYLOAD")
|
||||
data, _ := c.Get(jwtauth.JwtPayloadKey)
|
||||
v := data.(jwtauth.MapClaims)
|
||||
e, err := mycasbin.Casbin()
|
||||
tools.HasError(err, "", 500)
|
||||
@@ -12,5 +12,5 @@ type CasbinRule struct {
|
||||
}
|
||||
|
||||
func (CasbinRule) TableName() string {
|
||||
return "casbin_rule"
|
||||
return "sys_casbin_rule"
|
||||
}
|
||||
@@ -2,9 +2,10 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
"go-admin/tools"
|
||||
_ "time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
@@ -34,7 +35,7 @@ func (SysConfig) TableName() string {
|
||||
// Config 创建
|
||||
func (e *SysConfig) Create() (SysConfig, error) {
|
||||
var doc SysConfig
|
||||
i := 0
|
||||
var i int64
|
||||
orm.Eloquent.Table(e.TableName()).Where("config_name=? or config_key = ?", e.ConfigName, e.ConfigKey).Count(&i)
|
||||
if i > 0 {
|
||||
return doc, errors.New("参数名称或者参数键名已经存在!")
|
||||
@@ -71,7 +72,7 @@ func (e *SysConfig) Get() (SysConfig, error) {
|
||||
func (e *SysConfig) GetPage(pageSize int, pageIndex int) ([]SysConfig, int, error) {
|
||||
var doc []SysConfig
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.ConfigName != "" {
|
||||
table = table.Where("config_name = ?", e.ConfigName)
|
||||
@@ -90,13 +91,13 @@ func (e *SysConfig) GetPage(pageSize int, pageIndex int) ([]SysConfig, int, erro
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysConfig) Update(id int) (update SysConfig, err error) {
|
||||
@@ -3,7 +3,9 @@ package models
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jinzhu/gorm"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
@@ -49,3 +51,35 @@ func (e *DataPermission) GetDataScope(tbname string, table *gorm.DB) (*gorm.DB,
|
||||
|
||||
return table, nil
|
||||
}
|
||||
|
||||
func DataScopes(tableName string, userid int) func(db *gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
SysUser := new(SysUser)
|
||||
SysRole := new(SysRole)
|
||||
SysUser.UserId = userid
|
||||
user, err := SysUser.Get()
|
||||
if err != nil {
|
||||
db.Error = errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
return db
|
||||
}
|
||||
SysRole.RoleId = user.RoleId
|
||||
role, err := SysRole.Get()
|
||||
if err != nil {
|
||||
db.Error = errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
return db
|
||||
}
|
||||
if role.DataScope == "2" {
|
||||
return db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", user.RoleId)
|
||||
}
|
||||
if role.DataScope == "3" {
|
||||
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId)
|
||||
}
|
||||
if role.DataScope == "4" {
|
||||
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(user.DeptId)+"%")
|
||||
}
|
||||
if role.DataScope == "5" || role.DataScope == "" {
|
||||
return db.Where(tableName+".create_by = ?", userid)
|
||||
}
|
||||
return db
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,10 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
"go-admin/tools"
|
||||
_ "time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysDept struct {
|
||||
@@ -52,7 +53,7 @@ func (e *SysDept) Create() (SysDept, error) {
|
||||
}
|
||||
var mp = map[string]string{}
|
||||
mp["deptPath"] = deptPath
|
||||
if err := orm.Eloquent.Table(e.TableName()).Where("dept_id = ?", e.DeptId).Update(mp).Error; err != nil {
|
||||
if err := orm.Eloquent.Table(e.TableName()).Where("dept_id = ?", e.DeptId).Updates(mp).Error; err != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
@@ -101,7 +102,7 @@ func (e *SysDept) GetList() ([]SysDept, error) {
|
||||
func (e *SysDept) GetPage(bl bool) ([]SysDept, error) {
|
||||
var doc []SysDept
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.DeptId != 0 {
|
||||
table = table.Where("dept_id = ?", e.DeptId)
|
||||
}
|
||||
@@ -2,7 +2,8 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -32,8 +33,10 @@ func (DictData) TableName() string {
|
||||
func (e *DictData) Create() (DictData, error) {
|
||||
var doc DictData
|
||||
|
||||
i := 0
|
||||
orm.Eloquent.Table(e.TableName()).Where("dict_label=? or (dict_label=? and dict_value = ?)", e.DictLabel, e.DictValue).Count(&i)
|
||||
var i int64
|
||||
if err := orm.Eloquent.Table(e.TableName()).Where("dict_label=? or (dict_label=? and dict_value = ?)", e.DictLabel, e.DictLabel, e.DictValue).Count(&i).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
if i > 0 {
|
||||
return doc, errors.New("字典标签或者字典键值已经存在!")
|
||||
}
|
||||
@@ -90,7 +93,7 @@ func (e *DictData) Get() ([]DictData, error) {
|
||||
func (e *DictData) GetPage(pageSize int, pageIndex int) ([]DictData, int, error) {
|
||||
var doc []DictData
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.DictCode != 0 {
|
||||
table = table.Where("dict_code = ?", e.DictCode)
|
||||
}
|
||||
@@ -111,13 +114,13 @@ func (e *DictData) GetPage(pageSize int, pageIndex int) ([]DictData, int, error)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Order("dict_sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Order("dict_sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *DictData) Update(id int) (update DictData, err error) {
|
||||
@@ -2,7 +2,10 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -26,7 +29,7 @@ func (DictType) TableName() string {
|
||||
func (e *DictType) Create() (DictType, error) {
|
||||
var doc DictType
|
||||
|
||||
i := 0
|
||||
var i int64
|
||||
orm.Eloquent.Table(e.TableName()).Where("dict_name=? or dict_type = ?", e.DictName, e.DictType).Count(&i)
|
||||
if i > 0 {
|
||||
return doc, errors.New("字典名称或者字典类型已经存在!")
|
||||
@@ -83,13 +86,14 @@ func (e *DictType) GetList() ([]DictType, error) {
|
||||
|
||||
func (e *DictType) GetPage(pageSize int, pageIndex int) ([]DictType, int, error) {
|
||||
var doc []DictType
|
||||
var db *gorm.DB
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.DictId != 0 {
|
||||
table = table.Where("dict_id = ?", e.DictId)
|
||||
db = db.Where("dict_id = ?", e.DictId)
|
||||
}
|
||||
if e.DictName != "" {
|
||||
table = table.Where("dict_name = ?", e.DictName)
|
||||
db = db.Where("dict_name = ?", e.DictName)
|
||||
}
|
||||
|
||||
// 数据权限控制
|
||||
@@ -99,13 +103,13 @@ func (e *DictType) GetPage(pageSize int, pageIndex int) ([]DictType, int, error)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *DictType) Update(id int) (update DictType, err error) {
|
||||
@@ -0,0 +1,178 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysFileDir struct {
|
||||
gorm.Model
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;AUTO_INCREMENT"` //
|
||||
Label string `json:"label" gorm:"type:varchar(255);"` // 名称
|
||||
PId int `json:"pId" gorm:"type:int(11);"` // 父id
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Path string `json:"path" gorm:"size:255;"` //
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 编辑人
|
||||
Children []SysFileDir `json:"children" gorm:"-"`
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
}
|
||||
|
||||
func (SysFileDir) TableName() string {
|
||||
return "sys_file_dir"
|
||||
}
|
||||
|
||||
// 创建SysFileDir
|
||||
func (e *SysFileDir) Create() (SysFileDir, error) {
|
||||
var doc SysFileDir
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
|
||||
path := "/" + tools.IntToString(e.Id)
|
||||
if int(e.PId) != 0 {
|
||||
var deptP SysFileDir
|
||||
orm.Eloquent.Table(e.TableName()).Where("id = ?", e.PId).First(&deptP)
|
||||
path = deptP.Path + path
|
||||
} else {
|
||||
path = "/0" + path
|
||||
}
|
||||
var mp = map[string]string{}
|
||||
mp["path"] = path
|
||||
if err := orm.Eloquent.Table(e.TableName()).Where("id = ?", e.Id).Updates(mp).Error; err != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
doc.Path = path
|
||||
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysFileDir
|
||||
func (e *SysFileDir) Get() (SysFileDir, error) {
|
||||
var doc SysFileDir
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Id != 0 {
|
||||
table = table.Where("id = ?", e.Id)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysFileDir带分页
|
||||
func (e *SysFileDir) GetPage() ([]SysFileDir, int, error) {
|
||||
var doc []SysFileDir
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
//dataPermission := new(DataPermission)
|
||||
//dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
//table, err := dataPermission.GetDataScope(e.TableName(), table)
|
||||
//if err != nil {
|
||||
// return nil, 0, err
|
||||
//}
|
||||
var count int64
|
||||
|
||||
if err := table.Find(&doc).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
// 更新SysFileDir
|
||||
func (e *SysFileDir) Update(id int) (update SysFileDir, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
path := "/" + tools.IntToString(e.Id)
|
||||
if int(e.Id) != 0 {
|
||||
var deptP SysFileDir
|
||||
orm.Eloquent.Table(e.TableName()).Where("id = ?", e.Id).First(&deptP)
|
||||
path = deptP.Path + path
|
||||
} else {
|
||||
path = "/0" + path
|
||||
}
|
||||
e.Path = path
|
||||
|
||||
//if e.Path != "" && e.Path != update.Path {
|
||||
// return update, errors.New("上级不允许修改!")
|
||||
//}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 删除SysFileDir
|
||||
func (e *SysFileDir) Delete(id int) (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysFileDir{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
//批量删除
|
||||
func (e *SysFileDir) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysFileDir{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysFileDir) SetSysFileDir() ([]SysFileDir, error) {
|
||||
list, _, err := e.GetPage()
|
||||
|
||||
m := make([]SysFileDir, 0)
|
||||
for i := 0; i < len(list); i++ {
|
||||
if list[i].PId != 0 {
|
||||
continue
|
||||
}
|
||||
info := SysFileDirDigui(&list, list[i])
|
||||
|
||||
m = append(m, info)
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
func SysFileDirDigui(deptlist *[]SysFileDir, menu SysFileDir) SysFileDir {
|
||||
list := *deptlist
|
||||
|
||||
min := make([]SysFileDir, 0)
|
||||
for j := 0; j < len(list); j++ {
|
||||
|
||||
if menu.Id != list[j].PId {
|
||||
continue
|
||||
}
|
||||
mi := SysFileDir{}
|
||||
mi.Id = list[j].Id
|
||||
mi.PId = list[j].PId
|
||||
mi.Label = list[j].Label
|
||||
mi.Sort = list[j].Sort
|
||||
mi.CreatedAt = list[j].CreatedAt
|
||||
mi.UpdatedAt = list[j].UpdatedAt
|
||||
mi.Children = []SysFileDir{}
|
||||
ms := SysFileDirDigui(deptlist, mi)
|
||||
min = append(min, ms)
|
||||
|
||||
}
|
||||
menu.Children = min
|
||||
return menu
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package gorm
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
)
|
||||
|
||||
func InitData(db *gorm.DB) {
|
||||
|
||||
list := []models.CasbinRule{
|
||||
{"p", "admin", "/api/v1/menulist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menu", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/databytype/", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menu", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menu/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysUserList", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysUser/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysUser/", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysUser", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysUser", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysUser/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/user/profile", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/rolelist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/role/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/role", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/role", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/role/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/configList", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/config/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/config", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/config", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/config/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menurole", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/roleMenuTreeselect/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menuTreeselect", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/rolemenu", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/rolemenu", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/rolemenu/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/deptList", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dept/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dept", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dept", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dept/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/datalist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/data/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/databytype/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/data", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/data/", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/data/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/typelist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/type/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/type", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/type", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/type/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/postlist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/post/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/post", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/post", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/post/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menu/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/menuids", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/loginloglist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/loginlog/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/operloglist", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/getinfo", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/roledatascope", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/roleDeptTreeselect/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/deptTree", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/configKey/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/logout", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/user/avatar", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/user/pwd", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/dict/typeoptionselect", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysjobList", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysjob/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysjob", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysjob", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/sysjob/:id", "DELETE", "", "", ""},
|
||||
{"p", "admin", "/api/v1/syssettingList", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/syssetting/:id", "GET", "", "", ""},
|
||||
{"p", "admin", "/api/v1/syssetting", "POST", "", "", ""},
|
||||
{"p", "admin", "/api/v1/syssetting", "PUT", "", "", ""},
|
||||
{"p", "admin", "/api/v1/syssetting/:id", "DELETE", "", "", ""},
|
||||
}
|
||||
|
||||
db.Table("casbin_rule").Create(list)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package gorm
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
)
|
||||
|
||||
func AutoMigrate(db *gorm.DB) (err error) {
|
||||
err = db.Migrator().AutoMigrate(new(models.CasbinRule),
|
||||
new(models.SysDept),
|
||||
new(models.SysConfig),
|
||||
new(tools.SysTables),
|
||||
new(tools.SysColumns),
|
||||
new(models.Menu),
|
||||
new(models.LoginLog),
|
||||
new(models.SysOperLog),
|
||||
new(models.RoleMenu),
|
||||
new(models.SysRoleDept),
|
||||
new(models.SysUser),
|
||||
new(models.SysRole),
|
||||
new(models.Post),
|
||||
new(models.DictData),
|
||||
new(models.DictType),
|
||||
new(models.SysJob),
|
||||
new(models.SysConfig),
|
||||
new(models.SysSetting),
|
||||
new(models.SysFileDir),
|
||||
new(models.SysCategory),
|
||||
new(models.SysContent))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
models.DataInit()
|
||||
return err
|
||||
}
|
||||
|
||||
func CustomMigrate(db *gorm.DB, table interface{}) error {
|
||||
return db.AutoMigrate(&table)
|
||||
}
|
||||
@@ -2,22 +2,25 @@ package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-admin/global"
|
||||
"gorm.io/gorm"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"go-admin/common/global"
|
||||
)
|
||||
|
||||
func InitDb() error {
|
||||
func InitDb(db *gorm.DB) (err error) {
|
||||
filePath := "config/db.sql"
|
||||
err := ExecSql(filePath)
|
||||
err = ExecSql(db,filePath)
|
||||
if global.Driver == "postgres" {
|
||||
filePath = "config/pg.sql"
|
||||
err = ExecSql(filePath)
|
||||
err = ExecSql(db,filePath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func ExecSql(filePath string) error {
|
||||
func ExecSql(db *gorm.DB,filePath string) error {
|
||||
sql, err := Ioutil(filePath)
|
||||
if err != nil {
|
||||
fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
|
||||
@@ -31,7 +34,8 @@ func ExecSql(filePath string) error {
|
||||
}
|
||||
sql := strings.Replace(sqlList[i]+";", "\n", "", 0)
|
||||
sql = strings.TrimSpace(sql)
|
||||
if err = global.Eloquent.Exec(sql).Error; err != nil {
|
||||
if err = db.Exec(sql).Error; err != nil {
|
||||
log.Printf("error sql: %s", sql)
|
||||
if !strings.Contains(err.Error(), "Query was empty") {
|
||||
return err
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
"time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
type LoginLog struct {
|
||||
@@ -48,7 +49,7 @@ func (e *LoginLog) Get() (LoginLog, error) {
|
||||
func (e *LoginLog) GetPage(pageSize int, pageIndex int) ([]LoginLog, int, error) {
|
||||
var doc []LoginLog
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.Ipaddr != "" {
|
||||
table = table.Where("ipaddr = ?", e.Ipaddr)
|
||||
}
|
||||
@@ -59,13 +60,13 @@ func (e *LoginLog) GetPage(pageSize int, pageIndex int) ([]LoginLog, int, error)
|
||||
table = table.Where("userName = ?", e.Username)
|
||||
}
|
||||
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Order("info_id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Order("info_id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *LoginLog) Create() (LoginLog, error) {
|
||||
@@ -2,7 +2,8 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
"time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
//sys_operlog
|
||||
@@ -57,7 +58,7 @@ func (e *SysOperLog) Get() (SysOperLog, error) {
|
||||
func (e *SysOperLog) GetPage(pageSize int, pageIndex int) ([]SysOperLog, int, error) {
|
||||
var doc []SysOperLog
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.OperIp != "" {
|
||||
table = table.Where("oper_ip = ?", e.OperIp)
|
||||
}
|
||||
@@ -71,13 +72,13 @@ func (e *SysOperLog) GetPage(pageSize int, pageIndex int) ([]SysOperLog, int, er
|
||||
table = table.Where("business_type = ?", e.BusinessType)
|
||||
}
|
||||
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Order("oper_id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Order("oper_id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysOperLog) Create() (SysOperLog, error) {
|
||||
@@ -1,7 +1,7 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -83,7 +83,7 @@ func (e *Post) GetList() ([]Post, error) {
|
||||
func (e *Post) GetPage(pageSize int, pageIndex int) ([]Post, int, error) {
|
||||
var doc []Post
|
||||
|
||||
table := orm.Eloquent.Select("*").Table(e.TableName())
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.PostId != 0 {
|
||||
table = table.Where("post_id = ?", e.PostId)
|
||||
}
|
||||
@@ -104,13 +104,13 @@ func (e *Post) GetPage(pageSize int, pageIndex int) ([]Post, int, error) {
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Order("sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Order("sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *Post) Update(id int) (update Post, err error) {
|
||||
@@ -2,7 +2,9 @@ package models
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
orm "go-admin/global"
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -32,10 +34,14 @@ type MenuIdList struct {
|
||||
MenuId int `json:"menuId"`
|
||||
}
|
||||
|
||||
func (role *SysRole) GetById(tx *gorm.DB, id interface{}) error {
|
||||
return tx.First(role, id).Error
|
||||
}
|
||||
|
||||
func (role *SysRole) GetPage(pageSize int, pageIndex int) ([]SysRole, int, error) {
|
||||
var doc []SysRole
|
||||
|
||||
table := orm.Eloquent.Select("*").Table("sys_role")
|
||||
table := orm.Eloquent.Table("sys_role")
|
||||
if role.RoleId != 0 {
|
||||
table = table.Where("role_id = ?", role.RoleId)
|
||||
}
|
||||
@@ -56,13 +62,13 @@ func (role *SysRole) GetPage(pageSize int, pageIndex int) ([]SysRole, int, error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Order("role_sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Order("role_sort").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (role *SysRole) Get() (SysRole SysRole, err error) {
|
||||
@@ -110,7 +116,7 @@ func (role *SysRole) GetRoleMeunId() ([]int, error) {
|
||||
}
|
||||
|
||||
func (role *SysRole) Insert() (id int, err error) {
|
||||
i := 0
|
||||
var i int64
|
||||
orm.Eloquent.Table(role.TableName()).Where("role_name=? or role_key = ?", role.RoleName, role.RoleKey).Count(&i)
|
||||
if i > 0 {
|
||||
return 0, errors.New("角色名称或者角色标识已经存在!")
|
||||
@@ -167,9 +173,57 @@ func (role *SysRole) Update(id int) (update SysRole, err error) {
|
||||
|
||||
//批量删除
|
||||
func (role *SysRole) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(role.TableName()).Where("role_id in (?)", id).Delete(SysRole{}).Error; err != nil {
|
||||
return
|
||||
tx := orm.Eloquent.Begin()
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if err := tx.Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
// 查询角色
|
||||
var roles []SysRole
|
||||
if err := tx.Table("sys_role").Where("role_id in (?)", id).Find(&roles).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := tx.Table("sys_user").Where("role_id in (?)", id).Count(&count).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
if count > 0 {
|
||||
tx.Rollback()
|
||||
return false, errors.New("存在绑定用户,请解绑后重试")
|
||||
}
|
||||
|
||||
// 删除角色
|
||||
if err = tx.Table(role.TableName()).Where("role_id in (?)", id).Unscoped().Delete(&SysRole{}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 删除角色菜单
|
||||
if err := tx.Table("sys_role_menu").Where("role_id in (?)", id).Delete(&RoleMenu{}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 删除casbin配置
|
||||
for i := 0; i < len(roles); i++ {
|
||||
if err := tx.Table("casbin_rule").Where("v0 in (?)", roles[0].RoleKey).Delete(&CasbinRule{}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
@@ -2,7 +2,8 @@ package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
orm "go-admin/global"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
//sys_role_dept
|
||||
@@ -2,7 +2,8 @@ package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
orm "go-admin/global"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -102,6 +103,7 @@ func (rm *RoleMenu) DeleteRoleMenu(roleId int) (bool, error) {
|
||||
|
||||
}
|
||||
|
||||
// 该方法即将弃用
|
||||
func (rm *RoleMenu) BatchDeleteRoleMenu(roleIds []int) (bool, error) {
|
||||
tx := orm.Eloquent.Begin()
|
||||
defer func() {
|
||||
@@ -139,7 +141,13 @@ func (rm *RoleMenu) BatchDeleteRoleMenu(roleIds []int) (bool, error) {
|
||||
}
|
||||
|
||||
func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
|
||||
var role SysRole
|
||||
var (
|
||||
role SysRole
|
||||
menu []Menu
|
||||
casbinRuleQueue []CasbinRule // casbinRule 待插入队列
|
||||
)
|
||||
|
||||
// 开始事务
|
||||
tx := orm.Eloquent.Begin()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
@@ -150,42 +158,62 @@ func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
|
||||
if err := tx.Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 在事务中做一些数据库操作(从这一点使用'tx',而不是'db')
|
||||
if err := tx.Table("sys_role").Where("role_id = ?", roleId).First(&role).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
var menu []Menu
|
||||
if err := tx.Table("sys_menu").Where("menu_id in (?)", menuId).Find(&menu).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
//ORM不支持批量插入所以需要拼接 sql 串
|
||||
sql := "INSERT INTO `sys_role_menu` (`role_id`,`menu_id`,`role_name`) VALUES "
|
||||
sysRoleMenuSql := "INSERT INTO `sys_role_menu` (`role_id`,`menu_id`,`role_name`) VALUES "
|
||||
casbinRuleSql := "INSERT INTO `casbin_rule` (`p_type`,`v0`,`v1`,`v2`) VALUES "
|
||||
|
||||
sql2 := "INSERT INTO casbin_rule (`p_type`,`v0`,`v1`,`v2`) VALUES "
|
||||
for i := 0; i < len(menu); i++ {
|
||||
if len(menu)-1 == i {
|
||||
//最后一条数据 以分号结尾
|
||||
sql += fmt.Sprintf("(%d,%d,'%s');", role.RoleId, menu[i].MenuId, role.RoleKey)
|
||||
if menu[i].MenuType == "A" {
|
||||
sql2 += fmt.Sprintf("('p','%s','%s','%s');", role.RoleKey, menu[i].Path, menu[i].Action)
|
||||
}
|
||||
for i, m := range menu {
|
||||
// 拼装'role_menu'表批量插入SQL语句
|
||||
sysRoleMenuSql += fmt.Sprintf("(%d,%d,'%s')", role.RoleId, m.MenuId, role.RoleKey)
|
||||
if i == len(menu)-1 {
|
||||
sysRoleMenuSql += ";" //最后一条数据 以分号结尾
|
||||
} else {
|
||||
sql += fmt.Sprintf("(%d,%d,'%s'),", role.RoleId, menu[i].MenuId, role.RoleKey)
|
||||
if menu[i].MenuType == "A" {
|
||||
sql2 += fmt.Sprintf("('p','%s','%s','%s'),", role.RoleKey, menu[i].Path, menu[i].Action)
|
||||
}
|
||||
sysRoleMenuSql += ","
|
||||
}
|
||||
if m.MenuType == "A" {
|
||||
// 加入队列
|
||||
casbinRuleQueue = append(casbinRuleQueue,
|
||||
CasbinRule{
|
||||
V0: role.RoleKey,
|
||||
V1: m.Path,
|
||||
V2: m.Action,
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := tx.Exec(sql).Error; err != nil {
|
||||
// 执行批量插入sys_role_menu
|
||||
if err := tx.Exec(sysRoleMenuSql).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
sql2 = sql2[0:len(sql2)-1] + ";"
|
||||
if err := tx.Exec(sql2).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
|
||||
// 拼装'casbin_rule'批量插入SQL语句
|
||||
// TODO: casbinRuleQueue队列不为空时才会拼装,否则直接忽略不执行'for'循环
|
||||
for i, v := range casbinRuleQueue {
|
||||
casbinRuleSql += fmt.Sprintf("('p','%s','%s','%s')", v.V0, v.V1, v.V2)
|
||||
if i == len(casbinRuleQueue)-1 {
|
||||
casbinRuleSql += ";"
|
||||
} else {
|
||||
casbinRuleSql += ","
|
||||
}
|
||||
}
|
||||
// 执行批量插入casbin_rule
|
||||
if len(casbinRuleQueue) > 0 {
|
||||
if err := tx.Exec(casbinRuleSql).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysCategory struct {
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;AUTO_INCREMENT"` // 分类Id
|
||||
Name string `json:"name" gorm:"type:varchar(255);"` // 名称
|
||||
Img string `json:"img" gorm:"type:varchar(255);"` // 图片
|
||||
Sort string `json:"sort" gorm:"type:int(4);"` // 排序
|
||||
Status string `json:"status" gorm:"type:int(1);"` // 状态
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);"` // 备注
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(64);"` // 创建者
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(64);"` // 更新者
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysCategory) TableName() string {
|
||||
return "sys_category"
|
||||
}
|
||||
|
||||
// 创建SysCategory
|
||||
func (e *SysCategory) Create() (SysCategory, error) {
|
||||
var doc SysCategory
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysCategory
|
||||
func (e *SysCategory) Get() (SysCategory, error) {
|
||||
var doc SysCategory
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Id != 0 {
|
||||
table = table.Where("id = ?", e.Id)
|
||||
}
|
||||
|
||||
if e.Name != "" {
|
||||
table = table.Where("name = ?", e.Name)
|
||||
}
|
||||
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysCategory带分页
|
||||
func (e *SysCategory) GetPage(pageSize int, pageIndex int) ([]SysCategory, int, error) {
|
||||
var doc []SysCategory
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Name != "" {
|
||||
table = table.Where("name = ?", e.Name)
|
||||
}
|
||||
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
dataPermission := new(DataPermission)
|
||||
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
table, err := dataPermission.GetDataScope(e.TableName(), table)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
// 更新SysCategory
|
||||
func (e *SysCategory) Update(id int) (update SysCategory, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 删除SysCategory
|
||||
func (e *SysCategory) Delete(id int) (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysCategory{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
//批量删除
|
||||
func (e *SysCategory) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysCategory{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysContent struct {
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;auto_increment"` // id
|
||||
CateId string `json:"cateId" gorm:"type:int(11);"` // 分类id
|
||||
Name string `json:"name" gorm:"type:varchar(255);"` // 名称
|
||||
Status string `json:"status" gorm:"type:int(1);"` // 状态
|
||||
Img string `json:"img" gorm:"type:varchar(255);"` // 图片
|
||||
Content string `json:"content" gorm:"type:text;"` // 内容
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);"` // 备注
|
||||
Sort string `json:"sort" gorm:"type:int(4);"` // 排序
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建者
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 更新者
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysContent) TableName() string {
|
||||
return "sys_content"
|
||||
}
|
||||
|
||||
// 创建SysContent
|
||||
func (e *SysContent) Create() (SysContent, error) {
|
||||
var doc SysContent
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysContent
|
||||
func (e *SysContent) Get() (SysContent, error) {
|
||||
var doc SysContent
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Id != 0 {
|
||||
table = table.Where("id = ?", e.Id)
|
||||
}
|
||||
|
||||
if e.CateId != "" {
|
||||
table = table.Where("cate_id = ?", e.CateId)
|
||||
}
|
||||
|
||||
if e.Name != "" {
|
||||
table = table.Where("name like ?", "%"+e.Name+"%")
|
||||
}
|
||||
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysContent带分页
|
||||
func (e *SysContent) GetPage(pageSize int, pageIndex int) ([]SysContent, int, error) {
|
||||
var doc []SysContent
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.CateId != "" {
|
||||
table = table.Where("cate_id = ?", e.CateId)
|
||||
}
|
||||
|
||||
if e.Name != "" {
|
||||
table = table.Where("name like ?", "%"+e.Name+"%")
|
||||
}
|
||||
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
dataPermission := new(DataPermission)
|
||||
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
table, err := dataPermission.GetDataScope(e.TableName(), table)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
// 更新SysContent
|
||||
func (e *SysContent) Update(id int) (update SysContent, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 删除SysContent
|
||||
func (e *SysContent) Delete(id int) (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysContent{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
//批量删除
|
||||
func (e *SysContent) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysContent{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
type SysFileInfo struct {
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;AUTO_INCREMENT"` // id
|
||||
Type string `json:"type" gorm:"type:varchar(255);"` // 文件类型
|
||||
Name string `json:"name" gorm:"type:varchar(255);"` // 文件名称
|
||||
Size string `json:"size" gorm:"type:int(11);"` // 文件大小
|
||||
PId int `json:"pId" gorm:"type:int(11);"` // 目录id
|
||||
Source string `json:"source" gorm:"type:varchar(255);"` // 文件源
|
||||
Url string `json:"url" gorm:"type:varchar(255);"` // 文件路径
|
||||
FullUrl string `json:"fullUrl" gorm:"type:varchar(255);"` // 文件全路径
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 编辑人
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysFileInfo) TableName() string {
|
||||
return "sys_file_info"
|
||||
}
|
||||
|
||||
// 创建SysFileInfo
|
||||
func (e *SysFileInfo) Create() (SysFileInfo, error) {
|
||||
var doc SysFileInfo
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysFileInfo
|
||||
func (e *SysFileInfo) Get() (SysFileInfo, error) {
|
||||
var doc SysFileInfo
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Id != 0 {
|
||||
table = table.Where("id = ?", e.Id)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysFileInfo带分页
|
||||
func (e *SysFileInfo) GetPage(pageSize int, pageIndex int) ([]SysFileInfo, int, error) {
|
||||
var doc []SysFileInfo
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.PId != 0 {
|
||||
table = table.Where("p_id = ?", e.PId)
|
||||
}
|
||||
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
//dataPermission := new(DataPermission)
|
||||
//dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
//table, err := dataPermission.GetDataScope(e.TableName(), table)
|
||||
//if err != nil {
|
||||
// return nil, 0, err
|
||||
//}
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
// 更新SysFileInfo
|
||||
func (e *SysFileInfo) Update(id int) (update SysFileInfo, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 删除SysFileInfo
|
||||
func (e *SysFileInfo) Delete(id int) (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysFileInfo{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
//批量删除
|
||||
func (e *SysFileInfo) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysFileInfo{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"go-admin/common/dto"
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type SysJob struct {
|
||||
JobId int `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;"` // 任务类型
|
||||
CronExpression string `json:"cronExpression" gorm:"size:255;"` // cron表达式
|
||||
InvokeTarget string `json:"invokeTarget" gorm:"size:255;"` // 调用目标
|
||||
Args string `json:"args" gorm:"size:255;"` // 目标参数
|
||||
MisfirePolicy int `json:"misfirePolicy" gorm:"size:255;"` // 执行策略
|
||||
Concurrent int `json:"concurrent" gorm:"size:1;"` // 是否并发
|
||||
Status int `json:"status" gorm:"size:1;"` // 状态
|
||||
EntryId int `json:"entry_id" gorm:"size:11;"` // job启动时返回的id
|
||||
CreateBy string `json:"createBy" gorm:"size:128;"` //
|
||||
UpdateBy string `json:"updateBy" gorm:"size:128;"` //
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysJob) TableName() string {
|
||||
return "sys_job"
|
||||
}
|
||||
|
||||
func (e *SysJob) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysJob) GetId() interface{} {
|
||||
return e.JobId
|
||||
}
|
||||
|
||||
func (e *SysJob) SetCreateBy(createBy uint) {
|
||||
e.CreateBy = strconv.Itoa(int(createBy))
|
||||
}
|
||||
|
||||
func (e *SysJob) SetUpdateBy(updateBy uint) {
|
||||
e.UpdateBy = strconv.Itoa(int(updateBy))
|
||||
}
|
||||
|
||||
// 创建SysJob
|
||||
func (e *SysJob) Create() (err error) {
|
||||
return orm.Eloquent.Table(e.TableName()).Create(e).Error
|
||||
}
|
||||
|
||||
// 获取SysJob
|
||||
func (e *SysJob) Get(id interface{}) (err error) {
|
||||
return orm.Eloquent.Table(e.TableName()).First(e, id).Error
|
||||
}
|
||||
|
||||
// 获取SysJob带分页
|
||||
func (e *SysJob) GetPage(pageSize int, pageIndex int, v interface{}, list interface{}) (int, error) {
|
||||
table := orm.Eloquent.Table(e.TableName()).Scopes(dto.MakeCondition(v))
|
||||
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
//dataPermission := new(DataPermission)
|
||||
userid, _ := tools.StringToInt(e.DataScope)
|
||||
|
||||
var count int64
|
||||
|
||||
if err := table.Scopes(DataScopes(e.TableName(), userid), dto.Paginate(pageSize, pageIndex)).Find(list).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysJob) GetList(list interface{}) (err error) {
|
||||
return orm.Eloquent.Table(e.TableName()).Where("status = ?", 2).Find(list).Error
|
||||
}
|
||||
|
||||
// 更新SysJob
|
||||
func (e *SysJob) Update(id interface{}) (err error) {
|
||||
return orm.Eloquent.Table(e.TableName()).Where(id).Updates(&e).Error
|
||||
}
|
||||
|
||||
func (e *SysJob) RemoveAllEntryID() (update SysJob, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("entry_id > ?", 0).Update("entry_id", 0).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysJob) RemoveEntryID(entryID int) (update SysJob, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("entry_id = ?", entryID).Updates(map[string]interface{}{"entry_id": 0}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 删除SysJob
|
||||
func (e *SysJob) Delete(id int) (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where(id).Delete(&SysJob{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
//批量删除
|
||||
func (e *SysJob) BatchDelete(id []int) error {
|
||||
return orm.Eloquent.Table(e.TableName()).Where(id).Delete(&SysJob{}).Error
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
type SysSetting struct {
|
||||
SettingsId int `json:"settings_id" gorm:"primary_key;AUTO_INCREMENT"`
|
||||
Name string `json:"name" gorm:"type:varchar(256);"`
|
||||
Logo string `json:"logo" gorm:"type:varchar(256);"`
|
||||
Name string `json:"name" gorm:"type:varchar(256);"`
|
||||
Logo string `json:"logo" gorm:"type:varchar(256);"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ func (s *SysSetting) Get() (create SysSetting, err error) {
|
||||
err = result.Error
|
||||
return
|
||||
}
|
||||
return create,nil
|
||||
return create, nil
|
||||
}
|
||||
|
||||
//修改
|
||||
@@ -34,6 +34,6 @@ func (s *SysSetting) Update() (update SysSetting, err error) {
|
||||
}
|
||||
|
||||
type ResponseSystemConfig struct {
|
||||
Name string `json:"name" binding:"required"` // 名称
|
||||
Logo string `json:"logo" binding:"required"` // 头像
|
||||
}
|
||||
Name string `json:"name" binding:"required"` // 名称
|
||||
Logo string `json:"logo" binding:"required"` // 头像
|
||||
}
|
||||
@@ -2,11 +2,14 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"log"
|
||||
orm "go-admin/global"
|
||||
"go-admin/tools"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
// User
|
||||
@@ -213,20 +216,19 @@ func (e *SysUser) GetPage(pageSize int, pageIndex int) ([]SysUserPage, int, erro
|
||||
table = table.Where("sys_user.dept_id in (select dept_id from sys_dept where dept_path like ? )", "%"+tools.IntToString(e.DeptId)+"%")
|
||||
}
|
||||
|
||||
// 数据权限控制
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
dataPermission := new(DataPermission)
|
||||
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
table, err := dataPermission.GetDataScope("sys_user", table)
|
||||
table, err := dataPermission.GetDataScope(e.TableName(), table)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("sys_user.deleted_at IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
//加密
|
||||
@@ -251,7 +253,7 @@ func (e SysUser) Insert() (id int, err error) {
|
||||
}
|
||||
|
||||
// check 用户名
|
||||
var count int
|
||||
var count int64
|
||||
orm.Eloquent.Table(e.TableName()).Where("username = ?", e.Username).Count(&count)
|
||||
if count > 0 {
|
||||
err = errors.New("账户已存在!")
|
||||
@@ -314,3 +316,7 @@ func (e *SysUser) SetPwd(pwd SysUserPwd) (Result bool, err error) {
|
||||
tools.HasError(err, "更新密码失败(代码202)", 500)
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysUser) GetByUserId(tx *gorm.DB, id interface{}) error {
|
||||
return tx.First(e, id).Error
|
||||
}
|
||||
@@ -2,8 +2,10 @@ package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/jinzhu/gorm"
|
||||
orm "go-admin/global"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
)
|
||||
@@ -25,11 +27,11 @@ type DBColumns struct {
|
||||
|
||||
func (e *DBColumns) GetPage(pageSize int, pageIndex int) ([]DBColumns, int, error) {
|
||||
var doc []DBColumns
|
||||
var count int
|
||||
var count int64
|
||||
table := new(gorm.DB)
|
||||
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table = orm.Eloquent.Select("*").Table("information_schema.`COLUMNS`")
|
||||
table = orm.Eloquent.Table("information_schema.`COLUMNS`")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
|
||||
if e.TableName != "" {
|
||||
@@ -39,11 +41,11 @@ func (e *DBColumns) GetPage(pageSize int, pageIndex int) ([]DBColumns, int, erro
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName)
|
||||
}
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Count(&count)
|
||||
return doc, int(count), nil
|
||||
|
||||
}
|
||||
|
||||
@@ -56,10 +58,10 @@ func (e *DBColumns) GetList() ([]DBColumns, error) {
|
||||
}
|
||||
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table = orm.Eloquent.Select("*").Table("information_schema.columns")
|
||||
table = orm.Eloquent.Table("information_schema.columns")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName)
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName).Order("ORDINAL_POSITION asc")
|
||||
} else {
|
||||
tools.Assert(true, "目前只支持mysql数据库", 500)
|
||||
}
|
||||
@@ -2,8 +2,10 @@ package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/jinzhu/gorm"
|
||||
orm "go-admin/global"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
)
|
||||
@@ -21,32 +23,32 @@ type DBTables struct {
|
||||
func (e *DBTables) GetPage(pageSize int, pageIndex int) ([]DBTables, int, error) {
|
||||
var doc []DBTables
|
||||
table := new(gorm.DB)
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table = orm.Eloquent.Select("*").Table("information_schema.tables")
|
||||
table = orm.Eloquent.Table("information_schema.tables")
|
||||
table = table.Where("TABLE_NAME not in (select table_name from " + config2.GenConfig.DBName + ".sys_tables) ")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
|
||||
if e.TableName != "" {
|
||||
table = table.Where("TABLE_NAME = ?", e.TableName)
|
||||
}
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
} else {
|
||||
tools.Assert(true, "目前只支持mysql数据库", 500)
|
||||
}
|
||||
|
||||
table.Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *DBTables) Get() (DBTables, error) {
|
||||
var doc DBTables
|
||||
table := new(gorm.DB)
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table = orm.Eloquent.Select("*").Table("information_schema.tables")
|
||||
table = orm.Eloquent.Table("information_schema.tables")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
if e.TableName == "" {
|
||||
return doc, errors.New("table name cannot be empty!")
|
||||
@@ -0,0 +1,90 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
type SysColumns struct {
|
||||
ColumnId int `gorm:"primary_key;auto_increment" json:"columnId"`
|
||||
TableId int `gorm:"" json:"tableId"`
|
||||
ColumnName string `gorm:"size:128;" json:"columnName"`
|
||||
ColumnComment string `gorm:"column:column_comment;size:128;" json:"columnComment"`
|
||||
ColumnType string `gorm:"column:column_type;size:128;" json:"columnType"`
|
||||
GoType string `gorm:"column:go_type;size:128;" json:"goType"`
|
||||
GoField string `gorm:"column:go_field;size:128;" json:"goField"`
|
||||
JsonField string `gorm:"column:json_field;size:128;" json:"jsonField"`
|
||||
IsPk string `gorm:"column:is_pk;size:4;" json:"isPk"`
|
||||
IsIncrement string `gorm:"column:is_increment;size:4;" json:"isIncrement"`
|
||||
IsRequired string `gorm:"column:is_required;size:4;" json:"isRequired"`
|
||||
IsInsert string `gorm:"column:is_insert;size:4;" json:"isInsert"`
|
||||
IsEdit string `gorm:"column:is_edit;size:4;" json:"isEdit"`
|
||||
IsList string `gorm:"column:is_list;size:4;" json:"isList"`
|
||||
IsQuery string `gorm:"column:is_query;size:4;" json:"isQuery"`
|
||||
QueryType string `gorm:"column:query_type;size:128;" json:"queryType"`
|
||||
HtmlType string `gorm:"column:html_type;size:128;" json:"htmlType"`
|
||||
DictType string `gorm:"column:dict_type;size:128;" json:"dictType"`
|
||||
Sort int `gorm:"column:sort;" json:"sort"`
|
||||
List string `gorm:"column:list;size:1;" json:"list"`
|
||||
Pk bool `gorm:"column:pk;size:1;" json:"pk"`
|
||||
Required bool `gorm:"column:required;size:1;" json:"required"`
|
||||
SuperColumn bool `gorm:"column:super_column;size:1;" json:"superColumn"`
|
||||
UsableColumn bool `gorm:"column:usable_column;size:1;" json:"usableColumn"`
|
||||
Increment bool `gorm:"column:increment;size:1;" json:"increment"`
|
||||
Insert bool `gorm:"column:insert;size:1;" json:"insert"`
|
||||
Edit bool `gorm:"column:edit;size:1;" json:"edit"`
|
||||
Query bool `gorm:"column:query;size:1;" json:"query"`
|
||||
Remark string `gorm:"column:remark;size:255;" json:"remark"`
|
||||
FkTableName string `gorm:"" json:"fkTableName"`
|
||||
FkTableNameClass string `gorm:"" json:"fkTableNameClass"`
|
||||
FkTableNamePackage string `gorm:"" json:"fkTableNamePackage"`
|
||||
FkCol []SysColumns `gorm:"-" json:"fkCol"`
|
||||
FkLabelId string `gorm:"" json:"fkLabelId"`
|
||||
FkLabelName string `gorm:"size:255;" json:"fkLabelName"`
|
||||
CreateBy string `gorm:"column:create_by;size:128;" json:"createBy"`
|
||||
UpdateBy string `gorm:"column:update_By;size:128;" json:"updateBy"`
|
||||
|
||||
models.BaseModel
|
||||
}
|
||||
|
||||
func (SysColumns) TableName() string {
|
||||
return "sys_columns"
|
||||
}
|
||||
|
||||
func (e *SysColumns) GetList() ([]SysColumns, error) {
|
||||
var doc []SysColumns
|
||||
|
||||
table := orm.Eloquent.Table("sys_columns")
|
||||
|
||||
table = table.Where("table_id = ?", e.TableId)
|
||||
|
||||
if err := table.Find(&doc).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysColumns) Create() (SysColumns, error) {
|
||||
var doc SysColumns
|
||||
result := orm.Eloquent.Table("sys_columns").Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysColumns) Update() (update SysColumns, err error) {
|
||||
if err = orm.Eloquent.Table("sys_columns").First(&update, e.ColumnId).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table("sys_columns").Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
"go-admin/models"
|
||||
"strings"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
type SysTables struct {
|
||||
@@ -10,12 +12,12 @@ type SysTables struct {
|
||||
TBName string `gorm:"column:table_name;size:255;" json:"tableName"` //表名称
|
||||
TableComment string `gorm:"size:255;" json:"tableComment"` //表备注
|
||||
ClassName string `gorm:"size:255;" json:"className"` //类名
|
||||
TplCategory string `gorm:"size:255;" json:"tplCategory"`
|
||||
PackageName string `gorm:"size:255;" json:"packageName"` //包名
|
||||
ModuleName string `gorm:"size:255;" json:"moduleName"` //模块名
|
||||
BusinessName string `gorm:"size:255;" json:"businessName"`
|
||||
FunctionName string `gorm:"size:255;" json:"functionName"` //功能名称
|
||||
FunctionAuthor string `gorm:"size:255;" json:"functionAuthor"` //功能作者
|
||||
TplCategory string `gorm:"size:255;" json:"tplCategory"` //
|
||||
PackageName string `gorm:"size:255;" json:"packageName"` //包名
|
||||
ModuleName string `gorm:"size:255;" json:"moduleName"` //模块名
|
||||
BusinessName string `gorm:"size:255;" json:"businessName"` //
|
||||
FunctionName string `gorm:"size:255;" json:"functionName"` //功能名称
|
||||
FunctionAuthor string `gorm:"size:255;" json:"functionAuthor"` //功能作者
|
||||
PkColumn string `gorm:"size:255;" json:"pkColumn"`
|
||||
PkGoField string `gorm:"size:255;" json:"pkGoField"`
|
||||
PkJsonField string `gorm:"size:255;" json:"pkJsonField"`
|
||||
@@ -26,6 +28,9 @@ type SysTables struct {
|
||||
Tree bool `gorm:"size:1;" json:"tree"`
|
||||
Crud bool `gorm:"size:1;" json:"crud"`
|
||||
Remark string `gorm:"size:255;" json:"remark"`
|
||||
IsDataScope int `gorm:"size:1;" json:"isDataScope"`
|
||||
IsActions int `gorm:"size:1;" json:"isActions"`
|
||||
IsAuth int `gorm:"size:1;" json:"isAuth"`
|
||||
IsLogicalDelete string `gorm:"size:1;" json:"isLogicalDelete"`
|
||||
LogicalDelete bool `gorm:"size:1;" json:"logicalDelete"`
|
||||
LogicalDeleteColumn string `gorm:"size:128;" json:"logicalDeleteColumn"`
|
||||
@@ -51,7 +56,7 @@ type Params struct {
|
||||
func (e *SysTables) GetPage(pageSize int, pageIndex int) ([]SysTables, int, error) {
|
||||
var doc []SysTables
|
||||
|
||||
table := orm.Eloquent.Select("*").Table("sys_tables")
|
||||
table := orm.Eloquent.Table("sys_tables")
|
||||
|
||||
if e.TBName != "" {
|
||||
table = table.Where("table_name = ?", e.TBName)
|
||||
@@ -60,19 +65,19 @@ func (e *SysTables) GetPage(pageSize int, pageIndex int) ([]SysTables, int, erro
|
||||
table = table.Where("table_comment = ?", e.TableComment)
|
||||
}
|
||||
|
||||
var count int
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, count, nil
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysTables) Get() (SysTables, error) {
|
||||
var doc SysTables
|
||||
var err error
|
||||
table := orm.Eloquent.Select("*").Table("sys_tables")
|
||||
table := orm.Eloquent.Table("sys_tables")
|
||||
|
||||
if e.TBName != "" {
|
||||
table = table.Where("table_name = ?", e.TBName)
|
||||
@@ -96,6 +101,37 @@ func (e *SysTables) Get() (SysTables, error) {
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysTables) GetTree() ([]SysTables, error) {
|
||||
var doc []SysTables
|
||||
var err error
|
||||
table := orm.Eloquent.Table("sys_tables")
|
||||
|
||||
if e.TBName != "" {
|
||||
table = table.Where("table_name = ?", e.TBName)
|
||||
}
|
||||
if e.TableId != 0 {
|
||||
table = table.Where("table_id = ?", e.TableId)
|
||||
}
|
||||
if e.TableComment != "" {
|
||||
table = table.Where("table_comment = ?", e.TableComment)
|
||||
}
|
||||
|
||||
if err := table.Find(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
for i := 0; i < len(doc); i++ {
|
||||
var col SysColumns
|
||||
//col.FkCol = append(col.FkCol, SysColumns{ColumnId: 0, ColumnName: "请选择"})
|
||||
col.TableId = doc[i].TableId
|
||||
if doc[i].Columns, err = col.GetList(); err != nil {
|
||||
return doc, err
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysTables) Create() (SysTables, error) {
|
||||
var doc SysTables
|
||||
result := orm.Eloquent.Table("sys_tables").Create(&e)
|
||||
@@ -114,28 +150,47 @@ func (e *SysTables) Create() (SysTables, error) {
|
||||
}
|
||||
|
||||
func (e *SysTables) Update() (update SysTables, err error) {
|
||||
if err = orm.Eloquent.Table("sys_tables").First(&update, e.TableId).Error; err != nil {
|
||||
return
|
||||
}
|
||||
//if err = orm.Eloquent.Table("sys_tables").First(&update, e.TableId).Error; err != nil {
|
||||
// return
|
||||
//}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table("sys_tables").Model(&update).Updates(&e).Error; err != nil {
|
||||
if err = orm.Eloquent.Table("sys_tables").Where("table_id = ?", e.TableId).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < len(e.Columns); i++ {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
tableNameList := strings.Split(e.Columns[i].FkTableName, "_")
|
||||
e.Columns[i].FkTableNameClass = ""
|
||||
e.Columns[i].FkTableNamePackage = ""
|
||||
for a := 0; a < len(tableNameList); a++ {
|
||||
strStart := string([]byte(tableNameList[a])[:1])
|
||||
strEnd := string([]byte(tableNameList[a])[1:])
|
||||
e.Columns[i].FkTableNameClass += strings.ToUpper(strStart) + strEnd
|
||||
e.Columns[i].FkTableNamePackage += strings.ToLower(strStart) + strings.ToLower(strEnd)
|
||||
}
|
||||
}
|
||||
_, _ = e.Columns[i].Update()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysTables) Delete() (success bool, err error) {
|
||||
if err = orm.Eloquent.Table("sys_tables").Delete(SysTables{}, "table_id = ?", e.TableId).Error; err != nil {
|
||||
tx := orm.Eloquent.Begin()
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
} else {
|
||||
tx.Commit()
|
||||
}
|
||||
}()
|
||||
if err = tx.Table("sys_tables").Delete(SysTables{}, "table_id = ?", e.TableId).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
if err = orm.Eloquent.Table("sys_columns").Delete(SysColumns{}, "table_id = ?", e.TableId).Error; err != nil {
|
||||
if err = tx.Table("sys_columns").Delete(SysColumns{}, "table_id = ?", e.TableId).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
@@ -2,26 +2,22 @@ package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/global"
|
||||
"go-admin/handler"
|
||||
"go-admin/middleware"
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/middleware/handler"
|
||||
"go-admin/common/global"
|
||||
_ "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
)
|
||||
|
||||
func InitRouter() *gin.Engine {
|
||||
var r *gin.Engine
|
||||
if global.GinEngine == nil {
|
||||
r = gin.New()
|
||||
} else {
|
||||
r = global.GinEngine
|
||||
}
|
||||
func InitRouter(r *gin.Engine) *gin.Engine {
|
||||
if config2.SslConfig.Enable {
|
||||
r.Use(handler.TlsHandler())
|
||||
}
|
||||
r.Use(middleware.WithContextDb(middleware.GetGormFromConfig(global.Cfg)))
|
||||
middleware.InitMiddleware(r)
|
||||
// the jwt middleware
|
||||
var err error
|
||||
authMiddleware, err := middleware.AuthInit()
|
||||
tools.HasError(err, "JWT Init Error", 500)
|
||||
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
var (
|
||||
routerNoCheckRole = make([]func(*gin.RouterGroup), 0)
|
||||
routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
|
||||
)
|
||||
|
||||
// 路由示例
|
||||
func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
|
||||
|
||||
@@ -25,7 +30,13 @@ func examplesNoCheckRoleRouter(r *gin.Engine) {
|
||||
// 空接口防止v1定义无使用报错
|
||||
v1.GET("/nilcheckrole", nil)
|
||||
|
||||
for _, f := range routerNoCheckRole {
|
||||
f(v1)
|
||||
}
|
||||
|
||||
// {{无需认证路由自动补充在此处请勿删除}}
|
||||
registerSysFileInfoRouter(v1)
|
||||
registerSysFileDirRouter(v1)
|
||||
}
|
||||
|
||||
// 需要认证的路由示例
|
||||
@@ -35,5 +46,12 @@ func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddle
|
||||
// 空接口防止v1定义无使用报错
|
||||
v1.GET("/checkrole", nil)
|
||||
|
||||
for _, f := range routerCheckRole {
|
||||
f(v1, authMiddleware)
|
||||
}
|
||||
|
||||
// {{认证路由自动补充在此处请勿删除}}
|
||||
registerSysContentRouter(v1, authMiddleware)
|
||||
registerSysCategoryRouter(v1, authMiddleware)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/syscategory"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
|
||||
r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("/:id", syscategory.GetSysCategory)
|
||||
r.POST("", syscategory.InsertSysCategory)
|
||||
r.PUT("", syscategory.UpdateSysCategory)
|
||||
r.DELETE("/:id", syscategory.DeleteSysCategory)
|
||||
}
|
||||
|
||||
l := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
l.GET("/syscategoryList", syscategory.GetSysCategoryList)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/syscontent"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysContentRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
|
||||
r := v1.Group("/syscontent").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("/:id", syscontent.GetSysContent)
|
||||
r.POST("", syscontent.InsertSysContent)
|
||||
r.PUT("", syscontent.UpdateSysContent)
|
||||
r.DELETE("/:id", syscontent.DeleteSysContent)
|
||||
}
|
||||
|
||||
l := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
l.GET("/syscontentList", syscontent.GetSysContentList)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/sysfiledir"
|
||||
"go-admin/app/admin/apis/sysfileinfo"
|
||||
)
|
||||
|
||||
// 无需认证的路由代码
|
||||
func registerSysFileInfoRouter(v1 *gin.RouterGroup) {
|
||||
|
||||
v1.GET("/sysfileinfoList", sysfileinfo.GetSysFileInfoList)
|
||||
|
||||
r := v1.Group("/sysfileinfo")
|
||||
{
|
||||
r.GET("/:id", sysfileinfo.GetSysFileInfo)
|
||||
r.POST("", sysfileinfo.InsertSysFileInfo)
|
||||
r.PUT("", sysfileinfo.UpdateSysFileInfo)
|
||||
r.DELETE("/:id", sysfileinfo.DeleteSysFileInfo)
|
||||
}
|
||||
}
|
||||
|
||||
// 无需认证的路由代码
|
||||
func registerSysFileDirRouter(v1 *gin.RouterGroup) {
|
||||
|
||||
v1.GET("/sysfiledirList", sysfiledir.GetSysFileDirList)
|
||||
|
||||
r := v1.Group("/sysfiledir")
|
||||
{
|
||||
r.GET("/:id", sysfiledir.GetSysFileDir)
|
||||
r.POST("", sysfiledir.InsertSysFileDir)
|
||||
r.PUT("", sysfiledir.UpdateSysFileDir)
|
||||
r.DELETE("/:id", sysfiledir.DeleteSysFileDir)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/sysjob"
|
||||
"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, registerSysJobRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysJobRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
|
||||
r := v1.Group("/sysjob").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
sysJob := &models.SysJob{}
|
||||
r.GET("", actions.PermissionAction(), actions.IndexAction(sysJob, new(dto.SysJobSearch), func() interface{} {
|
||||
list := make([]models.SysJob, 0)
|
||||
return &list
|
||||
}))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysJobById)))
|
||||
r.POST("", actions.CreateAction(new(dto.SysJobControl)))
|
||||
r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto.SysJobControl)))
|
||||
r.DELETE("/:id", actions.PermissionAction(), actions.DeleteAction(new(dto.SysJobById)))
|
||||
}
|
||||
|
||||
v1.GET("/job/remove/:jobId", sysjob.RemoveJob)
|
||||
v1.GET("/job/start/:jobId", sysjob.StartJob)
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"mime"
|
||||
|
||||
log2 "go-admin/app/admin/apis/log"
|
||||
"go-admin/app/admin/apis/monitor"
|
||||
"go-admin/app/admin/apis/public"
|
||||
"go-admin/app/admin/apis/system"
|
||||
"go-admin/app/admin/apis/system/dict"
|
||||
. "go-admin/app/admin/apis/tools"
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/middleware/handler"
|
||||
_ "go-admin/docs"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/pkg/ws"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
"github.com/swaggo/gin-swagger/swaggerFiles"
|
||||
log2 "go-admin/apis/log"
|
||||
"go-admin/apis/monitor"
|
||||
"go-admin/apis/public"
|
||||
"go-admin/apis/sysjob"
|
||||
"go-admin/apis/system"
|
||||
"go-admin/apis/system/dict"
|
||||
. "go-admin/apis/tools"
|
||||
_ "go-admin/docs"
|
||||
"go-admin/handler"
|
||||
"go-admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/pkg/ws"
|
||||
)
|
||||
|
||||
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
|
||||
@@ -43,13 +45,12 @@ func sysBaseRouter(r *gin.RouterGroup) {
|
||||
|
||||
r.GET("/", system.HelloWorld)
|
||||
|
||||
r.GET("/ws", ws.WebsocketManager.WsClient)
|
||||
|
||||
|
||||
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")
|
||||
}
|
||||
@@ -64,8 +65,9 @@ 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", GenCode)
|
||||
v1.GET("/gen/toproject/:tableId", GenCodeV2)
|
||||
v1.GET("/gen/todb/:tableId", GenMenuAndApi)
|
||||
v1.GET("/gen/tabletree", GetSysTablesTree)
|
||||
v1.GET("/menuTreeselect", system.GetMenuTreeelect)
|
||||
v1.GET("/dict/databytype/:dictType", dict.GetDictDataByDictType)
|
||||
|
||||
@@ -77,7 +79,6 @@ func sysNoCheckRoleRouter(r *gin.RouterGroup) {
|
||||
|
||||
registerSysSettingRouter(v1)
|
||||
|
||||
registerSysJobRouter(v1)
|
||||
}
|
||||
|
||||
func registerDBRouter(api *gin.RouterGroup) {
|
||||
@@ -98,31 +99,20 @@ func registerSysTableRouter(v1 *gin.RouterGroup) {
|
||||
tablesinfo.PUT("", UpdateSysTable)
|
||||
tablesinfo.DELETE("/:tableId", DeleteSysTables)
|
||||
tablesinfo.GET("/:tableId", GetSysTables)
|
||||
tablesinfo.GET("", GetSysTablesInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func registerSysJobRouter(v1 *gin.RouterGroup) {
|
||||
|
||||
r := v1.Group("/sysjob")
|
||||
{
|
||||
r.GET("", sysjob.GetSysJobList)
|
||||
r.GET("/:jobId", sysjob.GetSysJob)
|
||||
r.POST("", sysjob.InsertSysJob)
|
||||
r.PUT("", sysjob.UpdateSysJob)
|
||||
r.DELETE("/:jobId", sysjob.DeleteSysJob)
|
||||
}
|
||||
|
||||
v1.GET("/job/remove/:jobId",sysjob.RemoveJob)
|
||||
v1.GET("/job/start/:jobId",sysjob.StartJob)
|
||||
}
|
||||
|
||||
|
||||
func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
r.POST("/login", authMiddleware.LoginHandler)
|
||||
// Refresh time can be longer than token timeout
|
||||
r.GET("/refresh_token", authMiddleware.RefreshHandler)
|
||||
|
||||
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/ws/:id/:channel", ws.WebsocketManager.WsClient)
|
||||
|
||||
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/wslogout/:id/:channel", ws.WebsocketManager.UnWsClient)
|
||||
|
||||
v1 := r.Group("/api/v1")
|
||||
|
||||
registerPageRouter(v1, authMiddleware)
|
||||
@@ -281,7 +271,7 @@ func registerSysSettingRouter(v1 *gin.RouterGroup) {
|
||||
{
|
||||
setting.GET("", system.GetSetting)
|
||||
setting.POST("", system.CreateSetting)
|
||||
setting.GET("/serverInfo",monitor.ServerInfo)
|
||||
setting.GET("/serverInfo", monitor.ServerInfo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,4 +280,4 @@ func registerPublicRouter(v1 *gin.RouterGroup) {
|
||||
{
|
||||
p.POST("/uploadFile", public.UploadFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
models2 "go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysJobSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
JobId int `form:"jobId" search:"type:exact;column:job_id;table:sys_job"`
|
||||
JobName string `form:"jobName" search:"type:icontains;column:job_name;table:sys_job"`
|
||||
JobGroup string `form:"jobGroup" search:"type:exact;column:job_group;table:sys_job"`
|
||||
CronExpression string `form:"cronExpression" search:"type:exact;column:cron_expression;table:sys_job"`
|
||||
InvokeTarget string `form:"invokeTarget" search:"type:exact;column:invoke_target;table:sys_job"`
|
||||
Status int `form:"status" search:"type:exact;column:status;table:sys_job"`
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) Bind(ctx *gin.Context) error {
|
||||
return ctx.Bind(m)
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) GetPageIndex() int {
|
||||
return m.PageIndex
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) GetPageSize() int {
|
||||
return m.PageSize
|
||||
}
|
||||
|
||||
type SysJobControl struct {
|
||||
JobId int `json:"jobId"`
|
||||
JobName string `json:"jobName" validate:"required"` // 名称
|
||||
JobGroup string `json:"jobGroup"` // 任务分组
|
||||
JobType int `json:"jobType"` // 任务类型
|
||||
CronExpression string `json:"cronExpression"` // cron表达式
|
||||
InvokeTarget string `json:"invokeTarget"` // 调用目标
|
||||
Args string `json:"args"` // 目标参数
|
||||
MisfirePolicy int `json:"misfirePolicy"` // 执行策略
|
||||
Concurrent int `json:"concurrent"` // 是否并发
|
||||
Status int `json:"status"` // 状态
|
||||
EntryId int `json:"entryId"` // job启动时返回的id
|
||||
}
|
||||
|
||||
func (s *SysJobControl) Bind(ctx *gin.Context) error {
|
||||
return ctx.Bind(s)
|
||||
}
|
||||
|
||||
func (s *SysJobControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysJobControl) GenerateM() (models2.ActiveRecord, error) {
|
||||
return &models.SysJob{
|
||||
JobId: s.JobId,
|
||||
JobName: s.JobName,
|
||||
JobGroup: s.JobGroup,
|
||||
JobType: s.JobType,
|
||||
CronExpression: s.CronExpression,
|
||||
InvokeTarget: s.InvokeTarget,
|
||||
Args: s.Args,
|
||||
MisfirePolicy: s.MisfirePolicy,
|
||||
Concurrent: s.Concurrent,
|
||||
Status: s.Status,
|
||||
EntryId: s.EntryId,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysJobControl) GetId() interface{} {
|
||||
return s.JobId
|
||||
}
|
||||
|
||||
type SysJobById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysJobById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysJobById) GenerateM() (models2.ActiveRecord, error) {
|
||||
return &models.SysJob{}, nil
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package dto
|
||||
|
||||
type SysTableSearch struct {
|
||||
TBName string `form:"tableName" search:"type:exact;column:table_name;table:table_name"`
|
||||
TableComment string `form:"tableComment" search:"type:icontains;column:table_comment;table:table_comment"`
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 需要将定义的struct 添加到字典中;
|
||||
// 字典 key 可以配置到 自动任务 调用目标 中;
|
||||
func InitJob() {
|
||||
jobList = map[string]JobsExec{
|
||||
"ExamplesOne": ExamplesOne{},
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
// 新添加的job 必须按照以下格式定义,并实现Exec函数
|
||||
type ExamplesOne struct {
|
||||
}
|
||||
|
||||
func (t ExamplesOne) Exec(arg interface{}) error {
|
||||
str := time.Now().Format(timeFormat) + " [INFO] JobCore ExamplesOne exec success"
|
||||
// TODO: 这里需要注意 Examples 传入参数是 string 所以 arg.(string);请根据对应的类型进行转化;
|
||||
switch arg.(type) {
|
||||
|
||||
case string:
|
||||
if arg.(string) != "" {
|
||||
fmt.Println("string", arg.(string))
|
||||
fmt.Println(str, arg.(string))
|
||||
} else {
|
||||
fmt.Println("arg is nil")
|
||||
fmt.Println(str, "arg is nil")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -2,13 +2,15 @@ package jobs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/robfig/cron/v3"
|
||||
"go-admin/global"
|
||||
"go-admin/models"
|
||||
"go-admin/pkg"
|
||||
"go-admin/pkg/cronjob"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/global"
|
||||
"go-admin/pkg"
|
||||
"go-admin/pkg/cronjob"
|
||||
)
|
||||
|
||||
var timeFormat = "2006-01-02 15:04:05"
|
||||
@@ -23,6 +25,7 @@ type JobCore struct {
|
||||
JobId int
|
||||
EntryId int
|
||||
CronExpression string
|
||||
Args string
|
||||
}
|
||||
|
||||
// 任务类型 http
|
||||
@@ -36,12 +39,12 @@ type ExecJob struct {
|
||||
|
||||
func (e *ExecJob) Run() {
|
||||
startTime := time.Now()
|
||||
var mp = jobList
|
||||
lock.Lock()
|
||||
var obj = mp[e.InvokeTarget]
|
||||
lock.Unlock()
|
||||
CallExec(obj.(JobsExec))
|
||||
//fmt.Println("CallExec exec success")
|
||||
var obj = jobList[e.InvokeTarget]
|
||||
if obj == nil {
|
||||
global.JobLogger.Warning(" ExecJob Run job nil", e)
|
||||
return
|
||||
}
|
||||
CallExec(obj.(JobsExec), e.Args)
|
||||
// 结束时间
|
||||
endTime := time.Now()
|
||||
|
||||
@@ -78,8 +81,7 @@ LOOP:
|
||||
// 执行时间
|
||||
latencyTime := endTime.Sub(startTime)
|
||||
//TODO: 待完善部分
|
||||
//str := time.Now().Format(timeFormat) + " [INFO] JobCore " + string(h.EntryId) + "exec success , spend :" + latencyTime.String()
|
||||
//ws.SendAll(str)
|
||||
|
||||
global.JobLogger.Info(time.Now().Format(timeFormat), " [INFO] JobCore ", h, "exec success , spend :", latencyTime)
|
||||
}
|
||||
|
||||
@@ -91,7 +93,8 @@ func Setup() {
|
||||
global.GADMCron = cronjob.NewWithSeconds()
|
||||
|
||||
sysJob := models.SysJob{}
|
||||
jobList, err := sysJob.GetList()
|
||||
jobList := make([]models.SysJob, 0)
|
||||
err := sysJob.GetList(&jobList)
|
||||
if err != nil {
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore init error", err)
|
||||
}
|
||||
@@ -119,9 +122,10 @@ func Setup() {
|
||||
j.CronExpression = jobList[i].CronExpression
|
||||
j.JobId = jobList[i].JobId
|
||||
j.Name = jobList[i].JobName
|
||||
j.Args = jobList[i].Args
|
||||
sysJob.EntryId, err = AddJob(j)
|
||||
}
|
||||
_, err = sysJob.Update(jobList[i].JobId)
|
||||
err = sysJob.Update(jobList[i].JobId)
|
||||
}
|
||||
|
||||
// 其中任务
|
||||
@@ -0,0 +1,14 @@
|
||||
package jobs
|
||||
|
||||
type Job interface {
|
||||
Run()
|
||||
addJob() (int, error)
|
||||
}
|
||||
|
||||
type JobsExec interface {
|
||||
Exec(arg interface{}) error
|
||||
}
|
||||
|
||||
func CallExec(e JobsExec, arg interface{}) error {
|
||||
return e.Exec(arg)
|
||||
}
|
||||
+31
-15
@@ -3,22 +3,24 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"go-admin/database"
|
||||
"go-admin/global"
|
||||
"go-admin/jobs"
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/router"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"go-admin/app/admin/router"
|
||||
"go-admin/app/jobs"
|
||||
"go-admin/common/database"
|
||||
"go-admin/common/global"
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -67,18 +69,32 @@ func run() error {
|
||||
if viper.GetString("settings.application.mode") == string(tools.ModeProd) {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
engine := global.Cfg.GetEngine()
|
||||
if engine == nil {
|
||||
engine = gin.New()
|
||||
}
|
||||
|
||||
r := router.InitRouter()
|
||||
defer global.Eloquent.Close()
|
||||
var r *gin.Engine
|
||||
switch engine.(type) {
|
||||
case *gin.Engine:
|
||||
r = engine.(*gin.Engine)
|
||||
default:
|
||||
panic("not support this engine")
|
||||
}
|
||||
|
||||
r = router.InitRouter(r)
|
||||
//defer global.Eloquent.Close()
|
||||
global.Cfg.SetEngine(r)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: config.ApplicationConfig.Host + ":" + config.ApplicationConfig.Port,
|
||||
Handler: r,
|
||||
Handler: global.Cfg.GetEngine(),
|
||||
}
|
||||
go func() {
|
||||
jobs.InitJob()
|
||||
jobs.Setup()
|
||||
}()
|
||||
|
||||
}()
|
||||
|
||||
go func() {
|
||||
// 服务连接
|
||||
|
||||
+9
-7
@@ -3,21 +3,23 @@ package cmd
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"go-admin/cmd/api"
|
||||
"go-admin/cmd/config"
|
||||
"go-admin/cmd/migrate"
|
||||
"go-admin/cmd/version"
|
||||
"go-admin/global"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"os"
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "go-admin",
|
||||
Short: "go-admin",
|
||||
SilenceUsage: true,
|
||||
Long: `go-admin`,
|
||||
Use: "go-admin",
|
||||
Short: "go-admin",
|
||||
SilenceUsage: true,
|
||||
Long: `go-admin`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
tip()
|
||||
@@ -32,7 +34,7 @@ var rootCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func tip() {
|
||||
usageStr := `欢迎使用 `+ tools.Green( `go-admin ` +global.Version) + ` 可以使用 ` + tools.Red(`-h`) + ` 查看命令`
|
||||
usageStr := `欢迎使用 ` + tools.Green(`go-admin `+global.Version) + ` 可以使用 ` + tools.Red(`-h`) + ` 查看命令`
|
||||
usageStr1 := `也可以参考 http://doc.zhangwj.com/go-admin-site/guide/ksks.html 里边的【启动】章节`
|
||||
fmt.Printf("%s\n", usageStr)
|
||||
fmt.Printf("%s\n", usageStr1)
|
||||
|
||||
@@ -3,9 +3,10 @@ package config
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"go-admin/tools/config"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"log"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var Migrate = &Migration{
|
||||
version: make(map[string]func(db *gorm.DB, version string) error),
|
||||
}
|
||||
|
||||
type Migration struct {
|
||||
db *gorm.DB
|
||||
version map[string]func(db *gorm.DB, version string) error
|
||||
mutex sync.Mutex
|
||||
}
|
||||
|
||||
func (e *Migration) GetDb() *gorm.DB {
|
||||
return e.db
|
||||
}
|
||||
|
||||
func (e *Migration) SetDb(db *gorm.DB) {
|
||||
e.db = db
|
||||
}
|
||||
|
||||
func (e *Migration) SetVersion(k string, f func(db *gorm.DB, version string) error) {
|
||||
e.mutex.Lock()
|
||||
defer e.mutex.Unlock()
|
||||
e.version[k] = f
|
||||
}
|
||||
|
||||
func (e *Migration) Migrate() {
|
||||
versions := make([]string, 0)
|
||||
for k := range e.version {
|
||||
versions = append(versions, k)
|
||||
}
|
||||
sort.StringsAreSorted(versions)
|
||||
log.Println(versions)
|
||||
var err error
|
||||
var count int64
|
||||
for _, v := range versions {
|
||||
err = e.db.Debug().Table("sys_migration").Where("version = ?", v).Count(&count).Error
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if count > 0 {
|
||||
log.Println(count)
|
||||
count = 0
|
||||
continue
|
||||
}
|
||||
err = (e.version[v])(e.db.Debug(), v)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
fileName = filepath.Base(fileName)
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
migration.Migrate.SetVersion(fileName, _1599190683659Tables)
|
||||
}
|
||||
|
||||
func _1599190683659Tables(db *gorm.DB, version string) error {
|
||||
err := db.Debug().Migrator().AutoMigrate(
|
||||
new(models.CasbinRule),
|
||||
new(models.SysDept),
|
||||
new(models.SysConfig),
|
||||
new(tools.SysTables),
|
||||
new(tools.SysColumns),
|
||||
new(models.Menu),
|
||||
new(models.LoginLog),
|
||||
new(models.SysOperLog),
|
||||
new(models.RoleMenu),
|
||||
new(models.SysRoleDept),
|
||||
new(models.SysUser),
|
||||
new(models.SysRole),
|
||||
new(models.Post),
|
||||
new(models.DictData),
|
||||
new(models.DictType),
|
||||
new(models.SysJob),
|
||||
new(models.SysConfig),
|
||||
new(models.SysSetting),
|
||||
new(models.SysFileDir),
|
||||
new(models.SysCategory),
|
||||
new(models.SysContent),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
fileName = filepath.Base(fileName)
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
migration.Migrate.SetVersion(fileName, _1599190683670Test)
|
||||
}
|
||||
|
||||
func _1599190683670Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
if err := models.InitDb(tx); err != nil {
|
||||
|
||||
}
|
||||
|
||||
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
fileName = filepath.Base(fileName)
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
migration.Migrate.SetVersion(fileName, _1599190683680Test)
|
||||
}
|
||||
|
||||
func _1599190683680Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
|
||||
list := []models.Menu{
|
||||
{MenuId: 496, MenuName: "Sources", Title: "资源管理", Icon: "network", Path: "/sources", Paths: "/0/496", MenuType: "M", Action: "无", Permission: "", ParentId: 0, NoCache: true, Breadcrumb: "", Component: "Layout", Sort: 3, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 497, MenuName: "File", Title: "文件管理", Icon: "documentation", Path: "filemanage", Paths: "/0/496/497", MenuType: "C", Action: "", Permission: "", ParentId: 496, NoCache: true, Breadcrumb: "", Component: "/filemanage/index", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 498, MenuName: "", Title: "内容管理", Icon: "pass", Path: "/content", Paths: "/0/498", MenuType: "M", Action: "无", Permission: "", ParentId: 0, NoCache: true, Breadcrumb: "", Component: "Layout", Sort: 4, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 499, MenuName: "SysCategory", Title: "分类", Icon: "pass", Path: "syscategory", Paths: "/0/498/499", MenuType: "C", Action: "无", Permission: "syscategory:syscategory:list", ParentId: 498, NoCache: true, Breadcrumb: "", Component: "/syscategory/index", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 500, MenuName: "", Title: "分页获取分类", Icon: "pass", Path: "", Paths: "/0/498/499/500", MenuType: "F", Action: "无", Permission: "syscategory:syscategory:query", ParentId: 499, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 501, MenuName: "", Title: "创建分类", Icon: "pass", Path: "", Paths: "/0/498/499/501", MenuType: "F", Action: "无", Permission: "syscategory:syscategory:add", ParentId: 499, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 502, MenuName: "", Title: "修改分类", Icon: "pass", Path: "", Paths: "/0/498/499/502", MenuType: "F", Action: "无", Permission: "syscategory:syscategory:edit", ParentId: 499, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 503, MenuName: "", Title: "删除分类", Icon: "pass", Path: "", Paths: "/0/498/499/503", MenuType: "F", Action: "无", Permission: "syscategory:syscategory:remove", ParentId: 499, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 504, MenuName: "Category", Title: "分类", Icon: "bug", Path: "category", Paths: "/0/63/504", MenuType: "M", Action: "无", Permission: "", ParentId: 63, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 505, MenuName: "", Title: "分页获取分类", Icon: "bug", Path: "/api/v1/syscategoryList", Paths: "/0/63/504/505", MenuType: "A", Action: "GET", Permission: "", ParentId: 504, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 506, MenuName: "", Title: "根据id获取分类", Icon: "bug", Path: "/api/v1/syscategory/:id", Paths: "/0/63/504/506", MenuType: "A", Action: "GET", Permission: "", ParentId: 504, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 507, MenuName: "", Title: "创建分类", Icon: "bug", Path: "/api/v1/syscategory", Paths: "/0/63/504/507", MenuType: "A", Action: "POST", Permission: "", ParentId: 504, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 508, MenuName: "", Title: "修改分类", Icon: "bug", Path: "/api/v1/syscategory", Paths: "/0/63/504/508", MenuType: "A", Action: "PUT", Permission: "", ParentId: 504, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 509, MenuName: "", Title: "删除分类", Icon: "bug", Path: "/api/v1/syscategory/:id", Paths: "/0/63/504/509", MenuType: "A", Action: "DELETE", Permission: "", ParentId: 504, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 511, MenuName: "SysContent", Title: "内容管理", Icon: "pass", Path: "syscontent", Paths: "/0/498/511", MenuType: "C", Action: "无", Permission: "syscontent:syscontent:list", ParentId: 498, NoCache: true, Breadcrumb: "", Component: "/syscontent/index", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 512, MenuName: "", Title: "分页获取内容管理", Icon: "pass", Path: "", Paths: "/0/510/511/512", MenuType: "F", Action: "无", Permission: "syscontent:syscontent:query", ParentId: 511, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 513, MenuName: "", Title: "创建内容管理", Icon: "pass", Path: "", Paths: "/0/510/511/513", MenuType: "F", Action: "无", Permission: "syscontent:syscontent:add", ParentId: 511, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 514, MenuName: "", Title: "修改内容管理", Icon: "pass", Path: "", Paths: "/0/510/511/514", MenuType: "F", Action: "无", Permission: "syscontent:syscontent:edit", ParentId: 511, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 515, MenuName: "", Title: "删除内容管理", Icon: "pass", Path: "", Paths: "/0/510/511/515", MenuType: "F", Action: "无", Permission: "syscontent:syscontent:remove", ParentId: 511, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 516, MenuName: "Content", Title: "内容管理", Icon: "bug", Path: "content", Paths: "/0/63/516", MenuType: "M", Action: "无", Permission: "", ParentId: 63, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 517, MenuName: "", Title: "分页获取内容管理", Icon: "bug", Path: "/api/v1/syscontentList", Paths: "/0/63/516/517", MenuType: "A", Action: "GET", Permission: "", ParentId: 516, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 518, MenuName: "", Title: "根据id获取内容管理", Icon: "bug", Path: "/api/v1/syscontent/:id", Paths: "/0/63/516/518", MenuType: "A", Action: "GET", Permission: "", ParentId: 516, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 519, MenuName: "", Title: "创建内容管理", Icon: "bug", Path: "/api/v1/syscontent", Paths: "/0/63/516/519", MenuType: "A", Action: "POST", Permission: "", ParentId: 516, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 520, MenuName: "", Title: "修改内容管理", Icon: "bug", Path: "/api/v1/syscontent", Paths: "/0/63/516/520", MenuType: "A", Action: "PUT", Permission: "", ParentId: 516, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 521, MenuName: "", Title: "删除内容管理", Icon: "bug", Path: "/api/v1/syscontent/:id", Paths: "/0/63/516/521", MenuType: "A", Action: "DELETE", Permission: "", ParentId: 516, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
}
|
||||
|
||||
err = tx.Create(list).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
+24
-17
@@ -2,23 +2,23 @@ package migrate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-admin/database"
|
||||
"go-admin/global"
|
||||
"go-admin/models"
|
||||
"go-admin/models/gorm"
|
||||
"github.com/spf13/cobra"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
_ "go-admin/cmd/migrate/migration/version"
|
||||
"go-admin/common/database"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/models"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/tools/config"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
configYml string
|
||||
mode string
|
||||
exec bool
|
||||
StartCmd = &cobra.Command{
|
||||
Use: "init",
|
||||
Short: "Initialize the database",
|
||||
Example: "go-admin init -c config/settings.yml",
|
||||
Use: "migrate",
|
||||
Short: "Initialize the database",
|
||||
Example: "go-admin migrate -c config/settings.yml",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
run()
|
||||
},
|
||||
@@ -27,7 +27,7 @@ var (
|
||||
|
||||
func init() {
|
||||
StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
|
||||
StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
|
||||
//StartCmd.PersistentFlags().BoolVarP(&exec, "exec", "e", false, "exec script")
|
||||
}
|
||||
|
||||
func run() {
|
||||
@@ -40,19 +40,26 @@ func run() {
|
||||
//3. 初始化数据库链接
|
||||
database.Setup(config.DatabaseConfig.Driver)
|
||||
//4. 数据库迁移
|
||||
fmt.Println("数据库迁移开始")
|
||||
_ = migrateModel()
|
||||
fmt.Println("数据库结构初始化成功!")
|
||||
//fmt.Println("数据库结构初始化成功!")
|
||||
//5. 数据初始化完成
|
||||
if err := models.InitDb(); err != nil {
|
||||
global.Logger.Fatal("数据库基础数据初始化失败!")
|
||||
}
|
||||
//if err := models.InitDb(); err != nil {
|
||||
// global.Logger.Fatalf("数据库基础数据初始化失败!error: %v ", err)
|
||||
//}
|
||||
usage = `数据库基础数据初始化成功`
|
||||
fmt.Println(usage)
|
||||
}
|
||||
|
||||
func migrateModel() error {
|
||||
if config.DatabaseConfig.Driver == "mysql" {
|
||||
global.Eloquent = global.Eloquent.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
|
||||
global.Eloquent.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
|
||||
}
|
||||
return gorm.AutoMigrate(global.Eloquent)
|
||||
err := global.Eloquent.Debug().AutoMigrate(&models.Migration{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
migration.Migrate.SetDb(global.Eloquent.Debug())
|
||||
migration.Migrate.Migrate()
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@ package version
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"go-admin/global"
|
||||
|
||||
"go-admin/common/global"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -27,4 +29,3 @@ func run() error {
|
||||
fmt.Println(global.Version)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// CreateAction 通用新增动作
|
||||
func CreateAction(control dto2.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
req := control.Generate()
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//新增操作
|
||||
db := idb.(*gorm.DB)
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "模型生成失败", 422)
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
err = db.WithContext(c).Create(object).Error
|
||||
tools.HasError(err, "创建失败", 500)
|
||||
app.OK(c, object.GetId(), "创建成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools/app"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
// DeleteAction 通用删除动作
|
||||
func DeleteAction(control dto2.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//删除操作
|
||||
db := idb.(*gorm.DB)
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "模型生成失败", 500)
|
||||
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
db = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).Delete(object)
|
||||
tools.HasError(db.Error, "删除失败", 500)
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
tools.HasError(err, "", 403)
|
||||
}
|
||||
app.OK(c, object.GetId(), "删除成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// IndexAction 通用查询动作
|
||||
func IndexAction(m models.ActiveRecord, d dto2.Index, f func() interface{}) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
list := f()
|
||||
object := m.Generate()
|
||||
req := d.Generate()
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
var count int64
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//查询列表
|
||||
db := idb.(*gorm.DB)
|
||||
err = c.Bind(req)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
err = db.WithContext(c).Model(object).
|
||||
Scopes(
|
||||
dto2.MakeCondition(req.GetNeedSearch()),
|
||||
dto2.Paginate(req.GetPageSize(), req.GetPageIndex()),
|
||||
Permission(object.TableName(), p),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(&count).Error
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
tools.HasError(err, "查询失败", 500)
|
||||
}
|
||||
app.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/tools/config"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type dataPermission struct {
|
||||
DataScope string
|
||||
UserId int
|
||||
DeptId int
|
||||
RoleId int
|
||||
}
|
||||
|
||||
func PermissionAction() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
db := idb.(*gorm.DB)
|
||||
var p = new(dataPermission)
|
||||
if userId := tools.GetUserIdStr(c); userId != "" {
|
||||
p, err = newDataPermission(db, userId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{
|
||||
"code": 500,
|
||||
"msg": fmt.Sprintf("权限范围鉴定错误, error:%v", err),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Set(PermissionKey, p)
|
||||
default:
|
||||
c.JSON(500, gin.H{
|
||||
"code": 500,
|
||||
"msg": "db connect not exist",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error) {
|
||||
var err error
|
||||
p := &dataPermission{}
|
||||
|
||||
err = tx.Table("sys_user").
|
||||
Select("sys_user.user_id", "sys_role.role_id", "sys_user.dept_id", "sys_role.data_scope").
|
||||
Joins("left join sys_role on sys_role.role_id = sys_user.role_id").
|
||||
Where("sys_user.user_id = ?", userId).
|
||||
Scan(p).Error
|
||||
if err != nil {
|
||||
err = errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
switch p.DataScope {
|
||||
case "2":
|
||||
return db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", p.RoleId)
|
||||
case "3":
|
||||
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", p.DeptId)
|
||||
case "4":
|
||||
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(p.DeptId)+"%")
|
||||
case "5":
|
||||
return db.Where(tableName+".create_by = ?", p.UserId)
|
||||
default:
|
||||
return db
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getPermissionFromContext(c *gin.Context) *dataPermission {
|
||||
p := new(dataPermission)
|
||||
if pm, ok := c.Get(PermissionKey); ok {
|
||||
switch pm.(type) {
|
||||
case *dataPermission:
|
||||
p = pm.(*dataPermission)
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package actions
|
||||
|
||||
const (
|
||||
PermissionKey = "dataPermission"
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// UpdateAction 通用更新动作
|
||||
func UpdateAction(control dto2.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
req := control.Generate()
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//更新操作
|
||||
db := idb.(*gorm.DB)
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
db = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).Updates(object)
|
||||
tools.HasError(db.Error, "更新失败", 500)
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权更新该数据")
|
||||
tools.HasError(err, "", 403)
|
||||
}
|
||||
app.OK(c, object.GetId(), "更新成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools/app"
|
||||
"gopkg.in/ffmt.v1"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
// ViewAction 通用详情动作
|
||||
func ViewAction(control dto2.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//查看详情
|
||||
db := idb.(*gorm.DB)
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "模型生成失败", 500)
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
ffmt.P(object)
|
||||
err = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).First(object).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
tools.HasError(err, "查看失败", 404)
|
||||
}
|
||||
tools.HasError(err, "查看失败", 500)
|
||||
app.OK(c, object, "查看成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
|
||||
"go-admin/logger"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
saas bool
|
||||
dbs map[string]*DBConfig
|
||||
db *DBConfig
|
||||
engine http.Handler
|
||||
}
|
||||
|
||||
type DBConfig struct {
|
||||
Driver string
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// SetDbs 设置对应key的db
|
||||
func (c *Config) SetDbs(key string, db *DBConfig) {
|
||||
c.dbs[key] = db
|
||||
}
|
||||
|
||||
// GetDbs 获取所有map里的db数据
|
||||
func (c *Config) GetDbs() map[string]*DBConfig {
|
||||
return c.dbs
|
||||
}
|
||||
|
||||
// GetDbByKey 根据key获取db
|
||||
func (c *Config) GetDbByKey(key string) *DBConfig {
|
||||
return c.dbs[key]
|
||||
}
|
||||
|
||||
// SetDb 设置单个db
|
||||
func (c *Config) SetDb(db *DBConfig) {
|
||||
c.db = db
|
||||
}
|
||||
|
||||
// GetDb 获取单个db
|
||||
func (c *Config) GetDb() *DBConfig {
|
||||
return c.db
|
||||
}
|
||||
|
||||
// SetEngine 设置路由引擎
|
||||
func (c *Config) SetEngine(engine http.Handler) {
|
||||
c.engine = engine
|
||||
}
|
||||
|
||||
// GetEngine 获取路由引擎
|
||||
func (c *Config) GetEngine() http.Handler {
|
||||
return c.engine
|
||||
}
|
||||
|
||||
// SetLogger 设置日志组件
|
||||
func (c *Config) SetLogger(l logger.Logger) {
|
||||
logger.DefaultLogger = l
|
||||
}
|
||||
|
||||
// GetLogger 获取日志组件
|
||||
func (c *Config) GetLogger() logger.Logger {
|
||||
return logger.DefaultLogger
|
||||
}
|
||||
|
||||
// SetSaas 设置是否是saas应用
|
||||
func (c *Config) SetSaas(saas bool) {
|
||||
c.saas = saas
|
||||
}
|
||||
|
||||
// GetSaas 获取是否是saas应用
|
||||
func (c *Config) GetSaas() bool {
|
||||
return c.saas
|
||||
}
|
||||
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user