mirror of
https://github.com/go-admin-team/go-admin.git
synced 2026-09-24 19:17:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07cb061ea5 | ||
|
|
5078403569 | ||
|
|
5e3e16025c | ||
|
|
4b5b0507e9 | ||
|
|
ccd76445f2 | ||
|
|
706c72b973 | ||
|
|
22fb2b5d0b | ||
|
|
16775cee45 | ||
|
|
2195c89099 | ||
|
|
199fc180b7 | ||
|
|
55112db749 | ||
|
|
da4637d285 | ||
|
|
a68e58f93b | ||
|
|
c814439f93 | ||
|
|
cc34268791 | ||
|
|
b94acb62ca | ||
|
|
c851e82762 | ||
|
|
870b144557 | ||
|
|
ac5b10e6c0 | ||
|
|
e1965be2ab | ||
|
|
b931925f75 | ||
|
|
e53cc4a9b5 | ||
|
|
b40d376e25 | ||
|
|
52f42616a2 | ||
|
|
01c519e894 | ||
|
|
93feb4779e | ||
|
|
61bf06c49b | ||
|
|
8ef816c2a9 | ||
|
|
8705ad0436 | ||
|
|
c350c8e32a | ||
|
|
f2703f16d5 | ||
|
|
7a0fff117b | ||
|
|
209db87d05 | ||
|
|
d12b1b7384 | ||
|
|
21603d5a4c | ||
|
|
bd658d9f0b | ||
|
|
9e640cf422 | ||
|
|
d1d545b29c | ||
|
|
1e8544f1ce | ||
|
|
2ecabd1202 | ||
|
|
4741137c9a | ||
|
|
f4c5aacf32 | ||
|
|
72a95babe5 | ||
|
|
3b5ce7ffaf | ||
|
|
7db918c495 | ||
|
|
faa8de7dc2 | ||
|
|
68c51fb480 | ||
|
|
4fe68183ba | ||
|
|
918e5c2ce1 | ||
|
|
ce656bf7a1 | ||
|
|
4be26aa5d2 | ||
|
|
dd09f52343 | ||
|
|
606aa821d5 | ||
|
|
99acf0086f | ||
|
|
c9b073908e | ||
|
|
000cd1d07d | ||
|
|
ca8d1e7e33 | ||
|
|
bc648c3f2f | ||
|
|
677cdb7821 | ||
|
|
7e2e40df56 | ||
|
|
2c23ef8c6d | ||
|
|
dab93f16b0 | ||
|
|
43dd214a7e | ||
|
|
c0ac9a6397 | ||
|
|
78bb246390 | ||
|
|
029783a685 | ||
|
|
8460b3f385 | ||
|
|
f3e0e4dbc6 | ||
|
|
72a876f37a | ||
|
|
7d8a267da7 | ||
|
|
2fe2c96e82 | ||
|
|
fdbb76086e | ||
|
|
a8d5846483 | ||
|
|
a06bd289b3 | ||
|
|
6bc3e6c00b | ||
|
|
91f2adb340 | ||
|
|
21d217c42a | ||
|
|
50464dc6e6 | ||
|
|
bb07d90407 | ||
|
|
3d5a2ea9f7 | ||
|
|
ca4ed89536 | ||
|
|
9cab65af6a | ||
|
|
7bba9b44b5 | ||
|
|
fd27170946 | ||
|
|
c6735c4b1a | ||
|
|
106ca70acc | ||
|
|
e0f5a9ede2 | ||
|
|
ab28eea2f3 | ||
|
|
6f09ecca32 | ||
|
|
0b80ac635d | ||
|
|
31544ff1ae | ||
|
|
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 | ||
|
|
c2f593de48 | ||
|
|
7140ff8a3a | ||
|
|
cc6c333372 | ||
|
|
77bfc07826 | ||
|
|
a33b0d036a | ||
|
|
729154212f | ||
|
|
e345ffe9af | ||
|
|
afb98f5e81 | ||
|
|
826eef40a3 | ||
|
|
589a9b7d9c | ||
|
|
7889e49633 | ||
|
|
ed238f0143 | ||
|
|
8ebcd772b2 | ||
|
|
e9ef8a2d12 | ||
|
|
509709f3fb | ||
|
|
4dbacc7a16 | ||
|
|
ee9f823bdd | ||
|
|
68eb8f1d51 | ||
|
|
fcd91d3f18 | ||
|
|
ec4bb6ee3a | ||
|
|
938c865089 | ||
|
|
2b794c03cc | ||
|
|
94aed14389 | ||
|
|
70e0141f64 | ||
|
|
6f8ad4efe4 | ||
|
|
5d88273910 | ||
|
|
45bc92eb46 | ||
|
|
65fd96b481 | ||
|
|
e37aaee861 | ||
|
|
dca1919c69 | ||
|
|
389d2970c0 | ||
|
|
c396f318ef | ||
|
|
54f48377f0 | ||
|
|
bdde879238 | ||
|
|
d2639ccf22 | ||
|
|
e0c8c8de6a | ||
|
|
b57af6c542 | ||
|
|
b9d30eee88 | ||
|
|
18a2aeadaa | ||
|
|
2ed4869c8b | ||
|
|
980d0977fc | ||
|
|
328f7d4f4f | ||
|
|
e709ee6209 | ||
|
|
80ecefb9f7 |
+8
-2
@@ -1,4 +1,5 @@
|
||||
.idea
|
||||
.vscode
|
||||
static/uploadfile
|
||||
main.exe
|
||||
go-admin
|
||||
@@ -7,6 +8,11 @@ temp/
|
||||
vendor
|
||||
config/settings.dev.yml
|
||||
go-admin
|
||||
middleware/demo.go
|
||||
config/settings.dev.b.yml
|
||||
common/middleware/demo.go
|
||||
config/settings.dev.*.yml
|
||||
config/settings.dev.*.yml.log
|
||||
temp/logs
|
||||
config/settings.dev.yml.log
|
||||
config/settings.b.dev.yml
|
||||
cmd/migrate/migration/version-local/*
|
||||
!cmd/migrate/migration/version-local/doc.go
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
|
||||
FROM golang:alpine as builder
|
||||
|
||||
MAINTAINER xxx
|
||||
|
||||
ENV GOPROXY https://goproxy.cn/
|
||||
|
||||
WORKDIR /go/release
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
||||
RUN apk update && apk add tzdata
|
||||
|
||||
COPY ./go.mod ./go.mod
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN pwd && ls
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -a -installsuffix cgo -o go-admin .
|
||||
|
||||
FROM alpine
|
||||
|
||||
COPY --from=builder /go/release/go-admin /
|
||||
COPY --from=builder /go/release/config/ /config/
|
||||
|
||||
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["/go-admin","server","-c", "/config/settings.yml"]
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
</p>
|
||||
|
||||
|
||||
[English](https://github.com/wenjianzhang/go-admin/blob/master/README.en.md) | 简体中文
|
||||
|
||||
[English](https://github.com/go-admin-team/go-admin/blob/master/README.en.md) | 简体中文
|
||||
|
||||
|
||||
##### 基于Gin + Vue + Element UI的前后端分离权限管理系统
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
[在线文档国内](http://mydearzwj.gitee.io/go-admin-site/)
|
||||
|
||||
[前端项目](https://github.com/wenjianzhang/go-admin-ui)
|
||||
[前端项目](https://github.com/go-admin-team/go-admin-ui)
|
||||
|
||||
[视频教程](https://space.bilibili.com/565616721/channel/detail?cid=125737)
|
||||
|
||||
@@ -128,10 +128,10 @@ cd goadmin
|
||||
|
||||
```bash
|
||||
# 获取后端代码
|
||||
git clone https://github.com/wenjianzhang/go-admin.git
|
||||
git clone https://github.com/go-admin-team/go-admin.git
|
||||
|
||||
# 获取前端代码
|
||||
git clone https://github.com/wenjianzhang/go-admin-ui.git
|
||||
git clone https://github.com/go-admin-team/go-admin-ui.git
|
||||
|
||||
```
|
||||
|
||||
@@ -159,15 +159,28 @@ vi ./config/setting.yml
|
||||
#### 初始化数据库,以及服务启动
|
||||
```
|
||||
# 首次配置需要初始化数据库资源信息
|
||||
./go-admin init -c config/settings.yml -m dev
|
||||
./go-admin migrate -c config/settings.yml
|
||||
|
||||
|
||||
# 启动项目,也可以用IDE进行调试
|
||||
./go-admin server -c config/settings.yml -p 8000 -m dev
|
||||
./go-admin server -c config/settings.yml -p 8000
|
||||
|
||||
```
|
||||
|
||||
#### 使用docker 编译启动
|
||||
|
||||
```shell
|
||||
# 编译镜像
|
||||
docker build -t go-admin .
|
||||
|
||||
# 启动容器,第一个go-admin是容器名字,第二个go-admin是镜像名称
|
||||
docker run --name go-admin -p 8000:8000 -d go-admin
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 文档生成
|
||||
|
||||
```bash
|
||||
swag init
|
||||
|
||||
@@ -245,7 +258,7 @@ zhuqiyun LLL狐 星星之火 cjj770 Sam 唐*i 晓聪 aLong *渊 海马 魏镇坪
|
||||
|
||||
## 🔑 License
|
||||
|
||||
[MIT](https://github.com/wenjianzhang/go-admin/blob/master/LICENSE.md)
|
||||
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
|
||||
|
||||
Copyright (c) 2020 wenjianzhang
|
||||
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 登录日志列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param status query string false "status"
|
||||
// @Param dictCode query string false "dictCode"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/loginloglist [get]
|
||||
// @Security Bearer
|
||||
func GetLoginLogList(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
size := c.Request.FormValue("pageSize")
|
||||
if size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
|
||||
index := c.Request.FormValue("pageIndex")
|
||||
if index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.Username = c.Request.FormValue("username")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
data.Ipaddr = c.Request.FormValue("ipaddr")
|
||||
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())
|
||||
}
|
||||
|
||||
// @Summary 通过编码获取登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param infoId path int true "infoId"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/loginlog/{infoId} [get]
|
||||
// @Security Bearer
|
||||
func GetLoginLog(c *gin.Context) {
|
||||
var LoginLog models.LoginLog
|
||||
LoginLog.InfoId, _ = tools.StringToInt(c.Param("infoId"))
|
||||
result, err := LoginLog.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 添加登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.LoginLog true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/loginlog [post]
|
||||
// @Security Bearer
|
||||
func InsertLoginLog(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 修改登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.LoginLog true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/loginlog [put]
|
||||
// @Security Bearer
|
||||
func UpdateLoginLog(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", -1)
|
||||
result, err := data.Update(data.InfoId)
|
||||
tools.HasError(err, "", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 批量删除登录日志
|
||||
// @Description 删除数据
|
||||
// @Tags 登录日志
|
||||
// @Param infoId path string true "以逗号(,)分割的infoId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/loginlog/{infoId} [delete]
|
||||
func DeleteLoginLog(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
IDS := tools.IdsStrToIdsIntGroup("infoId", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, "修改失败", 500)
|
||||
var res app.Response
|
||||
res.Msg = "删除成功"
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 登录日志列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param status query string false "status"
|
||||
// @Param dictCode query string false "dictCode"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/operloglist [get]
|
||||
// @Security Bearer
|
||||
func GetOperLogList(c *gin.Context) {
|
||||
var data models.SysOperLog
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
size := c.Request.FormValue("pageSize")
|
||||
if size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
|
||||
index := c.Request.FormValue("pageIndex")
|
||||
if index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.OperName = c.Request.FormValue("operName")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
data.OperIp = c.Request.FormValue("operIp")
|
||||
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())
|
||||
}
|
||||
|
||||
// @Summary 通过编码获取登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param infoId path int true "infoId"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/operlog/{infoId} [get]
|
||||
// @Security Bearer
|
||||
func GetOperLog(c *gin.Context) {
|
||||
var OperLog models.SysOperLog
|
||||
OperLog.OperId, _ = tools.StringToInt(c.Param("operId"))
|
||||
result, err := OperLog.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 添加操作日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 操作日志
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysOperLog true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/operlog [post]
|
||||
// @Security Bearer
|
||||
func InsertOperLog(c *gin.Context) {
|
||||
var data models.SysOperLog
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 批量删除操作日志
|
||||
// @Description 删除数据
|
||||
// @Tags 操作日志
|
||||
// @Param operId path string true "以逗号(,)分割的operId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/operlog/{operId} [delete]
|
||||
func DeleteOperLog(c *gin.Context) {
|
||||
var data models.SysOperLog
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
IDS := tools.IdsStrToIdsIntGroup("operId", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, "删除失败", 500)
|
||||
var res app.Response
|
||||
res.Msg = "删除成功"
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// @Summary 配置列表数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Param configKey query string false "configKey"
|
||||
// @Param configName query string false "configName"
|
||||
// @Param configType query string false "configType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/configList [get]
|
||||
// @Security Bearer
|
||||
func GetConfigList(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
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.ConfigKey = c.Request.FormValue("configKey")
|
||||
data.ConfigName = c.Request.FormValue("configName")
|
||||
data.ConfigType = c.Request.FormValue("configType")
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
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())
|
||||
}
|
||||
|
||||
// @Summary 获取配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Param configId path int true "配置编码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/config/{configId} [get]
|
||||
// @Security Bearer
|
||||
func GetConfig(c *gin.Context) {
|
||||
var Config models.SysConfig
|
||||
Config.ConfigId, _ = tools.StringToInt(c.Param("configId"))
|
||||
result, err := Config.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 获取配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Param configKey path int true "configKey"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/configKey/{configKey} [get]
|
||||
// @Security Bearer
|
||||
func GetConfigByConfigKey(c *gin.Context) {
|
||||
var Config models.SysConfig
|
||||
Config.ConfigKey = c.Param("configKey")
|
||||
result, err := Config.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, result.ConfigValue)
|
||||
}
|
||||
|
||||
// @Summary 添加配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysConfig true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/dict/data [post]
|
||||
// @Security Bearer
|
||||
func InsertConfig(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 修改配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysConfig true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/config [put]
|
||||
// @Security Bearer
|
||||
func UpdateConfig(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.ConfigId)
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 删除配置
|
||||
// @Description 删除数据
|
||||
// @Tags 配置
|
||||
// @Param configId path int true "configId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/config/{configId} [delete]
|
||||
func DeleteConfig(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
IDS := tools.IdsStrToIdsIntGroup("configId", c)
|
||||
result, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, "修改失败", 500)
|
||||
app.OK(c, result, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"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 (
|
||||
@@ -16,6 +19,11 @@ const (
|
||||
GB = 1024 * MB
|
||||
)
|
||||
|
||||
// @Summary 系统信息
|
||||
// @Description 获取JSON
|
||||
// @Tags 系统信息
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/settings/serverInfo [get]
|
||||
func ServerInfo(c *gin.Context) {
|
||||
|
||||
osDic := make(map[string]interface{}, 0)
|
||||
@@ -25,6 +33,8 @@ func ServerInfo(c *gin.Context) {
|
||||
osDic["compiler"] = runtime.Compiler
|
||||
osDic["version"] = runtime.Version()
|
||||
osDic["numGoroutine"] = runtime.NumGoroutine()
|
||||
osDic["ip"] = tools.GetLocaHonst()
|
||||
osDic["projectDir"] = tools.GetCurrentPath()
|
||||
|
||||
dis, _ := disk.Usage("/")
|
||||
diskTotalGB := int(dis.Total) / GB
|
||||
@@ -45,6 +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"] = 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,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, err = tools.StringToInt(size)
|
||||
}
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex, err = tools.StringToInt(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,70 @@
|
||||
package sysjob
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
type SysJob struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
// RemoveJobForService 调用service实现
|
||||
func (e *SysJob) RemoveJobForService(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := e.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s", msgID, err)
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
var v dto.GeneralDelDto
|
||||
err = c.BindUri(&v)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
|
||||
app.Error(c, 422, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
s := service.SysJob{}
|
||||
s.MsgID = msgID
|
||||
s.Orm = db
|
||||
err = s.RemoveJob(&v)
|
||||
if err != nil {
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
app.OK(c, nil, s.Msg)
|
||||
}
|
||||
|
||||
// StartJobForService 启动job service实现
|
||||
func (e *SysJob) StartJobForService(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := e.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s", msgID, err)
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
var v dto.GeneralGetDto
|
||||
err = c.BindUri(&v)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
|
||||
app.Error(c, 422, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
s := service.SysJob{}
|
||||
s.Orm = db
|
||||
s.MsgID = msgID
|
||||
err = s.StartJob(&v)
|
||||
if err != nil {
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
app.OK(c, nil, s.Msg)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/captcha"
|
||||
@@ -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 字典数据列表
|
||||
@@ -27,11 +29,11 @@ func GetDictDataList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.DictLabel = c.Request.FormValue("dictLabel")
|
||||
@@ -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) {
|
||||
@@ -27,11 +29,11 @@ func GetDictTypeList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.DictName = c.Request.FormValue("dictName")
|
||||
@@ -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"
|
||||
)
|
||||
@@ -45,17 +46,22 @@ func GetMenu(c *gin.Context) {
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// GetMenuTreeRoleselect 角色修改中的菜单列表
|
||||
func GetMenuTreeRoleselect(c *gin.Context) {
|
||||
var Menu models.Menu
|
||||
var SysRole models.SysRole
|
||||
|
||||
id, err := tools.StringToInt(c.Param("roleId"))
|
||||
SysRole.RoleId = id
|
||||
result, err := Menu.SetMenuLable()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
var result *[]models.MenuLable
|
||||
menuIds := make([]int, 0)
|
||||
if id != 0 {
|
||||
menuIds, err = SysRole.GetRoleMeunId()
|
||||
if tools.GetRoleName(c) != "admin" {
|
||||
result, err = Menu.SetMenuLable()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
if id != 0 {
|
||||
menuIds, err = SysRole.GetRoleMeunId()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
}
|
||||
}
|
||||
app.Custum(c, gin.H{
|
||||
"code": 200,
|
||||
@@ -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"
|
||||
)
|
||||
@@ -24,11 +25,11 @@ func GetPostList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
id := c.Request.FormValue("postId")
|
||||
@@ -2,8 +2,9 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/models"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -26,11 +27,11 @@ func GetRoleList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.RoleKey = c.Request.FormValue("roleKey")
|
||||
@@ -75,14 +76,21 @@ 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)
|
||||
if len(data.MenuIds) > 0 {
|
||||
_, err = t.Insert(id, data.MenuIds)
|
||||
tools.HasError(err, "", -1)
|
||||
}
|
||||
|
||||
_, err = global.LoadPolicy()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, data, "添加成功")
|
||||
}
|
||||
|
||||
@@ -104,9 +112,14 @@ 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)
|
||||
}
|
||||
|
||||
_, err = global.LoadPolicy()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "修改成功")
|
||||
}
|
||||
@@ -141,9 +154,10 @@ 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)
|
||||
|
||||
_, err = global.LoadPolicy()
|
||||
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列表数据
|
||||
@@ -0,0 +1,67 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// @Summary 查询系统信息
|
||||
// @Description 获取JSON
|
||||
// @Tags 系统信息
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/setting [get]
|
||||
func GetSetting(c *gin.Context) {
|
||||
var s models.SysSetting
|
||||
r, e := s.Get()
|
||||
|
||||
if r.Logo != "" {
|
||||
if !strings.HasPrefix(r.Logo, "http") {
|
||||
r.Logo = fmt.Sprintf("http://%s/%s", c.Request.Host, r.Logo)
|
||||
}
|
||||
}
|
||||
|
||||
tools.HasError(e, "查询失败", 500)
|
||||
app.OK(c, r, "查询成功")
|
||||
}
|
||||
|
||||
// @Summary 更新或提交系统信息
|
||||
// @Description 获取JSON
|
||||
// @Tags 系统信息
|
||||
// @Param data body models.SysUser true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/system/setting [post]
|
||||
func CreateSetting(c *gin.Context) {
|
||||
var s models.ResponseSystemConfig
|
||||
if err := c.ShouldBind(&s); err != nil {
|
||||
app.Error(c, 200, errors.New("缺少必要参数"), "")
|
||||
return
|
||||
}
|
||||
|
||||
var sModel models.SysSetting
|
||||
sModel.Logo = s.Logo
|
||||
sModel.Name = s.Name
|
||||
|
||||
a, e := sModel.Update()
|
||||
if e != nil {
|
||||
app.Error(c, 200, e, "")
|
||||
return
|
||||
}
|
||||
|
||||
if a.Logo != "" {
|
||||
if !strings.HasPrefix(a.Logo, "http") {
|
||||
a.Logo = fmt.Sprintf("http://%s/%s", c.Request.Host, a.Logo)
|
||||
}
|
||||
}
|
||||
|
||||
app.OK(c, a, "提交成功")
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package sys_config
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
// GetSysConfigByKEYForService 根据Key获取SysConfig的Service
|
||||
func (e *SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := e.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s", msgID, err)
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
var v dto.SysConfigControl
|
||||
err = c.Bind(&v)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
|
||||
app.Error(c, 422, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
s := service.SysConfig{}
|
||||
s.MsgID = msgID
|
||||
s.Orm = db
|
||||
err = s.GetSysConfigByKEY(&v)
|
||||
if err != nil {
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
app.OK(c, v, s.Msg)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package sys_login_log
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/models/system"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetSysLoginLogList(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
d := new(dto.SysLoginLogSearch)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
req := d.Generate()
|
||||
|
||||
//查询列表
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]system.SysLoginLog, 0)
|
||||
var count int64
|
||||
serviceStudent := service.SysLoginLog{}
|
||||
serviceStudent.MsgID = msgID
|
||||
serviceStudent.Orm = db
|
||||
err = serviceStudent.GetSysLoginLogPage(req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//查看详情
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object system.SysLoginLog
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
serviceSysLoginLog.Orm = db
|
||||
err = serviceSysLoginLog.GetSysLoginLog(req, &object)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object, "查看成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) InsertSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//新增操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
// 设置创建人
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.Orm = db
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
err = serviceSysLoginLog.InsertSysLoginLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(c, http.StatusInternalServerError, err, "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) UpdateSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
req := control.Generate()
|
||||
//更新操作
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.Orm = db
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
err = serviceSysLoginLog.UpdateSysLoginLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) DeleteSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//删除操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 设置编辑人
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.Orm = db
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
err = serviceSysLoginLog.RemoveSysLoginLog(req, object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package sys_opera_log
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetSysOperaLogList(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
d := new(dto.SysOperaLogSearch)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
req := d.Generate()
|
||||
|
||||
//查询列表
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]system.SysOperaLog, 0)
|
||||
var count int64
|
||||
serviceStudent := service.SysOperaLog{}
|
||||
serviceStudent.MsgID = msgID
|
||||
serviceStudent.Orm = db
|
||||
err = serviceStudent.GetSysOperaLogPage(req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//查看详情
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object system.SysOperaLog
|
||||
|
||||
serviceSysOperlog := service.SysOperaLog{}
|
||||
serviceSysOperlog.MsgID = msgID
|
||||
serviceSysOperlog.Orm = db
|
||||
err = serviceSysOperlog.GetSysOperaLog(req, &object)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object, "查看成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) InsertSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//新增操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
// 设置创建人
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysOperaLog := service.SysOperaLog{}
|
||||
serviceSysOperaLog.Orm = db
|
||||
serviceSysOperaLog.MsgID = msgID
|
||||
err = serviceSysOperaLog.InsertSysOperaLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(c, http.StatusInternalServerError, err, "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) UpdateSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
req := control.Generate()
|
||||
//更新操作
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysOperaLog := service.SysOperaLog{}
|
||||
serviceSysOperaLog.Orm = db
|
||||
serviceSysOperaLog.MsgID = msgID
|
||||
err = serviceSysOperaLog.UpdateSysOperaLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) DeleteSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//删除操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 设置编辑人
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysOperaLog := service.SysOperaLog{}
|
||||
serviceSysOperaLog.Orm = db
|
||||
serviceSysOperaLog.MsgID = msgID
|
||||
err = serviceSysOperaLog.RemoveSysOperaLog(req, object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "删除成功")
|
||||
}
|
||||
@@ -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"
|
||||
)
|
||||
@@ -26,12 +27,12 @@ func GetSysUserList(c *gin.Context) {
|
||||
|
||||
size := c.Request.FormValue("pageSize")
|
||||
if size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
index := c.Request.FormValue("pageIndex")
|
||||
if index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.Username = c.Request.FormValue("username")
|
||||
@@ -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
|
||||
@@ -23,11 +25,11 @@ func GetDBColumnList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools2.StrToInt(err, size)
|
||||
pageSize, err = tools2.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools2.StrToInt(err, index)
|
||||
pageIndex, err = tools2.StringToInt(index)
|
||||
}
|
||||
|
||||
data.TableName = c.Request.FormValue("tableName")
|
||||
@@ -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
|
||||
@@ -30,11 +32,11 @@ func GetDBTableList(c *gin.Context) {
|
||||
}
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools2.StrToInt(err, size)
|
||||
pageSize, err = tools2.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools2.StrToInt(err, index)
|
||||
pageIndex, err = tools2.StringToInt(index)
|
||||
}
|
||||
|
||||
data.TableName = c.Request.FormValue("tableName")
|
||||
@@ -2,15 +2,16 @@ 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"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/config"
|
||||
"net/http"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
func Preview(c *gin.Context) {
|
||||
@@ -18,15 +19,17 @@ func Preview(c *gin.Context) {
|
||||
id, err := tools2.StringToInt(c.Param("tableId"))
|
||||
tools2.HasError(err, "", -1)
|
||||
table.TableId = id
|
||||
t1, err := template.ParseFiles("template/model.go.template")
|
||||
t1, err := template.ParseFiles("template/v3/model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t2, err := template.ParseFiles("template/api.go.template")
|
||||
t2, err := template.ParseFiles("template/v3/no_actions/apis.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles("template/js.go.template")
|
||||
t3, err := template.ParseFiles("template/v3/js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/vue.go.template")
|
||||
t4, err := template.ParseFiles("template/v3/vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/router.go.template")
|
||||
t5, err := template.ParseFiles("template/v3/no_actions/router_check_role.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v3/dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
tab, _ := table.Get()
|
||||
var b1 bytes.Buffer
|
||||
@@ -39,6 +42,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,54 +51,59 @@ 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
|
||||
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
func GenCode(c *gin.Context) {
|
||||
func GenCodeV3(c *gin.Context) {
|
||||
table := tools.SysTables{}
|
||||
id, err := tools2.StringToInt(c.Param("tableId"))
|
||||
tools2.HasError(err, "", -1)
|
||||
table.TableId = id
|
||||
tab, _ := table.Get()
|
||||
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
|
||||
}
|
||||
if tab.IsActions == 1 {
|
||||
ActionsGenV3(tab)
|
||||
} else {
|
||||
NOActionsGenV3(tab)
|
||||
}
|
||||
|
||||
oldTest := "// {{认证路由自动补充在此处请勿删除}}"
|
||||
newText := "// {{认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1,authMiddleware)"
|
||||
app.OK(c, "", "Code generated successfully!")
|
||||
}
|
||||
|
||||
if !ischeckrole {
|
||||
oldTest = "// {{无需认证路由自动补充在此处请勿删除}}"
|
||||
newText = "// {{无需认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1)"
|
||||
routerfile = "template/routernocheckrole.go.template"
|
||||
func NOActionsGenV3(tab tools.SysTables) {
|
||||
|
||||
basePath := "template/v3/"
|
||||
routerFile := basePath + "no_actions/router_check_role.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerFile = basePath + "no_actions/router_no_check_role.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles("template/model.go.template")
|
||||
t1, err := template.ParseFiles(basePath + "model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t2, err := template.ParseFiles("template/api.go.template")
|
||||
t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerfile)
|
||||
t3, err := template.ParseFiles(routerFile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/js.go.template")
|
||||
t4, err := template.ParseFiles(basePath + "js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
t5, err := template.ParseFiles(basePath + "vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles(basePath + "dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t7, err := template.ParseFiles(basePath + "no_actions/service.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
|
||||
_ = tools2.PathCreate("./apis/" + tab.ModuleName + "/")
|
||||
_ = tools2.PathCreate("./models/")
|
||||
_ = tools2.PathCreate("./router/")
|
||||
_ = 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.PackageName)
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName)
|
||||
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
@@ -105,29 +115,61 @@ func GenCode(c *gin.Context) {
|
||||
err = t4.Execute(&b4, tab)
|
||||
var b5 bytes.Buffer
|
||||
err = t5.Execute(&b5, 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")
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
var b7 bytes.Buffer
|
||||
err = t7.Execute(&b7, tab)
|
||||
tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b2, "./app/"+tab.PackageName+"/apis/"+tab.ModuleName+"/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js")
|
||||
tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue")
|
||||
tools2.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b7, "./app/"+tab.PackageName+"/service/"+tab.BusinessName+".go")
|
||||
|
||||
helper := tools2.ReplaceHelper{
|
||||
Root: "./router/router.go",
|
||||
OldText: oldTest,
|
||||
NewText: newText,
|
||||
}
|
||||
if helper.OldText == helper.NewText {
|
||||
global.Logger.Println("error !! the NewText isEqual the OldText")
|
||||
return
|
||||
}
|
||||
if err := helper.DoWrok(); err != nil {
|
||||
global.Logger.Print("error:", err.Error())
|
||||
}
|
||||
|
||||
} else {
|
||||
global.Logger.Print("done!")
|
||||
func ActionsGenV3(tab tools.SysTables) {
|
||||
basePath := "template/v3/"
|
||||
routerFile := basePath + "actions/router_check_role.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerFile = basePath + "actions/router_no_check_role.go.template"
|
||||
}
|
||||
|
||||
app.OK(c, "", "Code generated successfully!")
|
||||
t1, err := template.ParseFiles(basePath + "model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerFile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles(basePath + "js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles(basePath + "vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles(basePath + "dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
|
||||
_ = tools2.PathCreate("./app/" + tab.PackageName + "/models/")
|
||||
_ = tools2.PathCreate("./app/" + tab.PackageName + "/router/")
|
||||
_ = tools2.PathCreate("./app/" + tab.PackageName + "/service/dto/")
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/api/")
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.BusinessName)
|
||||
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
var b3 bytes.Buffer
|
||||
err = t3.Execute(&b3, tab)
|
||||
var b4 bytes.Buffer
|
||||
err = t4.Execute(&b4, tab)
|
||||
var b5 bytes.Buffer
|
||||
err = t5.Execute(&b5, tab)
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
|
||||
tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js")
|
||||
tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue")
|
||||
tools2.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go")
|
||||
}
|
||||
|
||||
func GenMenuAndApi(c *gin.Context) {
|
||||
@@ -139,7 +181,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 +200,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 +220,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 +239,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 +258,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 +277,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 +315,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 +333,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 +351,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 +369,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 +387,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 工具 - 生成表
|
||||
@@ -112,9 +141,10 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
strStart := string([]byte(tablenamelist[i])[:1])
|
||||
strend := string([]byte(tablenamelist[i])[1:])
|
||||
data.ClassName += strings.ToUpper(strStart) + strend
|
||||
data.PackageName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
//data.PackageName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
data.ModuleName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
}
|
||||
data.PackageName = "admin"
|
||||
data.TplCategory = "crud"
|
||||
data.Crud = true
|
||||
|
||||
@@ -130,6 +160,9 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
data.IsLogicalDelete = "1"
|
||||
data.LogicalDelete = true
|
||||
data.LogicalDeleteColumn = "is_del"
|
||||
data.IsActions = 1
|
||||
data.IsDataScope = 1
|
||||
data.IsAuth = 1
|
||||
|
||||
data.FunctionAuthor = "wenjianzhang"
|
||||
for i := 0; i < len(dbcolumn); i++ {
|
||||
@@ -158,6 +191,8 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
column.IsPk = "1"
|
||||
column.Pk = true
|
||||
data.PkColumn = dbcolumn[i].ColumnName
|
||||
column.GoField = strings.ToUpper(column.GoField)
|
||||
column.JsonField = strings.ToUpper(column.JsonField)
|
||||
data.PkGoField = column.GoField
|
||||
data.PkJsonField = column.JsonField
|
||||
}
|
||||
@@ -169,7 +204,9 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
|
||||
if strings.Contains(dbcolumn[i].ColumnType, "int") {
|
||||
if strings.Contains(dbcolumn[i].ColumnKey, "PR") {
|
||||
column.GoType = "int"
|
||||
column.GoType = "uint"
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "unsigned") {
|
||||
column.GoType = "uint"
|
||||
} else {
|
||||
column.GoType = "string"
|
||||
}
|
||||
@@ -177,6 +214,9 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "timestamp") {
|
||||
column.GoType = "time.Time"
|
||||
column.HtmlType = "datetime"
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "datetime") {
|
||||
column.GoType = "time.Time"
|
||||
column.HtmlType = "datetime"
|
||||
} else {
|
||||
column.GoType = "string"
|
||||
column.HtmlType = "input"
|
||||
@@ -200,7 +240,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,17 +1,27 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"go-admin/handler"
|
||||
"time"
|
||||
|
||||
"go-admin/app/admin/middleware/handler"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools/config"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AuthInit jwt验证new
|
||||
func AuthInit() (*jwt.GinJWTMiddleware, error) {
|
||||
timeout := time.Hour
|
||||
if config.ApplicationConfig.Mode == "dev" {
|
||||
timeout = time.Duration(876010) * time.Hour
|
||||
} else {
|
||||
if config.JwtConfig.Timeout != 0 {
|
||||
timeout = time.Duration(config.JwtConfig.Timeout) * time.Second
|
||||
}
|
||||
}
|
||||
return jwt.New(&jwt.GinJWTMiddleware{
|
||||
Realm: "test zone",
|
||||
Key: []byte(config.ApplicationConfig.JwtSecret),
|
||||
Timeout: time.Hour,
|
||||
Timeout: timeout,
|
||||
MaxRefresh: time.Hour,
|
||||
PayloadFunc: handler.PayloadFunc,
|
||||
IdentityHandler: handler.IdentityHandler,
|
||||
@@ -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) {
|
||||
@@ -26,7 +27,7 @@ func CustomError(c *gin.Context) {
|
||||
}
|
||||
c.Status(statusCode)
|
||||
fmt.Println(
|
||||
time.Now().Format("2006-01-02 15:04:05.9999"),
|
||||
time.Now().Format("2006-01-02 15:04:05"),
|
||||
"[ERROR]",
|
||||
c.Request.Method,
|
||||
c.Request.URL,
|
||||
@@ -0,0 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"go-admin/common/config"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/middleware"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
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)
|
||||
case "sqlite3":
|
||||
return gorm.Open(sqlite.Open(global.Source), 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,20 @@
|
||||
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/app/admin/models/system"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var store = base64Captcha.DefaultMemStore
|
||||
@@ -88,29 +93,36 @@ func Authenticator(c *gin.Context) (interface{}, error) {
|
||||
msg = "登录失败"
|
||||
status = "1"
|
||||
LoginLogToDB(c, status, msg, username)
|
||||
global.RequestLogger.Println(e.Error())
|
||||
global.RequestLogger.Error(e)
|
||||
}
|
||||
return nil, jwt.ErrFailedAuthentication
|
||||
}
|
||||
|
||||
// Write log to database
|
||||
// LoginLogToDB Write log to database
|
||||
func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
|
||||
if config.LoggerConfig.EnabledDB {
|
||||
var loginlog models.LoginLog
|
||||
var loginLog system.SysLoginLog
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 获取Orm失败, error:%s", msgID, err)
|
||||
}
|
||||
ua := user_agent.New(c.Request.UserAgent())
|
||||
loginlog.Ipaddr = c.ClientIP()
|
||||
loginlog.Username = username
|
||||
loginLog.Ipaddr = c.ClientIP()
|
||||
loginLog.Username = username
|
||||
location := tools.GetLocation(c.ClientIP())
|
||||
loginlog.LoginLocation = location
|
||||
loginlog.LoginTime = tools.GetCurrentTime()
|
||||
loginlog.Status = status
|
||||
loginlog.Remark = c.Request.UserAgent()
|
||||
loginLog.LoginLocation = location
|
||||
loginLog.LoginTime = tools.GetCurrentTime()
|
||||
loginLog.Status = status
|
||||
loginLog.Remark = c.Request.UserAgent()
|
||||
browserName, browserVersion := ua.Browser()
|
||||
loginlog.Browser = browserName + " " + browserVersion
|
||||
loginlog.Os = ua.OS()
|
||||
loginlog.Msg = msg
|
||||
loginlog.Platform = ua.Platform()
|
||||
_, _ = loginlog.Create()
|
||||
loginLog.Browser = browserName + " " + browserVersion
|
||||
loginLog.Os = ua.OS()
|
||||
loginLog.Msg = msg
|
||||
loginLog.Platform = ua.Platform()
|
||||
serviceLoginLog := service.SysLoginLog{}
|
||||
serviceLoginLog.Orm = db
|
||||
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,21 +136,28 @@ func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
|
||||
// @Router /logout [post]
|
||||
// @Security Bearer
|
||||
func LogOut(c *gin.Context) {
|
||||
var loginlog models.LoginLog
|
||||
var loginLog system.SysLoginLog
|
||||
ua := user_agent.New(c.Request.UserAgent())
|
||||
loginlog.Ipaddr = c.ClientIP()
|
||||
loginLog.Ipaddr = c.ClientIP()
|
||||
location := tools.GetLocation(c.ClientIP())
|
||||
loginlog.LoginLocation = location
|
||||
loginlog.LoginTime = tools.GetCurrentTime()
|
||||
loginlog.Status = "0"
|
||||
loginlog.Remark = c.Request.UserAgent()
|
||||
loginLog.LoginLocation = location
|
||||
loginLog.LoginTime = tools.GetCurrentTime()
|
||||
loginLog.Status = "0"
|
||||
loginLog.Remark = c.Request.UserAgent()
|
||||
browserName, browserVersion := ua.Browser()
|
||||
loginlog.Browser = browserName + " " + browserVersion
|
||||
loginlog.Os = ua.OS()
|
||||
loginlog.Platform = ua.Platform()
|
||||
loginlog.Username = tools.GetUserName(c)
|
||||
loginlog.Msg = "退出成功"
|
||||
loginlog.Create()
|
||||
loginLog.Browser = browserName + " " + browserVersion
|
||||
loginLog.Os = ua.OS()
|
||||
loginLog.Platform = ua.Platform()
|
||||
loginLog.Username = tools.GetUserName(c)
|
||||
loginLog.Msg = "退出成功"
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 获取Orm失败, error:%s", msgID, err)
|
||||
}
|
||||
serviceLoginLog := service.SysLoginLog{}
|
||||
serviceLoginLog.Orm = db
|
||||
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 200,
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/unrolled/secure"
|
||||
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
@@ -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,9 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
|
||||
func InitMiddleware(r *gin.Engine) {
|
||||
// 日志处理
|
||||
r.Use(LoggerToFile())
|
||||
@@ -17,6 +16,6 @@ func InitMiddleware(r *gin.Engine) {
|
||||
r.Use(Options)
|
||||
// Secure is a middleware function that appends security
|
||||
r.Use(Secure)
|
||||
// Set X-Request-Id header
|
||||
r.Use(RequestId())
|
||||
}
|
||||
// 链路追踪
|
||||
r.Use(middleware.Trace())
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
// LoggerToFile 日志记录到文件
|
||||
func LoggerToFile() gin.HandlerFunc {
|
||||
|
||||
return func(c *gin.Context) {
|
||||
// 开始时间
|
||||
startTime := time.Now()
|
||||
|
||||
// 处理请求
|
||||
c.Next()
|
||||
|
||||
// 结束时间
|
||||
endTime := time.Now()
|
||||
|
||||
// 执行时间
|
||||
latencyTime := endTime.Sub(startTime)
|
||||
|
||||
// 请求方式
|
||||
reqMethod := c.Request.Method
|
||||
|
||||
// 请求路由
|
||||
reqUri := c.Request.RequestURI
|
||||
|
||||
// 状态码
|
||||
statusCode := c.Writer.Status()
|
||||
|
||||
// 请求IP
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
// 日志格式
|
||||
logData := map[string]interface{}{
|
||||
"statusCode": statusCode,
|
||||
"latencyTime": latencyTime,
|
||||
"clientIP": clientIP,
|
||||
"method": reqMethod,
|
||||
"uri": reqUri,
|
||||
}
|
||||
log.Info(logData)
|
||||
global.RequestLogger.Info(logData)
|
||||
|
||||
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" && config.LoggerConfig.EnabledDB {
|
||||
SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用
|
||||
func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration) {
|
||||
menu := models.Menu{}
|
||||
menu.Path = reqUri
|
||||
menu.Action = reqMethod
|
||||
menuList, _ := menu.Get()
|
||||
sysOperaLog := system.SysOperaLog{}
|
||||
sysOperaLog.OperIp = clientIP
|
||||
sysOperaLog.OperLocation = tools.GetLocation(clientIP)
|
||||
sysOperaLog.Status = tools.IntToString(statusCode)
|
||||
sysOperaLog.OperName = tools.GetUserName(c)
|
||||
sysOperaLog.RequestMethod = c.Request.Method
|
||||
sysOperaLog.OperUrl = reqUri
|
||||
if reqUri == "/login" {
|
||||
sysOperaLog.BusinessType = "10"
|
||||
sysOperaLog.Title = "用户登录"
|
||||
sysOperaLog.OperName = "-"
|
||||
} else if strings.Contains(reqUri, "/api/v1/logout") {
|
||||
sysOperaLog.BusinessType = "11"
|
||||
} else if strings.Contains(reqUri, "/api/v1/getCaptcha") {
|
||||
sysOperaLog.BusinessType = "12"
|
||||
sysOperaLog.Title = "验证码"
|
||||
} else {
|
||||
if reqMethod == "POST" {
|
||||
sysOperaLog.BusinessType = "1"
|
||||
} else if reqMethod == "PUT" {
|
||||
sysOperaLog.BusinessType = "2"
|
||||
} else if reqMethod == "DELETE" {
|
||||
sysOperaLog.BusinessType = "3"
|
||||
}
|
||||
}
|
||||
sysOperaLog.Method = reqMethod
|
||||
if len(menuList) > 0 {
|
||||
sysOperaLog.Title = menuList[0].Title
|
||||
}
|
||||
b, _ := c.Get("body")
|
||||
sysOperaLog.OperParam, _ = tools.StructToJsonStr(b)
|
||||
sysOperaLog.CreateBy = tools.GetUserIdUint(c)
|
||||
sysOperaLog.OperTime = tools.GetCurrentTime()
|
||||
sysOperaLog.LatencyTime = (latencyTime).String()
|
||||
sysOperaLog.UserAgent = c.Request.UserAgent()
|
||||
if c.Err() == nil {
|
||||
sysOperaLog.Status = "0"
|
||||
} else {
|
||||
sysOperaLog.Status = "1"
|
||||
}
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 获取Orm失败, error:%s", msgID, err)
|
||||
}
|
||||
serviceOperaLog := service.SysOperaLog{}
|
||||
serviceOperaLog.Orm = db
|
||||
_ = serviceOperaLog.InsertSysOperaLog(sysOperaLog.Generate())
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
//权限检查中间件
|
||||
func AuthCheckRole() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
data, _ := c.Get(jwtauth.JwtPayloadKey)
|
||||
v := data.(jwtauth.MapClaims)
|
||||
e := global.CasbinEnforcer
|
||||
var res bool
|
||||
var err error
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//检查权限
|
||||
if v["rolekey"] == "admin" {
|
||||
res = true
|
||||
log.Infof("msgID[%s] info:%s method:%s path:%s", msgID, v["rolekey"], c.Request.Method, c.Request.URL.Path)
|
||||
} else {
|
||||
res, err = e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s method:%s path:%s", msgID, err, c.Request.Method, c.Request.URL.Path)
|
||||
app.Error(c, 500, err, "")
|
||||
}
|
||||
}
|
||||
|
||||
if res {
|
||||
c.Next()
|
||||
} else {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 403,
|
||||
"msg": "对不起,您没有该接口访问权限,请联系管理员",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package models
|
||||
|
||||
//casbin_rule
|
||||
//sys_casbin_rule
|
||||
type CasbinRule struct {
|
||||
PType string `json:"p_type" gorm:"size:100;"`
|
||||
V0 string `json:"v0" gorm:"size:100;"`
|
||||
@@ -12,5 +12,5 @@ type CasbinRule struct {
|
||||
}
|
||||
|
||||
func (CasbinRule) TableName() string {
|
||||
return "casbin_rule"
|
||||
return "sys_casbin_rule"
|
||||
}
|
||||
@@ -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,27 +2,29 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
"go-admin/tools"
|
||||
_ "time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysDept struct {
|
||||
DeptId int `json:"deptId" gorm:"primary_key;AUTO_INCREMENT"` //部门编码
|
||||
ParentId int `json:"parentId" gorm:""` //上级部门
|
||||
DeptPath string `json:"deptPath" gorm:"size:255;"` //
|
||||
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Leader string `json:"leader" gorm:"size:128;"` //负责人
|
||||
Phone string `json:"phone" gorm:"size:11;"` //手机
|
||||
Email string `json:"email" gorm:"size:64;"` //邮箱
|
||||
Status string `json:"status" gorm:"size:4;"` //状态
|
||||
DeptId int `json:"deptId" gorm:"primary_key;auto_increment;"` //部门编码
|
||||
ParentId int `json:"parentId" gorm:""` //上级部门
|
||||
DeptPath string `json:"deptPath" gorm:"size:255;"` //
|
||||
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Leader string `json:"leader" gorm:"size:128;"` //负责人
|
||||
Phone string `json:"phone" gorm:"size:11;"` //手机
|
||||
Email string `json:"email" gorm:"size:64;"` //邮箱
|
||||
Status string `json:"status" gorm:"size:4;"` //状态
|
||||
CreateBy string `json:"createBy" gorm:"size:64;"`
|
||||
UpdateBy string `json:"updateBy" gorm:"size:64;"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
Children []SysDept `json:"children" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysDept) TableName() string {
|
||||
@@ -52,7 +54,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 +103,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,27 +2,29 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type DictData struct {
|
||||
DictCode int `gorm:"primary_key;AUTO_INCREMENT" json:"dictCode" example:"1"` //字典编码
|
||||
DictSort int `gorm:"" json:"dictSort"` //显示顺序
|
||||
DictLabel string `gorm:"size:128;" json:"dictLabel"` //数据标签
|
||||
DictValue string `gorm:"size:255;" json:"dictValue"` //数据键值
|
||||
DictType string `gorm:"size:64;" json:"dictType"` //字典类型
|
||||
CssClass string `gorm:"size:128;" json:"cssClass"` //
|
||||
ListClass string `gorm:"size:128;" json:"listClass"` //
|
||||
IsDefault string `gorm:"size:8;" json:"isDefault"` //
|
||||
Status string `gorm:"size:4;" json:"status"` //状态
|
||||
Default string `gorm:"size:8;" json:"default"` //
|
||||
CreateBy string `gorm:"size:64;" json:"createBy"` //
|
||||
UpdateBy string `gorm:"size:64;" json:"updateBy"` //
|
||||
Remark string `gorm:"size:255;" json:"remark"` //备注
|
||||
DictCode int `gorm:"primary_key;auto_increment;" json:"dictCode" example:"1"` //字典编码
|
||||
DictSort int `gorm:"" json:"dictSort"` //显示顺序
|
||||
DictLabel string `gorm:"size:128;" json:"dictLabel"` //数据标签
|
||||
DictValue string `gorm:"size:255;" json:"dictValue"` //数据键值
|
||||
DictType string `gorm:"size:64;" json:"dictType"` //字典类型
|
||||
CssClass string `gorm:"size:128;" json:"cssClass"` //
|
||||
ListClass string `gorm:"size:128;" json:"listClass"` //
|
||||
IsDefault string `gorm:"size:8;" json:"isDefault"` //
|
||||
Status string `gorm:"size:4;" json:"status"` //状态
|
||||
Default string `gorm:"size:8;" json:"default"` //
|
||||
CreateBy string `gorm:"size:64;" json:"createBy"` //
|
||||
UpdateBy string `gorm:"size:64;" json:"updateBy"` //
|
||||
Remark string `gorm:"size:255;" json:"remark"` //备注
|
||||
BaseModel
|
||||
|
||||
Params string `gorm:"-" json:"params"`
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (DictData) TableName() string {
|
||||
@@ -32,8 +34,13 @@ 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_type = ?", e.DictType).
|
||||
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 +97,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 +118,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,21 +2,25 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type DictType struct {
|
||||
DictId int `gorm:"primary_key;AUTO_INCREMENT" json:"dictId"`
|
||||
DictId int `gorm:"primary_key;auto_increment;" json:"dictId"`
|
||||
DictName string `gorm:"size:128;" json:"dictName"` //字典名称
|
||||
DictType string `gorm:"size:128;" json:"dictType"` //字典类型
|
||||
Status string `gorm:"size:4;" json:"status"` //状态
|
||||
DataScope string `gorm:"-" json:"dataScope"` //
|
||||
Params string `gorm:"-" json:"params"` //
|
||||
CreateBy string `gorm:"size:11;" json:"createBy"` //创建者
|
||||
UpdateBy string `gorm:"size:11;" json:"updateBy"` //更新者
|
||||
Remark string `gorm:"size:255;" json:"remark"` //备注
|
||||
BaseModel
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"` //
|
||||
Params string `gorm:"-" json:"params"` //
|
||||
}
|
||||
|
||||
func (DictType) TableName() string {
|
||||
@@ -26,7 +30,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 +87,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 +104,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,177 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysFileDir struct {
|
||||
Id int `json:"id"`
|
||||
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:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
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("sys_casbin_rule").Create(list)
|
||||
}
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -2,7 +2,9 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
orm "go-admin/global"
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -44,7 +46,7 @@ type MenuLable struct {
|
||||
}
|
||||
|
||||
type Menus struct {
|
||||
MenuId int `json:"menuId" gorm:"column:menu_id;primary_key"`
|
||||
MenuId int `json:"menuId" gorm:"column:menu_id;primary_key;"`
|
||||
MenuName string `json:"menuName" gorm:"column:menu_name"`
|
||||
Title string `json:"title" gorm:"column:title"`
|
||||
Icon string `json:"icon" gorm:"column:icon"`
|
||||
@@ -144,10 +146,10 @@ func DiguiMenu(menulist *[]Menu, menu Menu) Menu {
|
||||
return menu
|
||||
}
|
||||
|
||||
func (e *Menu) SetMenuLable() (m []MenuLable, err error) {
|
||||
func (e *Menu) SetMenuLable() (m *[]MenuLable, err error) {
|
||||
menulist, err := e.Get()
|
||||
|
||||
m = make([]MenuLable, 0)
|
||||
ml := make([]MenuLable, 0)
|
||||
for i := 0; i < len(menulist); i++ {
|
||||
if menulist[i].ParentId != 0 {
|
||||
continue
|
||||
@@ -157,9 +159,9 @@ func (e *Menu) SetMenuLable() (m []MenuLable, err error) {
|
||||
e.Label = menulist[i].Title
|
||||
menusInfo := DiguiMenuLable(&menulist, e)
|
||||
|
||||
m = append(m, menusInfo)
|
||||
ml = append(ml, menusInfo)
|
||||
}
|
||||
return
|
||||
return &ml, err
|
||||
}
|
||||
|
||||
func DiguiMenuLable(menulist *[]Menu, menu MenuLable) MenuLable {
|
||||
@@ -215,8 +217,14 @@ func (e *MenuRole) Get() (Menus []MenuRole, err error) {
|
||||
}
|
||||
|
||||
func (e *Menu) GetByRoleName(rolename string) (Menus []Menu, err error) {
|
||||
table := orm.Eloquent.Table(e.TableName()).Select("sys_menu.*").Joins("left join sys_role_menu on sys_role_menu.menu_id=sys_menu.menu_id")
|
||||
table = table.Where("sys_role_menu.role_name=? and menu_type in ('M','C')", rolename)
|
||||
var table *gorm.DB
|
||||
if rolename == "admin" {
|
||||
table = orm.Eloquent.Table(e.TableName()).Select("sys_menu.*")
|
||||
table = table.Where(" menu_type in ('M','C')")
|
||||
} else {
|
||||
table = orm.Eloquent.Table(e.TableName()).Select("sys_menu.*").Joins("left join sys_role_menu on sys_role_menu.menu_id=sys_menu.menu_id")
|
||||
table = table.Where("sys_role_menu.role_name=? and menu_type in ('M','C')", rolename)
|
||||
}
|
||||
if err = table.Order("sort").Find(&Menus).Error; err != nil {
|
||||
return
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/global"
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -14,9 +14,10 @@ type Post struct {
|
||||
Remark string `gorm:"size:255;" json:"remark"` //描述
|
||||
CreateBy string `gorm:"size:128;" json:"createBy"`
|
||||
UpdateBy string `gorm:"size:128;" json:"updateBy"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
Params string `gorm:"-" json:"params"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (Post) TableName() string {
|
||||
@@ -83,7 +84,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 +105,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) {
|
||||
@@ -1,8 +1,11 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
orm "go-admin/global"
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
@@ -18,10 +21,11 @@ type SysRole struct {
|
||||
Remark string `json:"remark" gorm:"size:255;"` //备注
|
||||
Admin bool `json:"admin" gorm:"size:4;"`
|
||||
DataScope string `json:"dataScope" gorm:"size:128;"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
MenuIds []int `json:"menuIds" gorm:"-"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
BaseModel
|
||||
|
||||
Params string `json:"params" gorm:"-"`
|
||||
MenuIds []int `json:"menuIds" gorm:"-"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
}
|
||||
|
||||
func (SysRole) TableName() string {
|
||||
@@ -32,10 +36,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 +64,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 +118,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 +175,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("sys_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"
|
||||
)
|
||||
|
||||
@@ -89,7 +90,7 @@ func (rm *RoleMenu) DeleteRoleMenu(roleId int) (bool, error) {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
sql3 := "delete from casbin_rule where v0= '" + role.RoleKey + "';"
|
||||
sql3 := "delete from sys_casbin_rule where v0= '" + role.RoleKey + "';"
|
||||
if err := tx.Exec(sql3).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
@@ -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() {
|
||||
@@ -125,7 +127,7 @@ func (rm *RoleMenu) BatchDeleteRoleMenu(roleIds []int) (bool, error) {
|
||||
}
|
||||
sql := ""
|
||||
for i := 0; i < len(role); i++ {
|
||||
sql += "delete from casbin_rule where v0= '" + role[i].RoleName + "';"
|
||||
sql += "delete from sys_casbin_rule where v0= '" + role[i].RoleName + "';"
|
||||
}
|
||||
if err := tx.Exec(sql).Error; err != nil {
|
||||
tx.Rollback()
|
||||
@@ -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 `sys_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
|
||||
|
||||
// 拼装'sys_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 += ","
|
||||
}
|
||||
}
|
||||
// 执行批量插入sys_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,31 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysCategory struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
|
||||
Name string `json:"name" gorm:"type:varchar(255);comment:名称"` //
|
||||
Img string `json:"img" gorm:"type:varchar(255);comment:图标"` //
|
||||
Sort string `json:"sort" gorm:"type:int(4);comment:排序"` //
|
||||
Status string `json:"status" gorm:"type:int(1);comment:状态"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
|
||||
}
|
||||
|
||||
func (SysCategory) TableName() string {
|
||||
return "sys_category"
|
||||
}
|
||||
|
||||
func (e *SysCategory) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysCategory) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -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"` // 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,113 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"go-admin/common/dto"
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type SysJob struct {
|
||||
JobId uint `json:"jobId" gorm:"primary_key;AUTO_INCREMENT"` // 编码
|
||||
JobName string `json:"jobName" gorm:"size:255;"` // 名称
|
||||
JobGroup string `json:"jobGroup" gorm:"size:255;"` // 任务分组
|
||||
JobType int `json:"jobType" gorm:"size:1;"` // 任务类型
|
||||
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;"` //
|
||||
BaseModel
|
||||
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
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);"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysSetting) TableName() string {
|
||||
return "sys_setting"
|
||||
}
|
||||
|
||||
//查询
|
||||
func (s *SysSetting) Get() (create SysSetting, err error) {
|
||||
result := orm.Eloquent.Table("sys_setting").First(&create)
|
||||
if result.Error != nil {
|
||||
err = result.Error
|
||||
return
|
||||
}
|
||||
return create, nil
|
||||
}
|
||||
|
||||
//修改
|
||||
func (s *SysSetting) Update() (update SysSetting, err error) {
|
||||
if err = orm.Eloquent.Table("sys_setting").Model(&update).Updates(&s).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ResponseSystemConfig struct {
|
||||
Name string `json:"name" binding:"required"` // 名称
|
||||
Logo string `json:"logo" binding:"required"` // 头像
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
ConfigName string `json:"configName" gorm:"type:varchar(128);comment:ConfigName"` //
|
||||
ConfigKey string `json:"configKey" gorm:"type:varchar(128);comment:ConfigKey"` //
|
||||
ConfigValue string `json:"configValue" gorm:"type:varchar(255);comment:ConfigValue"` //
|
||||
ConfigType string `json:"configType" gorm:"type:varchar(64);comment:ConfigType"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(128);comment:Remark"` //
|
||||
}
|
||||
|
||||
func (SysConfig) TableName() string {
|
||||
return "sys_config"
|
||||
}
|
||||
|
||||
func (e *SysConfig) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysConfig) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
|
||||
Username string `json:"username" gorm:"type:varchar(128);comment:用户名"` //
|
||||
Status string `json:"status" gorm:"type:varchar(4);comment:状态"` //
|
||||
Ipaddr string `json:"ipaddr" gorm:"type:varchar(255);comment:ip地址"` //
|
||||
LoginLocation string `json:"loginLocation" gorm:"type:varchar(255);comment:归属地"` //
|
||||
Browser string `json:"browser" gorm:"type:varchar(255);comment:浏览器"` //
|
||||
Os string `json:"os" gorm:"type:varchar(255);comment:系统"` //
|
||||
Platform string `json:"platform" gorm:"type:varchar(255);comment:固件"` //
|
||||
LoginTime time.Time `json:"loginTime" gorm:"type:timestamp;comment:登录时间"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
|
||||
Msg string `json:"msg" gorm:"type:varchar(255);comment:信息"` //
|
||||
}
|
||||
|
||||
func (SysLoginLog) TableName() string {
|
||||
return "sys_login_log"
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
|
||||
Title string `json:"title" gorm:"type:varchar(255);comment:操作模块"` //
|
||||
BusinessType string `json:"businessType" gorm:"type:varchar(128);comment:操作类型"` //
|
||||
BusinessTypes string `json:"businessTypes" gorm:"type:varchar(128);comment:BusinessTypes"` //
|
||||
Method string `json:"method" gorm:"type:varchar(128);comment:函数"` //
|
||||
RequestMethod string `json:"requestMethod" gorm:"type:varchar(128);comment:请求方式"` //
|
||||
OperatorType string `json:"operatorType" gorm:"type:varchar(128);comment:操作类型"` //
|
||||
OperName string `json:"operName" gorm:"type:varchar(128);comment:操作者"` //
|
||||
DeptName string `json:"deptName" gorm:"type:varchar(128);comment:部门名称"` //
|
||||
OperUrl string `json:"operUrl" gorm:"type:varchar(255);comment:访问地址"` //
|
||||
OperIp string `json:"operIp" gorm:"type:varchar(128);comment:客户端ip"` //
|
||||
OperLocation string `json:"operLocation" gorm:"type:varchar(128);comment:访问位置"` //
|
||||
OperParam string `json:"operParam" gorm:"type:varchar(255);comment:请求参数"` //
|
||||
Status string `json:"status" gorm:"type:varchar(4);comment:操作状态"` //
|
||||
OperTime time.Time `json:"operTime" gorm:"type:timestamp;comment:操作时间"` //
|
||||
JsonResult string `json:"jsonResult" gorm:"type:varchar(255);comment:返回数据"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
|
||||
LatencyTime string `json:"latencyTime" gorm:"type:varchar(128);comment:耗时"` //
|
||||
UserAgent string `json:"userAgent" gorm:"type:varchar(255);comment:ua"` //
|
||||
}
|
||||
|
||||
func (SysOperaLog) TableName() string {
|
||||
return "sys_opera_log"
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -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
|
||||
@@ -53,16 +56,16 @@ type SysUserB struct {
|
||||
UpdateBy string `gorm:"size:128" json:"updateBy"` //
|
||||
Remark string `gorm:"size:255" json:"remark"` //备注
|
||||
Status string `gorm:"size:4;" json:"status"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
Params string `gorm:"-" json:"params"`
|
||||
|
||||
BaseModel
|
||||
}
|
||||
|
||||
type SysUser struct {
|
||||
SysUserId
|
||||
SysUserB
|
||||
LoginM
|
||||
SysUserB
|
||||
}
|
||||
|
||||
func (SysUser) TableName() string {
|
||||
@@ -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 = table.Where("TABLE_NAME not in (select table_name from " + config2.GenConfig.DBName + ".sys_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,71 @@ 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
|
||||
}
|
||||
|
||||
tableNames := make([]string, 0)
|
||||
for i := range e.Columns {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
tableNames = append(tableNames, e.Columns[i].FkTableName)
|
||||
}
|
||||
}
|
||||
|
||||
tables := make([]SysTables, 0)
|
||||
tableMap := make(map[string]*SysTables)
|
||||
if len(tableNames) > 0 {
|
||||
if err = orm.Eloquent.Table("sys_tables").Where("table_name in (?)", tableNames).Find(&tables).Error; err != nil {
|
||||
return
|
||||
}
|
||||
for i := range tables {
|
||||
tableMap[tables[i].TBName] = &tables[i]
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < len(e.Columns); i++ {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
t, ok := tableMap[e.Columns[i].FkTableName]
|
||||
if ok {
|
||||
e.Columns[i].FkTableNameClass = t.ClassName
|
||||
e.Columns[i].FkTableNamePackage = t.ModuleName
|
||||
} else {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/middleware/handler"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/middleware"
|
||||
_ "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func InitRouter() {
|
||||
var r *gin.Engine
|
||||
h := global.Cfg.GetEngine()
|
||||
if h == nil {
|
||||
h = gin.New()
|
||||
global.Cfg.SetEngine(h)
|
||||
}
|
||||
switch h.(type) {
|
||||
case *gin.Engine:
|
||||
r = h.(*gin.Engine)
|
||||
default:
|
||||
log.Fatal("not support other engine")
|
||||
os.Exit(-1)
|
||||
}
|
||||
if config.SslConfig.Enable {
|
||||
r.Use(handler.TlsHandler())
|
||||
}
|
||||
r.Use(middleware.WithContextDb(middleware.GetGormFromConfig(global.Cfg)))
|
||||
|
||||
r.Use(common.Sentinel())
|
||||
middleware.InitMiddleware(r)
|
||||
// the jwt middleware
|
||||
var err error
|
||||
authMiddleware, err := middleware.AuthInit()
|
||||
tools.HasError(err, "JWT Init Error", 500)
|
||||
|
||||
// 注册系统路由
|
||||
InitSysRouter(r, authMiddleware)
|
||||
|
||||
// 注册业务路由
|
||||
// TODO: 这里可存放业务路由,里边并无实际路由只有演示代码
|
||||
InitExamplesRouter(r, authMiddleware)
|
||||
|
||||
//return r
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/transfer"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Monitor() {
|
||||
var r *gin.Engine
|
||||
h := global.Cfg.GetEngine()
|
||||
if h == nil {
|
||||
h = gin.New()
|
||||
global.Cfg.SetEngine(h)
|
||||
}
|
||||
switch h.(type) {
|
||||
case *gin.Engine:
|
||||
r = h.(*gin.Engine)
|
||||
default:
|
||||
log.Fatal("not support other engine")
|
||||
}
|
||||
//开发环境启动监控指标
|
||||
r.GET("/metrics", transfer.Handler(promhttp.Handler()))
|
||||
//健康检查
|
||||
r.GET("/health", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
}
|
||||
@@ -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,10 @@ func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddle
|
||||
// 空接口防止v1定义无使用报错
|
||||
v1.GET("/checkrole", nil)
|
||||
|
||||
for _, f := range routerCheckRole {
|
||||
f(v1, authMiddleware)
|
||||
}
|
||||
|
||||
// {{认证路由自动补充在此处请勿删除}}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysCategoryRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
model := &models.SysCategory{}
|
||||
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysCategorySearch), func() interface{} {
|
||||
list := make([]models.SysCategory, 0)
|
||||
return &list
|
||||
}))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysCategoryById), nil))
|
||||
r.POST("", actions.CreateAction(new(dto.SysCategoryControl)))
|
||||
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysCategoryControl)))
|
||||
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysCategoryById)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/system/sys_config"
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysConfigRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
model := &system.SysConfig{}
|
||||
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysConfigSearch), func() interface{} {
|
||||
list := make([]system.SysConfig, 0)
|
||||
return &list
|
||||
}))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysConfigById), nil))
|
||||
r.POST("", actions.CreateAction(new(dto.SysConfigControl)))
|
||||
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysConfigControl)))
|
||||
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysConfigById)))
|
||||
}
|
||||
|
||||
r1 := v1.Group("/configKey").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
model := &sys_config.SysConfig{}
|
||||
r1.POST("", model.GetSysConfigByKEYForService)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/system/sys_login_log"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysLoginLogRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := &sys_login_log.SysLoginLog{}
|
||||
r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetSysLoginLogList)
|
||||
r.GET("/:id", api.GetSysLoginLog)
|
||||
r.POST("", api.InsertSysLoginLog)
|
||||
r.PUT("/:id", api.UpdateSysLoginLog)
|
||||
r.DELETE("", api.DeleteSysLoginLog)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/system/sys_opera_log"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysOperaLogRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysOperaLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := &sys_opera_log.SysOperaLog{}
|
||||
r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetSysOperaLogList)
|
||||
r.GET("/:id", api.GetSysOperaLog)
|
||||
r.POST("", api.InsertSysOperaLog)
|
||||
r.PUT("/:id", api.UpdateSysOperaLog)
|
||||
r.DELETE("", api.DeleteSysOperaLog)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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 init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysContentRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
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,38 @@
|
||||
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), func() interface{} {
|
||||
return &dto.SysJobItem{}
|
||||
}))
|
||||
r.POST("", actions.CreateAction(new(dto.SysJobControl)))
|
||||
r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto.SysJobControl)))
|
||||
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysJobById)))
|
||||
}
|
||||
sysJob := &sysjob.SysJob{}
|
||||
|
||||
v1.GET("/job/remove/:id", sysJob.RemoveJobForService)
|
||||
v1.GET("/job/start/:id", sysJob.StartJobForService)
|
||||
}
|
||||
@@ -1,18 +1,22 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"mime"
|
||||
|
||||
"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/system"
|
||||
"go-admin/apis/system/dict"
|
||||
. "go-admin/apis/tools"
|
||||
_ "go-admin/docs"
|
||||
"go-admin/handler"
|
||||
"go-admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
|
||||
@@ -20,24 +24,27 @@ func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Rou
|
||||
sysBaseRouter(g)
|
||||
// 静态文件
|
||||
sysStaticFileRouter(g)
|
||||
|
||||
// swagger;注意:生产环境可以注释掉
|
||||
sysSwaggerRouter(g)
|
||||
|
||||
// 无需认证
|
||||
sysNoCheckRoleRouter(g)
|
||||
// 需要认证
|
||||
sysCheckRoleRouterInit(g, authMiddleware)
|
||||
|
||||
return g
|
||||
}
|
||||
|
||||
func sysBaseRouter(r *gin.RouterGroup) {
|
||||
|
||||
go ws.WebsocketManager.Start()
|
||||
go ws.WebsocketManager.SendService()
|
||||
go ws.WebsocketManager.SendAllService()
|
||||
|
||||
r.GET("/", system.HelloWorld)
|
||||
r.GET("/info", handler.Ping)
|
||||
}
|
||||
|
||||
func sysStaticFileRouter(r *gin.RouterGroup) {
|
||||
mime.AddExtensionType(".js", "application/javascript")
|
||||
r.Static("/static", "./static")
|
||||
r.Static("/form-generator", "./static/form-generator")
|
||||
}
|
||||
@@ -52,15 +59,16 @@ 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", GenCodeV3)
|
||||
v1.GET("/gen/todb/:tableId", GenMenuAndApi)
|
||||
v1.GET("/gen/tabletree", GetSysTablesTree)
|
||||
v1.GET("/menuTreeselect", system.GetMenuTreeelect)
|
||||
v1.GET("/dict/databytype/:dictType", dict.GetDictDataByDictType)
|
||||
|
||||
registerDBRouter(v1)
|
||||
|
||||
registerSysTableRouter(v1)
|
||||
|
||||
registerPublicRouter(v1)
|
||||
registerSysSettingRouter(v1)
|
||||
}
|
||||
|
||||
func registerDBRouter(api *gin.RouterGroup) {
|
||||
@@ -81,6 +89,7 @@ func registerSysTableRouter(v1 *gin.RouterGroup) {
|
||||
tablesinfo.PUT("", UpdateSysTable)
|
||||
tablesinfo.DELETE("/:tableId", DeleteSysTables)
|
||||
tablesinfo.GET("/:tableId", GetSysTables)
|
||||
tablesinfo.GET("", GetSysTablesInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,7 +98,8 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
|
||||
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)
|
||||
@@ -98,12 +108,9 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
|
||||
registerDictRouter(v1, authMiddleware)
|
||||
registerSysUserRouter(v1, authMiddleware)
|
||||
registerRoleRouter(v1, authMiddleware)
|
||||
registerConfigRouter(v1, authMiddleware)
|
||||
registerUserCenterRouter(v1, authMiddleware)
|
||||
registerPostRouter(v1, authMiddleware)
|
||||
registerMenuRouter(v1, authMiddleware)
|
||||
registerLoginLogRouter(v1, authMiddleware)
|
||||
registerOperLogRouter(v1, authMiddleware)
|
||||
}
|
||||
|
||||
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
@@ -117,9 +124,6 @@ func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
|
||||
v1auth.POST("/logout", handler.LogOut)
|
||||
v1auth.GET("/menuids", system.GetMenuIDS)
|
||||
|
||||
v1auth.GET("/operloglist", log2.GetOperLogList)
|
||||
v1auth.GET("/configKey/:configKey", system.GetConfigByConfigKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,10 +134,9 @@ func registerPageRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
v1auth.GET("/deptTree", system.GetDeptTree)
|
||||
v1auth.GET("/sysUserList", system.GetSysUserList)
|
||||
v1auth.GET("/rolelist", system.GetRoleList)
|
||||
v1auth.GET("/configList", system.GetConfigList)
|
||||
//v1auth.GET("/configList", system.GetConfigList)
|
||||
v1auth.GET("/postlist", system.GetPostList)
|
||||
v1auth.GET("/menulist", system.GetMenuList)
|
||||
v1auth.GET("/loginloglist", log2.GetLoginLogList)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,24 +149,6 @@ func registerUserCenterRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMid
|
||||
}
|
||||
}
|
||||
|
||||
func registerOperLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
operlog := v1.Group("/operlog").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
operlog.GET("/:operId", log2.GetOperLog)
|
||||
operlog.DELETE("/:operId", log2.DeleteOperLog)
|
||||
}
|
||||
}
|
||||
|
||||
func registerLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
loginlog := v1.Group("/loginlog").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
loginlog.GET("/:infoId", log2.GetLoginLog)
|
||||
loginlog.POST("", log2.InsertLoginLog)
|
||||
loginlog.PUT("", log2.UpdateLoginLog)
|
||||
loginlog.DELETE("/:infoId", log2.DeleteLoginLog)
|
||||
}
|
||||
}
|
||||
|
||||
func registerPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
post := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
@@ -184,16 +169,6 @@ func registerMenuRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
}
|
||||
}
|
||||
|
||||
func registerConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
config := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
config.GET("/:configId", system.GetConfig)
|
||||
config.POST("", system.InsertConfig)
|
||||
config.PUT("", system.UpdateConfig)
|
||||
config.DELETE("/:configId", system.DeleteConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func registerRoleRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
role := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
@@ -243,3 +218,18 @@ func registerDeptRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
dept.DELETE("/:id", system.DeleteDept)
|
||||
}
|
||||
}
|
||||
func registerSysSettingRouter(v1 *gin.RouterGroup) {
|
||||
setting := v1.Group("/setting")
|
||||
{
|
||||
setting.GET("", system.GetSetting)
|
||||
setting.POST("", system.CreateSetting)
|
||||
setting.GET("/serverInfo", monitor.ServerInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func registerPublicRouter(v1 *gin.RouterGroup) {
|
||||
p := v1.Group("/public")
|
||||
{
|
||||
p.POST("/uploadFile", public.UploadFile)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysCategorySearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Name string `form:"name" search:"type:exact;column:name;table:sys_category" comment:"名称"`
|
||||
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_category" comment:"状态"`
|
||||
|
||||
|
||||
}
|
||||
|
||||
func (m *SysCategorySearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysCategorySearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysCategorySearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysCategoryControl struct {
|
||||
|
||||
ID uint `uri:"ID" comment:"标识"` // 标识
|
||||
|
||||
Name string `json:"name" comment:"名称"`
|
||||
|
||||
|
||||
Img string `json:"img" comment:"图标"`
|
||||
|
||||
|
||||
Sort string `json:"sort" comment:"排序"`
|
||||
|
||||
|
||||
Status string `json:"status" comment:"状态"`
|
||||
|
||||
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysCategory{
|
||||
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
Name: s.Name,
|
||||
Img: s.Img,
|
||||
Sort: s.Sort,
|
||||
Status: s.Status,
|
||||
Remark: s.Remark,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysCategoryById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysCategoryById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysCategoryById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysCategory{}, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/models/system"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysConfigSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
ConfigName string `form:"configName" search:"type:exact;column:config_name;table:sys_config" comment:""`
|
||||
ConfigKey string `form:"configKey" search:"type:exact;column:config_key;table:sys_config" comment:""`
|
||||
ConfigType string `form:"configType" search:"type:exact;column:config_type;table:sys_config" comment:""`
|
||||
}
|
||||
|
||||
func (m *SysConfigSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysConfigSearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysConfigSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysConfigControl struct {
|
||||
ID uint `uri:"ID" comment:"编码"` // 编码
|
||||
ConfigName string `json:"configName" comment:""`
|
||||
ConfigKey string `json:"configKey" comment:""`
|
||||
ConfigValue string `json:"configValue" comment:""`
|
||||
ConfigType string `json:"configType" comment:""`
|
||||
Remark string `json:"remark" comment:""`
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysConfig{
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
ConfigName: s.ConfigName,
|
||||
ConfigKey: s.ConfigKey,
|
||||
ConfigValue: s.ConfigValue,
|
||||
ConfigType: s.ConfigType,
|
||||
Remark: s.Remark,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysConfigById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysConfigById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysConfigById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysConfig{}, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysLoginLogSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
|
||||
Username string `form:"username" search:"type:exact;column:username;table:sys_login_log" comment:"用户名"`
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_login_log" comment:"状态"`
|
||||
Ipaddr string `form:"ipaddr" search:"type:exact;column:ipaddr;table:sys_login_log" comment:"ip地址"`
|
||||
LoginLocation string `form:"loginLocation" search:"type:exact;column:login_location;table:sys_login_log" comment:"归属地"`
|
||||
}
|
||||
|
||||
func (m *SysLoginLogSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysLoginLogSearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysLoginLogSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysLoginLogControl struct {
|
||||
ID uint `uri:"ID" comment:"主键"` // 主键
|
||||
Username string `json:"username" comment:"用户名"`
|
||||
Status string `json:"status" comment:"状态"`
|
||||
Ipaddr string `json:"ipaddr" comment:"ip地址"`
|
||||
LoginLocation string `json:"loginLocation" comment:"归属地"`
|
||||
Browser string `json:"browser" comment:"浏览器"`
|
||||
Os string `json:"os" comment:"系统"`
|
||||
Platform string `json:"platform" comment:"固件"`
|
||||
LoginTime time.Time `json:"loginTime" comment:"登录时间"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
Msg string `json:"msg" comment:"信息"`
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysLoginLog{
|
||||
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
Username: s.Username,
|
||||
Status: s.Status,
|
||||
Ipaddr: s.Ipaddr,
|
||||
LoginLocation: s.LoginLocation,
|
||||
Browser: s.Browser,
|
||||
Os: s.Os,
|
||||
Platform: s.Platform,
|
||||
LoginTime: s.LoginTime,
|
||||
Remark: s.Remark,
|
||||
Msg: s.Msg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysLoginLogById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysLoginLogById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysLoginLogById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysLoginLog{}, nil
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysOperaLogSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
|
||||
Title string `form:"title" search:"type:contains;column:title;table:sys_opera_log" comment:"操作模块"`
|
||||
Method string `form:"method" search:"type:contains;column:method;table:sys_opera_log" comment:"函数"`
|
||||
RequestMethod string `form:"requestMethod" search:"type:contains;column:request_method;table:sys_opera_log" comment:"请求方式"`
|
||||
OperUrl string `form:"operUrl" search:"type:contains;column:oper_url;table:sys_opera_log" comment:"访问地址"`
|
||||
OperIp string `form:"operIp" search:"type:exact;column:oper_ip;table:sys_opera_log" comment:"客户端ip"`
|
||||
}
|
||||
|
||||
func (m *SysOperaLogSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysOperaLogSearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysOperaLogSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysOperaLogControl struct {
|
||||
ID uint `uri:"ID" comment:"编码"` // 编码
|
||||
Title string `json:"title" comment:"操作模块"`
|
||||
BusinessType string `json:"businessType" comment:"操作类型"`
|
||||
BusinessTypes string `json:"businessTypes" comment:""`
|
||||
Method string `json:"method" comment:"函数"`
|
||||
RequestMethod string `json:"requestMethod" comment:"请求方式"`
|
||||
OperatorType string `json:"operatorType" comment:"操作类型"`
|
||||
OperName string `json:"operName" comment:"操作者"`
|
||||
DeptName string `json:"deptName" comment:"部门名称"`
|
||||
OperUrl string `json:"operUrl" comment:"访问地址"`
|
||||
OperIp string `json:"operIp" comment:"客户端ip"`
|
||||
OperLocation string `json:"operLocation" comment:"访问位置"`
|
||||
OperParam string `json:"operParam" comment:"请求参数"`
|
||||
Status string `json:"status" comment:"操作状态"`
|
||||
OperTime time.Time `json:"operTime" comment:"操作时间"`
|
||||
JsonResult string `json:"jsonResult" comment:"返回数据"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
LatencyTime string `json:"latencyTime" comment:"耗时"`
|
||||
UserAgent string `json:"userAgent" comment:"ua"`
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysOperaLog{
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
Title: s.Title,
|
||||
BusinessType: s.BusinessType,
|
||||
BusinessTypes: s.BusinessTypes,
|
||||
Method: s.Method,
|
||||
RequestMethod: s.RequestMethod,
|
||||
OperatorType: s.OperatorType,
|
||||
OperName: s.OperName,
|
||||
DeptName: s.DeptName,
|
||||
OperUrl: s.OperUrl,
|
||||
OperIp: s.OperIp,
|
||||
OperLocation: s.OperLocation,
|
||||
OperParam: s.OperParam,
|
||||
Status: s.Status,
|
||||
OperTime: s.OperTime,
|
||||
JsonResult: s.JsonResult,
|
||||
Remark: s.Remark,
|
||||
LatencyTime: s.LatencyTime,
|
||||
UserAgent: s.UserAgent,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysOperaLogById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysOperaLogById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysOperaLogById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysOperaLog{}, nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "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 {
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysJobControl struct {
|
||||
JobId uint `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.ShouldBind(s)
|
||||
}
|
||||
|
||||
func (s *SysJobControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysJobControl) GenerateM() (common.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() (common.ActiveRecord, error) {
|
||||
return &models.SysJob{}, nil
|
||||
}
|
||||
|
||||
type SysJobItem struct {
|
||||
JobId uint `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
|
||||
}
|
||||
@@ -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,27 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/service"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetSysConfigByKEY 根据Key获取SysConfig
|
||||
func (e *SysConfig) GetSysConfigByKEY(c *dto.SysConfigControl) error {
|
||||
var err error
|
||||
var data system.SysConfig
|
||||
msgID := e.MsgID
|
||||
data.ConfigKey = c.ConfigKey
|
||||
err = e.Orm.Table(data.TableName()).Where("config_key = ?", data.ConfigKey).First(c).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"go-admin/app/admin/models/system"
|
||||
cDto "go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/common/service"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetSysLoginLogPage 获取SysLoginLog列表
|
||||
func (e *SysLoginLog) GetSysLoginLogPage(c cDto.Index, list *[]system.SysLoginLog, count *int64) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSysLoginLog 获取SysLoginLog对象
|
||||
func (e *SysLoginLog) GetSysLoginLog(d cDto.Control, model *system.SysLoginLog) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertSysLoginLog 创建SysLoginLog对象
|
||||
func (e *SysLoginLog) InsertSysLoginLog(model common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Create(model).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateSysLoginLog 修改SysLoginLog对象
|
||||
func (e *SysLoginLog) UpdateSysLoginLog(c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(c.GetId()).Updates(c)
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveSysLoginLog 删除SysLoginLog
|
||||
func (e *SysLoginLog) RemoveSysLoginLog(d cDto.Control, c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(d.GetId()).Delete(c)
|
||||
if db.Error != nil {
|
||||
err = db.Error
|
||||
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"go-admin/app/admin/models/system"
|
||||
cDto "go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/common/service"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetSysOperaLogPage 获取SysOperaLog列表
|
||||
func (e *SysOperaLog) GetSysOperaLogPage(c cDto.Index, list *[]system.SysOperaLog, count *int64) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSysOperaLog 获取SysOperaLog对象
|
||||
func (e *SysOperaLog) GetSysOperaLog(d cDto.Control, model *system.SysOperaLog) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertSysOperaLog 创建SysOperaLog对象
|
||||
func (e *SysOperaLog) InsertSysOperaLog(model common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Create(model).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateSysOperaLog 修改SysOperaLog对象
|
||||
func (e *SysOperaLog) UpdateSysOperaLog(c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(c.GetId()).Updates(c)
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveSysOperaLog 删除SysOperaLog
|
||||
func (e *SysOperaLog) RemoveSysOperaLog(d cDto.Control, c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(d.GetId()).Delete(c)
|
||||
if db.Error != nil {
|
||||
err = db.Error
|
||||
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/jobs"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/service"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
type SysJob struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// RemoveJob 删除job
|
||||
func (e *SysJob) RemoveJob(c *dto.GeneralDelDto) error {
|
||||
var err error
|
||||
var data models.SysJob
|
||||
msgID := e.MsgID
|
||||
data.JobId = c.Id
|
||||
err = e.Orm.Table(data.TableName()).First(&data).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
cn := jobs.Remove(data.EntryId)
|
||||
|
||||
select {
|
||||
case res := <-cn:
|
||||
if res {
|
||||
err = e.Orm.Table(data.TableName()).Where("entry_id = ?", data.EntryId).Update("entry_id", 0).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
case <-time.After(time.Second * 1):
|
||||
e.Msg = msg.TimeOut
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartJob 启动任务
|
||||
func (e *SysJob) StartJob(c *dto.GeneralGetDto) error {
|
||||
var data models.SysJob
|
||||
var err error
|
||||
msgID := e.MsgID
|
||||
err = e.Orm.Table(data.TableName()).First(&data, c.Id).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] jobs AddJob[HttpJob] error:%s", msgID, err)
|
||||
}
|
||||
} 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)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] jobs AddJob[ExecJob] error:%s", msgID, err)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = e.Orm.Table(data.TableName()).Where(c.Id).Updates(&data).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"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"
|
||||
var retryCount = 3
|
||||
|
||||
var jobList map[string]JobsExec
|
||||
var lock sync.Mutex
|
||||
|
||||
type JobCore struct {
|
||||
InvokeTarget string
|
||||
Name string
|
||||
JobId uint
|
||||
EntryId int
|
||||
CronExpression string
|
||||
Args string
|
||||
}
|
||||
|
||||
// 任务类型 http
|
||||
type HttpJob struct {
|
||||
JobCore
|
||||
}
|
||||
|
||||
type ExecJob struct {
|
||||
JobCore
|
||||
}
|
||||
|
||||
func (e *ExecJob) Run() {
|
||||
startTime := time.Now()
|
||||
var obj = jobList[e.InvokeTarget]
|
||||
if obj == nil {
|
||||
global.JobLogger.Warn(" ExecJob Run job nil")
|
||||
return
|
||||
}
|
||||
err := CallExec(obj.(JobsExec), e.Args)
|
||||
if err != nil {
|
||||
// 如果失败暂停一段时间重试
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] mission failed! ", err)
|
||||
}
|
||||
// 结束时间
|
||||
endTime := time.Now()
|
||||
|
||||
// 执行时间
|
||||
latencyTime := endTime.Sub(startTime)
|
||||
//TODO: 待完善部分
|
||||
//str := time.Now().Format(timeFormat) + " [INFO] JobCore " + string(e.EntryId) + "exec success , spend :" + latencyTime.String()
|
||||
//ws.SendAll(str)
|
||||
global.JobLogger.Info(time.Now().Format(timeFormat), " [INFO] JobCore ", e, "exec success , spend :", latencyTime)
|
||||
return
|
||||
}
|
||||
|
||||
//http 任务接口
|
||||
func (h *HttpJob) Run() {
|
||||
|
||||
startTime := time.Now()
|
||||
var count = 0
|
||||
var err error
|
||||
var str string
|
||||
/* 循环 */
|
||||
LOOP:
|
||||
if count < retryCount {
|
||||
/* 跳过迭代 */
|
||||
str, err = pkg.Get(h.InvokeTarget)
|
||||
if err != nil {
|
||||
// 如果失败暂停一段时间重试
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] mission failed! ", err)
|
||||
fmt.Printf(time.Now().Format(timeFormat)+" [INFO] Retry after the task fails %d seconds! %s \n", (count+1)*5, str)
|
||||
time.Sleep(time.Duration(count+1) * 5 * time.Second)
|
||||
count = count + 1
|
||||
goto LOOP
|
||||
}
|
||||
}
|
||||
// 结束时间
|
||||
endTime := time.Now()
|
||||
|
||||
// 执行时间
|
||||
latencyTime := endTime.Sub(startTime)
|
||||
//TODO: 待完善部分
|
||||
|
||||
global.JobLogger.Info(time.Now().Format(timeFormat), " [INFO] JobCore ", h, "exec success , spend :", latencyTime)
|
||||
return
|
||||
}
|
||||
|
||||
// 初始化
|
||||
func Setup() {
|
||||
|
||||
fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Starting...")
|
||||
|
||||
global.GADMCron = cronjob.NewWithSeconds()
|
||||
|
||||
sysJob := models.SysJob{}
|
||||
jobList := make([]models.SysJob, 0)
|
||||
err := sysJob.GetList(&jobList)
|
||||
if err != nil {
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore init error", err)
|
||||
}
|
||||
if len(jobList) == 0 {
|
||||
fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore total:0")
|
||||
}
|
||||
|
||||
_, err = sysJob.RemoveAllEntryID()
|
||||
if err != nil {
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore remove entry_id error", err)
|
||||
}
|
||||
|
||||
for i := 0; i < len(jobList); i++ {
|
||||
if jobList[i].JobType == 1 {
|
||||
j := &HttpJob{}
|
||||
j.InvokeTarget = jobList[i].InvokeTarget
|
||||
j.CronExpression = jobList[i].CronExpression
|
||||
j.JobId = jobList[i].JobId
|
||||
j.Name = jobList[i].JobName
|
||||
|
||||
sysJob.EntryId, err = AddJob(j)
|
||||
} else if jobList[i].JobType == 2 {
|
||||
j := &ExecJob{}
|
||||
j.InvokeTarget = jobList[i].InvokeTarget
|
||||
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)
|
||||
}
|
||||
|
||||
// 其中任务
|
||||
global.GADMCron.Start()
|
||||
fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore start success.")
|
||||
// 关闭任务
|
||||
defer global.GADMCron.Stop()
|
||||
select {}
|
||||
}
|
||||
|
||||
// 添加任务 AddJob(invokeTarget string, jobId int, jobName string, cronExpression string)
|
||||
func AddJob(job Job) (int, error) {
|
||||
if job == nil {
|
||||
fmt.Println("unknown")
|
||||
return 0, nil
|
||||
}
|
||||
return job.addJob()
|
||||
}
|
||||
|
||||
func (h *HttpJob) addJob() (int, error) {
|
||||
id, err := global.GADMCron.AddJob(h.CronExpression, h)
|
||||
if err != nil {
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore AddJob error", err)
|
||||
return 0, err
|
||||
}
|
||||
EntryId := int(id)
|
||||
return EntryId, nil
|
||||
}
|
||||
|
||||
func (h *ExecJob) addJob() (int, error) {
|
||||
id, err := global.GADMCron.AddJob(h.CronExpression, h)
|
||||
if err != nil {
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore AddJob error", err)
|
||||
return 0, err
|
||||
}
|
||||
EntryId := int(id)
|
||||
return EntryId, nil
|
||||
}
|
||||
|
||||
// 移除任务
|
||||
func Remove(entryID int) chan bool {
|
||||
ch := make(chan bool)
|
||||
go func() {
|
||||
global.GADMCron.Remove(cron.EntryID(entryID))
|
||||
fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Remove success ,info entryID :", entryID)
|
||||
ch <- true
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
// 任务停止
|
||||
func Stop() chan bool {
|
||||
ch := make(chan bool)
|
||||
go func() {
|
||||
global.GADMCron.Stop()
|
||||
ch <- true
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
+64
-35
@@ -3,28 +3,33 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"go-admin/database"
|
||||
"go-admin/global"
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/router"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
"io/ioutil"
|
||||
"go-admin/tools/trace"
|
||||
"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"
|
||||
"go-admin/common/log"
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
var (
|
||||
configYml string
|
||||
port string
|
||||
mode string
|
||||
StartCmd = &cobra.Command{
|
||||
configYml string
|
||||
port string
|
||||
mode string
|
||||
traceStart bool
|
||||
StartCmd = &cobra.Command{
|
||||
Use: "server",
|
||||
Short: "Start API server",
|
||||
Example: "go-admin server -c config/settings.yml",
|
||||
@@ -36,15 +41,18 @@ var (
|
||||
return run()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
)
|
||||
|
||||
var echoTimes int
|
||||
var AppRouters = make([]func(), 0)
|
||||
|
||||
func init() {
|
||||
StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
|
||||
StartCmd.PersistentFlags().StringVarP(&port, "port", "p", "8000", "Tcp port server listening on")
|
||||
StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
|
||||
StartCmd.PersistentFlags().BoolVarP(&traceStart, "traceStart", "t", false, "start traceStart app dash")
|
||||
|
||||
//注册路由 fixme 其他应用的路由,在本目录新建文件放在init方法
|
||||
AppRouters = append(AppRouters, router.InitRouter)
|
||||
}
|
||||
|
||||
func setup() {
|
||||
@@ -52,47 +60,69 @@ func setup() {
|
||||
//1. 读取配置
|
||||
config.Setup(configYml)
|
||||
//2. 设置日志
|
||||
logger.Setup()
|
||||
global.Logger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "bus")
|
||||
global.JobLogger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "job")
|
||||
global.RequestLogger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "request")
|
||||
//3. 初始化数据库链接
|
||||
database.Setup(config.DatabaseConfig.Driver)
|
||||
//4. 接口访问控制加载
|
||||
mycasbin.Setup()
|
||||
global.CasbinEnforcer = mycasbin.Setup(global.Eloquent, "sys_")
|
||||
|
||||
usageStr := `starting api server`
|
||||
global.Logger.Info(usageStr)
|
||||
log.Info(usageStr)
|
||||
|
||||
}
|
||||
|
||||
func run() error {
|
||||
if mode != "" {
|
||||
config.SetConfig(configYml, "settings.application.mode", mode)
|
||||
}
|
||||
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()
|
||||
if mode == "dev" {
|
||||
//监控
|
||||
AppRouters = append(AppRouters, router.Monitor)
|
||||
}
|
||||
|
||||
defer global.Eloquent.Close()
|
||||
for _, f := range AppRouters {
|
||||
f()
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: config.ApplicationConfig.Host + ":" + config.ApplicationConfig.Port,
|
||||
Handler: r,
|
||||
Handler: global.Cfg.GetEngine(),
|
||||
}
|
||||
go func() {
|
||||
jobs.InitJob()
|
||||
jobs.Setup()
|
||||
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if traceStart {
|
||||
//链路追踪, fixme 页面显示需要自备梯子
|
||||
trace.Start()
|
||||
defer trace.Stop(ctx)
|
||||
}
|
||||
|
||||
go func() {
|
||||
// 服务连接
|
||||
if config.SslConfig.Enable {
|
||||
if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
|
||||
global.Logger.Fatal("listen: ", err)
|
||||
log.Fatal("listen: ", err)
|
||||
}
|
||||
} else {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
global.Logger.Fatal("listen: ", err)
|
||||
log.Fatal("listen: ", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
content, _ := ioutil.ReadFile("./static/go-admin.txt")
|
||||
fmt.Println(tools.Red(string(content)))
|
||||
fmt.Println(tools.Red(string(global.LogoContent)))
|
||||
tip()
|
||||
fmt.Println(tools.Green("Server run at:"))
|
||||
fmt.Printf("- Local: http://localhost:%s/ \r\n", config.ApplicationConfig.Port)
|
||||
@@ -107,12 +137,11 @@ func run() error {
|
||||
<-quit
|
||||
fmt.Printf("%s Shutdown Server ... \r\n", tools.GetCurrentTimeStr())
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
global.Logger.Fatal("Server Shutdown:", err)
|
||||
log.Fatal("Server Shutdown:", err)
|
||||
}
|
||||
global.Logger.Println("Server exiting")
|
||||
log.Info("Server exiting")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+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,68 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"log"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var Migrate = &Migration{
|
||||
version: make(map[int]func(db *gorm.DB, version string) error),
|
||||
}
|
||||
|
||||
type Migration struct {
|
||||
db *gorm.DB
|
||||
version map[int]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 int, 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([]int, 0)
|
||||
for k := range e.version {
|
||||
versions = append(versions, k)
|
||||
}
|
||||
if !sort.IntsAreSorted(versions) {
|
||||
sort.Ints(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(), strconv.Itoa(v))
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetFilename(s string) int {
|
||||
s = filepath.Base(s)
|
||||
return cast.ToInt(s[:13])
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package version_local
|
||||
|
||||
func init() {
|
||||
}
|
||||
|
||||
/**
|
||||
开发者项目的迁移脚本放在这个目录里,init写法参考version目录里的migrate或者自动生成
|
||||
*/
|
||||
@@ -0,0 +1,51 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1599190683659Tables)
|
||||
}
|
||||
|
||||
func _1599190683659Tables(db *gorm.DB, version string) error {
|
||||
err := db.Debug().Migrator().AutoMigrate(
|
||||
new(models.CasbinRule),
|
||||
new(models.SysDept),
|
||||
new(system.SysConfig),
|
||||
new(tools.SysTables),
|
||||
new(tools.SysColumns),
|
||||
new(models.Menu),
|
||||
new(system.SysLoginLog),
|
||||
new(system.SysOperaLog),
|
||||
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(system.SysConfig),
|
||||
new(models.SysSetting),
|
||||
new(models.SysFileDir),
|
||||
new(models.SysFileInfo),
|
||||
new(models.SysCategory),
|
||||
new(models.SysContent),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1599190683670Test)
|
||||
}
|
||||
|
||||
func _1599190683670Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
list3 := []models.SysDept{
|
||||
{DeptId: 1, ParentId: 0, DeptPath: "/0/1", DeptName: "爱拓科技", Sort: 0, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 7, ParentId: 1, DeptPath: "/0/1/7", DeptName: "研发部", Sort: 1, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 8, ParentId: 1, DeptPath: "/0/1/8", DeptName: "运维部", Sort: 0, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 9, ParentId: 1, DeptPath: "/0/1/9", DeptName: "客服部", Sort: 0, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 10, ParentId: 1, DeptPath: "/0/1/10", DeptName: "人力资源", Sort: 3, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "1", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list4 := []system.SysConfig{
|
||||
{Model: gorm.Model{ID: 1, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeletedAt: gorm.DeletedAt{}}, ControlBy: common.ControlBy{CreateBy: 1, UpdateBy: 1}, ConfigName: "主框架页-默认皮肤样式名称", ConfigKey: "sys_index_skinName", ConfigValue: "skin-blue", ConfigType: "Y", Remark: "蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow"},
|
||||
{Model: gorm.Model{ID: 2, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeletedAt: gorm.DeletedAt{}}, ControlBy: common.ControlBy{CreateBy: 1, UpdateBy: 1}, ConfigName: "用户管理-账号初始密码", ConfigKey: "sys.user.initPassword", ConfigValue: "123456", ConfigType: "Y", Remark: "初始化密码 123456"},
|
||||
{Model: gorm.Model{ID: 3, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeletedAt: gorm.DeletedAt{}}, ControlBy: common.ControlBy{CreateBy: 1, UpdateBy: 1}, ConfigName: "主框架页-侧边栏主题", ConfigKey: "sys_index_sideTheme", ConfigValue: "theme-dark", ConfigType: "Y", Remark: "深色主题theme-dark,浅色主题theme-light"},
|
||||
}
|
||||
|
||||
list5 := []models.Post{
|
||||
{PostId: 1, PostName: "首席执行官", PostCode: "CEO", Sort: 0, Status: "0", Remark: "首席执行官", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{PostId: 2, PostName: "首席技术执行官", PostCode: "CTO", Sort: 2, Status: "0", Remark: "首席技术执行官", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{PostId: 3, PostName: "首席运营官", PostCode: "COO", Sort: 3, Status: "0", Remark: "测试工程师", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list6 := []models.SysRole{
|
||||
{1, "系统管理员", "0", "admin", 1, "", "1", "", "", true, "", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, "", []int{}, []int{}},
|
||||
}
|
||||
|
||||
list7 := []models.DictType{
|
||||
{DictId: 1, DictName: "系统开关", DictType: "sys_normal_disable", Status: "0", CreateBy: "1", UpdateBy: "1", Remark: "系统开关列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 2, DictName: "用户性别", DictType: "sys_user_sex", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "用户性别列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 3, DictName: "菜单状态", DictType: "sys_show_hide", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "菜单状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 4, DictName: "系统是否", DictType: "sys_yes_no", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "系统是否列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 5, DictName: "任务状态", DictType: "sys_job_status", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "任务状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 6, DictName: "任务分组", DictType: "sys_job_group", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "任务分组列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 7, DictName: "通知类型", DictType: "sys_notice_type", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "通知类型列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 8, DictName: "系统状态", DictType: "sys_common_status", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "登录状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 9, DictName: "操作类型", DictType: "sys_oper_type", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "操作类型列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 10, DictName: "通知状态", DictType: "sys_notice_status", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "通知状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list8 := []models.SysUser{
|
||||
{models.SysUserId{1}, models.LoginM{models.UserName{"admin"}, models.PassWord{"$2a$10$cKFFTCzGOvaIHHJY2K45Zuwt8TD6oPzYi4s5MzYIBAWCLL6ZhouP2"}}, models.SysUserB{"zhangwj", "13818888888", 1, "", "", "0", "1@qq.com", 1, 1, "1", "1", "", "0", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, "", ""}},
|
||||
}
|
||||
|
||||
list9 := []models.DictData{
|
||||
{DictCode: 1, DictSort: 0, DictLabel: "正常", DictValue: "0", DictType: "sys_normal_disable", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统正常", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 2, DictSort: 0, DictLabel: "停用", DictValue: "1", DictType: "sys_normal_disable", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统停用", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 3, DictSort: 0, DictLabel: "男", DictValue: "0", DictType: "sys_user_sex", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "性别男", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 4, DictSort: 0, DictLabel: "女", DictValue: "1", DictType: "sys_user_sex", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "性别女", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 5, DictSort: 0, DictLabel: "未知", DictValue: "2", DictType: "sys_user_sex", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "性别未知", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 6, DictSort: 0, DictLabel: "显示", DictValue: "0", DictType: "sys_show_hide", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "显示菜单", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 7, DictSort: 0, DictLabel: "隐藏", DictValue: "1", DictType: "sys_show_hide", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "隐藏菜单", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 8, DictSort: 0, DictLabel: "是", DictValue: "Y", DictType: "sys_yes_no", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统默认是", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 9, DictSort: 0, DictLabel: "否", DictValue: "N", DictType: "sys_yes_no", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统默认否", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 10, DictSort: 0, DictLabel: "正常", DictValue: "2", DictType: "sys_job_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "正常状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 11, DictSort: 0, DictLabel: "停用", DictValue: "1", DictType: "sys_job_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "停用状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 12, DictSort: 0, DictLabel: "默认", DictValue: "DEFAULT", DictType: "sys_job_group", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "默认分组", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 13, DictSort: 0, DictLabel: "系统", DictValue: "SYSTEM", DictType: "sys_job_group", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统分组", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 14, DictSort: 0, DictLabel: "通知", DictValue: "1", DictType: "sys_notice_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "通知", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 15, DictSort: 0, DictLabel: "公告", DictValue: "2", DictType: "sys_notice_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "公告", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 16, DictSort: 0, DictLabel: "正常", DictValue: "0", DictType: "sys_common_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "正常状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 17, DictSort: 0, DictLabel: "关闭", DictValue: "1", DictType: "sys_common_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "关闭状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 18, DictSort: 0, DictLabel: "新增", DictValue: "1", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "新增操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 19, DictSort: 0, DictLabel: "修改", DictValue: "2", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "修改操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 20, DictSort: 0, DictLabel: "删除", DictValue: "3", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "删除操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 21, DictSort: 0, DictLabel: "授权", DictValue: "4", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "授权操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 22, DictSort: 0, DictLabel: "导出", DictValue: "5", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "导出操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 23, DictSort: 0, DictLabel: "导入", DictValue: "6", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "导入操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 24, DictSort: 0, DictLabel: "强退", DictValue: "7", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "强退操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 25, DictSort: 0, DictLabel: "生成代码", DictValue: "8", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "生成操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 26, DictSort: 0, DictLabel: "清空数据", DictValue: "9", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "清空操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 27, DictSort: 0, DictLabel: "成功", DictValue: "0", DictType: "sys_notice_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "成功状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 28, DictSort: 0, DictLabel: "失败", DictValue: "1", DictType: "sys_notice_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "失败状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 29, DictSort: 0, DictLabel: "登录", DictValue: "10", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "1", Remark: "登录操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 30, DictSort: 0, DictLabel: "退出", DictValue: "11", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "1", Remark: "", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 31, DictSort: 0, DictLabel: "获取验证码", DictValue: "12", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "1", Remark: "获取验证码", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list10 := []models.SysSetting{
|
||||
{1, "go-admin管理系统", "https://gitee.com/mydearzwj/image/raw/master/img/go-admin.png", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list11 := []models.SysJob{
|
||||
{1, "接口测试", "DEFAULT", 1, "0/5 * * * * ", "http://localhost:8000", "", 1, 1, 1, 0, "", "", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, ""},
|
||||
{2, "函数测试", "DEFAULT", 2, "0/5 * * * * ", "ExamplesOne", "参数", 1, 1, 1, 0, "", "", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, ""},
|
||||
}
|
||||
|
||||
err := tx.Create(list3).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list4).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list5).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list6).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list7).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list8).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list9).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list10).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list11).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := models.InitDb(tx); err != nil {
|
||||
|
||||
}
|
||||
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user