mirror of
https://github.com/flipped-aurora/gin-vue-admin.git
synced 2026-09-25 05:50:19 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17cab8fcb7 | ||
|
|
d64753859d | ||
|
|
48b1c24c95 | ||
|
|
7e5e12b139 | ||
|
|
59ba4752c0 | ||
|
|
189219c673 | ||
|
|
4b54262edd | ||
|
|
458b035a7e | ||
|
|
abe85cf6e7 | ||
|
|
379b63275a | ||
|
|
07cde689b1 | ||
|
|
26606f138d | ||
|
|
24c4774f7e | ||
|
|
4890de5052 | ||
|
|
746af37899 | ||
|
|
0136ce7034 | ||
|
|
5ca47a91a6 | ||
|
|
d849df41be | ||
|
|
a2269bcdd5 | ||
|
|
d41394c70a | ||
|
|
756f73bbd2 | ||
|
|
95eb17b6d1 | ||
|
|
773fd1f221 | ||
|
|
c95b436680 | ||
|
|
3f47151678 | ||
|
|
dbf1e7136c | ||
|
|
84b44eef91 | ||
|
|
686ada1e49 | ||
|
|
d9f6bc058a | ||
|
|
6f531793f0 | ||
|
|
f8794bef5f | ||
|
|
9daf103669 | ||
|
|
26fa047fe4 | ||
|
|
1a04bb535d | ||
|
|
ad41b7b434 | ||
|
|
6791b1dbdc | ||
|
|
dc1b84130c | ||
|
|
e70a933090 | ||
|
|
08617f2fd4 | ||
|
|
8aefb5db8e | ||
|
|
e1d214b91a | ||
|
|
0285de50e5 | ||
|
|
5f7caa0535 | ||
|
|
df9d2bc472 | ||
|
|
a923b6beca | ||
|
|
760ef77593 | ||
|
|
64f703856e | ||
|
|
36eba36bf2 | ||
|
|
332176a619 | ||
|
|
cd5b60c8cc | ||
|
|
5ea8947fc9 | ||
|
|
474a5c8e42 | ||
|
|
952062d5be | ||
|
|
c071564de4 | ||
|
|
b2fa7563d3 | ||
|
|
22f68fedcb | ||
|
|
0a4cda26cb | ||
|
|
54eb84e690 | ||
|
|
5cd33814fc | ||
|
|
90f19679e7 | ||
|
|
38ade9e498 | ||
|
|
4c77831001 | ||
|
|
722fe556e3 | ||
|
|
98b83c0078 | ||
|
|
85646b5ffa | ||
|
|
d3f5ed7d60 | ||
|
|
e0a8e93704 | ||
|
|
3aab5e9eb7 | ||
|
|
2307ac88cb | ||
|
|
0f2018d913 | ||
|
|
8b9a75ba5a | ||
|
|
7872e0ce38 | ||
|
|
d28ac73987 | ||
|
|
2c8c7a8b51 | ||
|
|
f98fc6bf3c | ||
|
|
d42958734f | ||
|
|
6f2c785713 | ||
|
|
05a1ce51f0 | ||
|
|
58b063770d | ||
|
|
6f9a83709d | ||
|
|
bd2a3ddfba | ||
|
|
4433b6623e | ||
|
|
e1ca17637f | ||
|
|
5ef0e43312 | ||
|
|
aa6ca95f13 | ||
|
|
2523467c97 | ||
|
|
b38eb6709e | ||
|
|
f6dacdb046 | ||
|
|
cc0903f74d | ||
|
|
72936fc0d1 | ||
|
|
4b7f552885 | ||
|
|
9b2fc60d79 | ||
|
|
3e5a26b95a | ||
|
|
a5f3139784 | ||
|
|
9ca9fcdb09 | ||
|
|
913db35b23 | ||
|
|
8eba3ba4f7 | ||
|
|
5bd0f24a84 | ||
|
|
e8fb3180db | ||
|
|
232aaad090 | ||
|
|
b3dbb8d4be | ||
|
|
3caf070056 | ||
|
|
1e24bbc3e2 | ||
|
|
18694fd24a | ||
|
|
10dc003f20 | ||
|
|
809e2496c0 | ||
|
|
c1c37901b5 | ||
|
|
44e115f211 | ||
|
|
217cc338a8 | ||
|
|
81eccc177d | ||
|
|
4ea00b7e7b | ||
|
|
844699263d | ||
|
|
d72a548852 | ||
|
|
722ed9bece | ||
|
|
8852367837 | ||
|
|
5559f9b9af | ||
|
|
39526edafd | ||
|
|
a4f86354d3 | ||
|
|
636204bbaf | ||
|
|
08494834c2 | ||
|
|
2247f34b89 | ||
|
|
5c84412238 | ||
|
|
13112aa4d8 | ||
|
|
836a165ff2 | ||
|
|
f36e0b39ed | ||
|
|
74e2ec74e0 | ||
|
|
bcb6243f3b | ||
|
|
c00b628fb4 | ||
|
|
2fbed17ebc | ||
|
|
7bfea23958 | ||
|
|
91c567779b | ||
|
|
c4aeeb419e | ||
|
|
7808fbb852 | ||
|
|
9e64bd474b | ||
|
|
25a6aef472 | ||
|
|
203ba521b0 | ||
|
|
287685420a | ||
|
|
a6ae0ba4b0 | ||
|
|
208346a480 | ||
|
|
0d5c55a3b5 | ||
|
|
4fcd2bf14c | ||
|
|
deea1aba7f | ||
|
|
3e31666cd6 | ||
|
|
197c4c46ab | ||
|
|
33cb2ed43d | ||
|
|
b56e521c5f | ||
|
|
639b930ac9 | ||
|
|
607235eb01 | ||
|
|
dbfeb4b0fa | ||
|
|
432725b80d | ||
|
|
91c2909c4a | ||
|
|
699a2f7956 | ||
|
|
7c2751ad37 | ||
|
|
50b524fa7a | ||
|
|
aee26bc9b2 | ||
|
|
78de254230 | ||
|
|
22fe4053e9 | ||
|
|
e73f9ac8f2 | ||
|
|
19987234e5 | ||
|
|
33239f28f8 | ||
|
|
350f4572ed | ||
|
|
ab29267d64 | ||
|
|
b410820868 | ||
|
|
b1268e0001 | ||
|
|
9fe661269d | ||
|
|
a715a77e76 | ||
|
|
20933f77f5 | ||
|
|
c618fcafaa | ||
|
|
350ce2ad35 | ||
|
|
eef8580e89 | ||
|
|
406fc05970 | ||
|
|
2b6cb775d8 | ||
|
|
fe27fd4c86 | ||
|
|
784dca2baa | ||
|
|
6cff6414c2 | ||
|
|
b84b6c3464 | ||
|
|
bd3931d62d | ||
|
|
7ababb626b | ||
|
|
62b2833c2f | ||
|
|
190c82bbe6 | ||
|
|
b8055d45e7 | ||
|
|
fe09bb3c91 | ||
|
|
84d0a91c44 | ||
|
|
9d95f660e3 | ||
|
|
2d76d1f50c | ||
|
|
df3b921654 | ||
|
|
e98fccdcfd | ||
|
|
7b9b940b6a | ||
|
|
3a4b750d93 | ||
|
|
40e3555d13 | ||
|
|
4b6adb3919 | ||
|
|
66aece580f | ||
|
|
09fc200d55 | ||
|
|
b17b56dba0 | ||
|
|
a9d0531a56 | ||
|
|
a7a2c85f82 | ||
|
|
83a06fcd2b | ||
|
|
d2d7b22a8f | ||
|
|
92b78ab3c8 | ||
|
|
0bed3bab98 | ||
|
|
a60637fb79 | ||
|
|
f1218264be | ||
|
|
18cf63facc | ||
|
|
9f8e1775af | ||
|
|
0e39f3ad05 | ||
|
|
4fc90c0168 | ||
|
|
57b4f539f9 | ||
|
|
8667ce5fb4 | ||
|
|
0ed922bb29 | ||
|
|
80eff97be3 | ||
|
|
e5cfe5cd99 | ||
|
|
1d8b952a6d | ||
|
|
c204f7a514 | ||
|
|
6e2ef1e29c | ||
|
|
5f0402043a | ||
|
|
6ad7ccdd6e | ||
|
|
90a2fd7f19 | ||
|
|
58c8b11f85 | ||
|
|
4d700be9ae | ||
|
|
da0d02b990 | ||
|
|
854cb59f6b | ||
|
|
33cbee23d4 | ||
|
|
0497cf384d | ||
|
|
acd8fa3810 | ||
|
|
9d024bca3b | ||
|
|
7434c9db55 | ||
|
|
a3ab0b3243 | ||
|
|
64608f6b05 | ||
|
|
a207c982b7 | ||
|
|
072acac399 | ||
|
|
8049466dff | ||
|
|
80077ba94d | ||
|
|
bd4744557f | ||
|
|
d8072634ef | ||
|
|
27158f7075 | ||
|
|
f06f1fb7f1 | ||
|
|
8bb7b75f05 | ||
|
|
0c9e92abb0 | ||
|
|
7a8787b1a0 | ||
|
|
78f71c8b13 | ||
|
|
a0a35e8253 | ||
|
|
e892e3f9e1 | ||
|
|
2dadc98485 | ||
|
|
1bd2b4629e | ||
|
|
ce52cbf6ac | ||
|
|
0abcb5aba1 | ||
|
|
ca7bdc913e | ||
|
|
2de7d34b4a | ||
|
|
0eea78f796 | ||
|
|
95fa7e8130 | ||
|
|
fd78876dd3 | ||
|
|
eaa3075516 | ||
|
|
92338fd219 | ||
|
|
26d32c02ea | ||
|
|
e03efc33d7 | ||
|
|
2d1188af11 | ||
|
|
66666ed5fd | ||
|
|
dfcb283899 | ||
|
|
24215f8b28 | ||
|
|
ddc2b4c2ad | ||
|
|
10cef483f4 | ||
|
|
51dde2f71e | ||
|
|
5e0117e7c6 |
@@ -48,7 +48,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.18]
|
||||
go-version: [1.21]
|
||||
steps:
|
||||
- name: Set up Go ${{ matrix.go-version }}
|
||||
uses: actions/setup-go@v1
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [16.8.0]
|
||||
go-version: [1.18]
|
||||
go-version: [1.21]
|
||||
steps:
|
||||
- name: Check out branch
|
||||
uses: actions/checkout@v2
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
- name: Build-go
|
||||
run: |
|
||||
cd server/ && go mod tidy && go build && mkdir ../web/ser && mv server ../web/ser/ && cd ../web/ser/ && ls -s
|
||||
cd server/ && go mod tidy && CGO_ENABLED=0 go build && mkdir ../web/ser && mv server ../web/ser/ && cd ../web/ser/ && ls -s
|
||||
- name: restart
|
||||
env:
|
||||
KEY: ${{ secrets.KEY }}
|
||||
@@ -195,7 +195,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: ['16.x']
|
||||
go-version: ['1.18']
|
||||
go-version: ['1.21']
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: tag major and minor versions
|
||||
@@ -220,7 +220,7 @@ jobs:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
- name: Build-go
|
||||
run: |
|
||||
cd server/ && go mod tidy && go build && mkdir ../web/ser && mv server ../web/ser/ && cd ../web/ser/ && ls -s
|
||||
cd server/ && go mod tidy && CGO_ENABLED=0 go build && mkdir ../web/ser && mv server ../web/ser/ && cd ../web/ser/ && ls -s
|
||||
- name: restart
|
||||
env:
|
||||
KEY: ${{ secrets.KEY }}
|
||||
|
||||
@@ -186,7 +186,7 @@
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2019 JiZhao Jiang
|
||||
Copyright 2019 北京翻转极光科技有限责任公司
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
+5
-5
@@ -3,11 +3,11 @@
|
||||
<img src="http://qmplusimg.henrongyi.top/gvalogo.jpg" width=300" height="300" />
|
||||
</div>
|
||||
<div align=center>
|
||||
<img src="https://img.shields.io/badge/golang-1.16-blue"/>
|
||||
<img src="https://img.shields.io/badge/gin-1.7.0-lightBlue"/>
|
||||
<img src="https://img.shields.io/badge/vue-3.2.25-brightgreen"/>
|
||||
<img src="https://img.shields.io/badge/element--plus-2.0.1-green"/>
|
||||
<img src="https://img.shields.io/badge/gorm-1.22.5-red"/>
|
||||
<img src="https://img.shields.io/badge/golang-1.18-blue"/>
|
||||
<img src="https://img.shields.io/badge/gin-1.9.1-lightBlue"/>
|
||||
<img src="https://img.shields.io/badge/vue-3.3.4-brightgreen"/>
|
||||
<img src="https://img.shields.io/badge/element--plus-2.3.8-green"/>
|
||||
<img src="https://img.shields.io/badge/gorm-1.25.2-red"/>
|
||||
</div>
|
||||
|
||||
English | [简体中文](./README.md)
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
<img src="http://qmplusimg.henrongyi.top/gvalogo.jpg" width=300" height="300" />
|
||||
</div>
|
||||
<div align=center>
|
||||
<img src="https://img.shields.io/badge/golang-1.16-blue"/>
|
||||
<img src="https://img.shields.io/badge/gin-1.7.0-lightBlue"/>
|
||||
<img src="https://img.shields.io/badge/vue-3.2.25-brightgreen"/>
|
||||
<img src="https://img.shields.io/badge/element--plus-2.0.1-green"/>
|
||||
<img src="https://img.shields.io/badge/gorm-1.22.5-red"/>
|
||||
<img src="https://img.shields.io/badge/golang-1.20-blue"/>
|
||||
<img src="https://img.shields.io/badge/gin-1.9.1-lightBlue"/>
|
||||
<img src="https://img.shields.io/badge/vue-3.3.4-brightgreen"/>
|
||||
<img src="https://img.shields.io/badge/element--plus-2.3.8-green"/>
|
||||
<img src="https://img.shields.io/badge/gorm-1.25.2-red"/>
|
||||
</div>
|
||||
|
||||
[English](./README-en.md) | 简体中文
|
||||
@@ -66,8 +66,8 @@ Gin-vue-admin 是一套为快速研发准备的一整套前后端分离架构式
|
||||
Gin-vue-admin 的成长离不开大家的支持,如果你愿意为 gin-vue-admin 贡献代码或提供建议,请阅读以下内容。
|
||||
|
||||
#### 1.2.1 Issue 规范
|
||||
- issue 仅用于提交 Bug 或 Feature 以及设计相关的内容,其它内容可能会被直接关闭。如果你在使用时产生了疑问,请到 Slack 或 [Gitter](https://gitter.im/ElemeFE/element) 里咨询。
|
||||
|
||||
- issue 仅用于提交 Bug 或 Feature 以及设计相关的内容,其它内容可能会被直接关闭。
|
||||
|
||||
- 在提交 issue 之前,请搜索相关内容是否已被提出。
|
||||
|
||||
#### 1.2.2 Pull Request 规范
|
||||
@@ -125,29 +125,8 @@ npm run serve
|
||||
|
||||
#### 2.3.1 安装 swagger
|
||||
|
||||
##### (1)可以访问外国网站
|
||||
|
||||
````
|
||||
go get -u github.com/swaggo/swag/cmd/swag
|
||||
````
|
||||
|
||||
##### (2)无法访问外国网站
|
||||
|
||||
由于国内没法安装 go.org/x 包下面的东西,推荐使用 [goproxy.cn](https://goproxy.cn) 或者 [goproxy.io](https://goproxy.io/zh/)
|
||||
|
||||
```bash
|
||||
# 如果您使用的 Go 版本是 1.13 - 1.15 需要手动设置GO111MODULE=on, 开启方式如下命令, 如果你的 Go 版本 是 1.16 ~ 最新版 可以忽略以下步骤一
|
||||
# 步骤一、启用 Go Modules 功能
|
||||
go env -w GO111MODULE=on
|
||||
# 步骤二、配置 GOPROXY 环境变量
|
||||
go env -w GOPROXY=https://goproxy.cn,https://goproxy.io,direct
|
||||
|
||||
# 如果嫌弃麻烦,可以使用go generate 编译前自动执行代码, 不过这个不能使用 `Goland` 或者 `Vscode` 的 命令行终端
|
||||
cd server
|
||||
go generate -run "go env -w .*?"
|
||||
|
||||
# 使用如下命令下载swag
|
||||
go get -u github.com/swaggo/swag/cmd/swag
|
||||
``` shell
|
||||
go install github.com/swaggo/swag/cmd/swag@latest
|
||||
```
|
||||
|
||||
#### 2.3.2 生成API文档
|
||||
@@ -314,8 +293,8 @@ swag init
|
||||
- 前端文件参考: [web/src/view/superAdmin/api/api.vue](https://github.com/flipped-aurora/gin-vue-admin/blob/master/web/src/view/superAdmin/api/api.vue)
|
||||
- 后台文件参考: [server/router/sys_api.go](https://github.com/flipped-aurora/gin-vue-admin/blob/master/server/router/sys_api.go)
|
||||
- 多点登录限制:需要在`config.yaml`中把`system`中的`use-multipoint`修改为true(需要自行配置Redis和Config中的Redis参数,测试阶段,有bug请及时反馈)。
|
||||
- 分片长传:提供文件分片上传和大文件分片上传功能示例。
|
||||
- 表单生成器:表单生成器借助 [@form-generator](https://github.com/JakHuang/form-generator) 。
|
||||
- 分片上传:提供文件分片上传和大文件分片上传功能示例。
|
||||
- 表单生成器:表单生成器借助 [@Variant Form](https://github.com/vform666/variant-form) 。
|
||||
- 代码生成器:后台基础逻辑以及简单curd的代码生成器。
|
||||
|
||||
## 6. 知识库
|
||||
@@ -362,7 +341,13 @@ swag init
|
||||
| :---: |
|
||||
| <img width="150" src="http://qmplusimg.henrongyi.top/qrjjz.png">
|
||||
|
||||
添加微信,备注"加入gin-vue-admin交流群"
|
||||
防止广告进群,添加微信,输入以下代码执行结果(请勿转码为string)
|
||||
|
||||
```
|
||||
str := "5Yqg5YWlR1ZB5Lqk5rWB576k"
|
||||
decodeBytes, err := base64.StdEncoding.DecodeString(str)
|
||||
fmt.Println(decodeBytes, err)
|
||||
```
|
||||
|
||||
### [关于我们](https://www.gin-vue-admin.com/about/join.html)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ RUN set -ex \
|
||||
&& echo "LANG=en_US.utf8" > /etc/locale.conf \
|
||||
&& echo "net.core.somaxconn = 1024" >> /etc/sysctl.conf \
|
||||
&& echo "vm.overcommit_memory = 1" >> /etc/sysctl.conf \
|
||||
&& yum -y install yum -y install *epel* \
|
||||
&& yum -y install epel-release \
|
||||
&& yum -y localinstall http://mirrors.ustc.edu.cn/mysql-repo/mysql57-community-release-el7.rpm \
|
||||
&& yum -y install mysql-community-server git redis nginx go npm --nogpgcheck && chmod +x ./entrypoint.sh \
|
||||
&& npm install -g yarn && go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct \
|
||||
|
||||
@@ -17,6 +17,7 @@ type ApiGroup struct {
|
||||
AutoCodeHistoryApi
|
||||
DictionaryDetailApi
|
||||
AuthorityBtnApi
|
||||
SysExportTemplateApi
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -212,3 +212,20 @@ func (s *SystemApiApi) DeleteApisByIds(c *gin.Context) {
|
||||
}
|
||||
response.OkWithMessage("删除成功", c)
|
||||
}
|
||||
|
||||
// FreshCasbin
|
||||
// @Tags SysApi
|
||||
// @Summary 刷新casbin缓存
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Success 200 {object} response.Response{msg=string} "刷新成功"
|
||||
// @Router /api/freshCasbin [get]
|
||||
func (s *SystemApiApi) FreshCasbin(c *gin.Context) {
|
||||
err := casbinService.FreshCasbin()
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("刷新失败!", zap.Error(err))
|
||||
response.FailWithMessage("刷新失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithMessage("刷新成功", c)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
|
||||
systemRes "github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
|
||||
@@ -25,26 +24,31 @@ type AuthorityApi struct{}
|
||||
// @Success 200 {object} response.Response{data=systemRes.SysAuthorityResponse,msg=string} "创建角色,返回包括系统角色详情"
|
||||
// @Router /authority/createAuthority [post]
|
||||
func (a *AuthorityApi) CreateAuthority(c *gin.Context) {
|
||||
var authority system.SysAuthority
|
||||
err := c.ShouldBindJSON(&authority)
|
||||
if err != nil {
|
||||
var authority, authBack system.SysAuthority
|
||||
var err error
|
||||
|
||||
if err = c.ShouldBindJSON(&authority); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
|
||||
err = utils.Verify(authority, utils.AuthorityVerify)
|
||||
if err != nil {
|
||||
if err = utils.Verify(authority, utils.AuthorityVerify); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if authBack, err := authorityService.CreateAuthority(authority); err != nil {
|
||||
|
||||
if authBack, err = authorityService.CreateAuthority(authority); err != nil {
|
||||
global.GVA_LOG.Error("创建失败!", zap.Error(err))
|
||||
response.FailWithMessage("创建失败"+err.Error(), c)
|
||||
} else {
|
||||
_ = menuService.AddMenuAuthority(systemReq.DefaultMenu(), authority.AuthorityId)
|
||||
_ = casbinService.UpdateCasbin(authority.AuthorityId, systemReq.DefaultCasbin())
|
||||
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authBack}, "创建成功", c)
|
||||
return
|
||||
}
|
||||
err = casbinService.FreshCasbin()
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("创建成功,权限刷新失败。", zap.Error(err))
|
||||
response.FailWithMessage("创建成功,权限刷新失败。"+err.Error(), c)
|
||||
return
|
||||
}
|
||||
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authBack}, "创建成功", c)
|
||||
}
|
||||
|
||||
// CopyAuthority
|
||||
@@ -93,22 +97,22 @@ func (a *AuthorityApi) CopyAuthority(c *gin.Context) {
|
||||
// @Router /authority/deleteAuthority [post]
|
||||
func (a *AuthorityApi) DeleteAuthority(c *gin.Context) {
|
||||
var authority system.SysAuthority
|
||||
err := c.ShouldBindJSON(&authority)
|
||||
if err != nil {
|
||||
var err error
|
||||
if err = c.ShouldBindJSON(&authority); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
err = utils.Verify(authority, utils.AuthorityIdVerify)
|
||||
if err != nil {
|
||||
if err = utils.Verify(authority, utils.AuthorityIdVerify); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
err = authorityService.DeleteAuthority(&authority)
|
||||
if err != nil { // 删除角色之前需要判断是否有用户正在使用此角色
|
||||
// 删除角色之前需要判断是否有用户正在使用此角色
|
||||
if err = authorityService.DeleteAuthority(&authority); err != nil {
|
||||
global.GVA_LOG.Error("删除失败!", zap.Error(err))
|
||||
response.FailWithMessage("删除失败"+err.Error(), c)
|
||||
return
|
||||
}
|
||||
_ = casbinService.FreshCasbin()
|
||||
response.OkWithMessage("删除成功", c)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@ type AuthorityBtnApi struct{}
|
||||
func (a *AuthorityBtnApi) GetAuthorityBtn(c *gin.Context) {
|
||||
var req request.SysAuthorityBtnReq
|
||||
err := c.ShouldBindJSON(&req)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
res, err := authorityBtnService.GetAuthorityBtn(req)
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("查询失败!", zap.Error(err))
|
||||
|
||||
@@ -11,8 +11,6 @@ import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"golang.org/x/text/cases"
|
||||
"golang.org/x/text/language"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
@@ -20,8 +18,6 @@ import (
|
||||
|
||||
type AutoCodeApi struct{}
|
||||
|
||||
var caser = cases.Title(language.English)
|
||||
|
||||
// PreviewTemp
|
||||
// @Tags AutoCode
|
||||
// @Summary 预览创建后的代码
|
||||
@@ -39,7 +35,7 @@ func (autoApi *AutoCodeApi) PreviewTemp(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
a.Pretreatment() // 处理go关键字
|
||||
a.PackageT = caser.String(a.Package)
|
||||
a.PackageT = utils.FirstUpper(a.Package)
|
||||
autoCode, err := autoCodeService.PreviewTemp(a)
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("预览失败!", zap.Error(err))
|
||||
@@ -77,7 +73,7 @@ func (autoApi *AutoCodeApi) CreateTemp(c *gin.Context) {
|
||||
apiIds = ids
|
||||
}
|
||||
}
|
||||
a.PackageT = caser.String(a.Package)
|
||||
a.PackageT = utils.FirstUpper(a.Package)
|
||||
err := autoCodeService.CreateTemp(a, apiIds...)
|
||||
if err != nil {
|
||||
if errors.Is(err, system.ErrAutoMove) {
|
||||
@@ -185,7 +181,7 @@ func (autoApi *AutoCodeApi) CreatePackage(c *gin.Context) {
|
||||
err := autoCodeService.CreateAutoCode(&a)
|
||||
if err != nil {
|
||||
|
||||
global.GVA_LOG.Error("创建成功!", zap.Error(err))
|
||||
global.GVA_LOG.Error("创建失败!", zap.Error(err))
|
||||
response.FailWithMessage("创建失败", c)
|
||||
} else {
|
||||
response.OkWithMessage("创建成功", c)
|
||||
@@ -266,7 +262,7 @@ func (autoApi *AutoCodeApi) AutoPlug(c *gin.Context) {
|
||||
// @Produce application/json
|
||||
// @Param plug formData file true "this is a test file"
|
||||
// @Success 200 {object} response.Response{data=[]interface{},msg=string} "安装插件成功"
|
||||
// @Router /autoCode/createPlug [post]
|
||||
// @Router /autoCode/installPlugin [post]
|
||||
func (autoApi *AutoCodeApi) InstallPlugin(c *gin.Context) {
|
||||
header, err := c.FormFile("plug")
|
||||
if err != nil {
|
||||
@@ -296,3 +292,23 @@ func (autoApi *AutoCodeApi) InstallPlugin(c *gin.Context) {
|
||||
"msg": serverStr,
|
||||
}}, c)
|
||||
}
|
||||
|
||||
// PubPlug
|
||||
// @Tags AutoCode
|
||||
// @Summary 打包插件
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body system.SysAutoCode true "打包插件"
|
||||
// @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "打包插件成功"
|
||||
// @Router /autoCode/pubPlug [get]
|
||||
func (autoApi *AutoCodeApi) PubPlug(c *gin.Context) {
|
||||
plugName := c.Query("plugName")
|
||||
zipPath, err := autoCodeService.PubPlug(plugName)
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("打包失败!", zap.Error(err))
|
||||
response.FailWithMessage("打包失败"+err.Error(), c)
|
||||
return
|
||||
}
|
||||
response.OkWithMessage(fmt.Sprintf("打包成功,文件路径为:%s", zipPath), c)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
systemRes "github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
|
||||
@@ -21,9 +23,22 @@ type BaseApi struct{}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Success 200 {object} response.Response{data=systemRes.SysCaptchaResponse,msg=string} "生成验证码,返回包括随机数id,base64,验证码长度"
|
||||
// @Success 200 {object} response.Response{data=systemRes.SysCaptchaResponse,msg=string} "生成验证码,返回包括随机数id,base64,验证码长度,是否开启验证码"
|
||||
// @Router /base/captcha [post]
|
||||
func (b *BaseApi) Captcha(c *gin.Context) {
|
||||
// 判断验证码是否开启
|
||||
openCaptcha := global.GVA_CONFIG.Captcha.OpenCaptcha // 是否开启防爆次数
|
||||
openCaptchaTimeOut := global.GVA_CONFIG.Captcha.OpenCaptchaTimeOut // 缓存超时时间
|
||||
key := c.ClientIP()
|
||||
v, ok := global.BlackCache.Get(key)
|
||||
if !ok {
|
||||
global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
|
||||
}
|
||||
|
||||
var oc bool
|
||||
if openCaptcha == 0 || openCaptcha < interfaceToInt(v) {
|
||||
oc = true
|
||||
}
|
||||
// 字符,公式,验证码配置
|
||||
// 生成默认数字的driver
|
||||
driver := base64Captcha.NewDriverDigit(global.GVA_CONFIG.Captcha.ImgHeight, global.GVA_CONFIG.Captcha.ImgWidth, global.GVA_CONFIG.Captcha.KeyLong, 0.7, 80)
|
||||
@@ -39,5 +54,17 @@ func (b *BaseApi) Captcha(c *gin.Context) {
|
||||
CaptchaId: id,
|
||||
PicPath: b64s,
|
||||
CaptchaLength: global.GVA_CONFIG.Captcha.KeyLong,
|
||||
OpenCaptcha: oc,
|
||||
}, "验证码获取成功", c)
|
||||
}
|
||||
|
||||
// 类型转换
|
||||
func interfaceToInt(v interface{}) (i int) {
|
||||
switch v := v.(type) {
|
||||
case int:
|
||||
i = v
|
||||
default:
|
||||
i = 0
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@ import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -118,31 +116,14 @@ func (s *DictionaryApi) FindSysDictionary(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query request.SysDictionarySearch true "页码, 每页大小, 搜索条件"
|
||||
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取SysDictionary列表,返回包括列表,总数,页码,每页数量"
|
||||
// @Router /sysDictionary/getSysDictionaryList [get]
|
||||
func (s *DictionaryApi) GetSysDictionaryList(c *gin.Context) {
|
||||
var pageInfo request.SysDictionarySearch
|
||||
err := c.ShouldBindQuery(&pageInfo)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
list, total, err := dictionaryService.GetSysDictionaryInfoList(pageInfo)
|
||||
list, err := dictionaryService.GetSysDictionaryInfoList()
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("获取失败!", zap.Error(err))
|
||||
response.FailWithMessage("获取失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithDetailed(response.PageResult{
|
||||
List: list,
|
||||
Total: total,
|
||||
Page: pageInfo.Page,
|
||||
PageSize: pageInfo.PageSize,
|
||||
}, "获取成功", c)
|
||||
response.OkWithDetailed(list, "获取成功", c)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/service"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type SysExportTemplateApi struct {
|
||||
}
|
||||
|
||||
var sysExportTemplateService = service.ServiceGroupApp.SystemServiceGroup.SysExportTemplateService
|
||||
|
||||
// CreateSysExportTemplate 创建导出模板
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 创建导出模板
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body system.SysExportTemplate true "创建导出模板"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
|
||||
// @Router /sysExportTemplate/createSysExportTemplate [post]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) CreateSysExportTemplate(c *gin.Context) {
|
||||
var sysExportTemplate system.SysExportTemplate
|
||||
err := c.ShouldBindJSON(&sysExportTemplate)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
verify := utils.Rules{
|
||||
"Name": {utils.NotEmpty()},
|
||||
}
|
||||
if err := utils.Verify(sysExportTemplate, verify); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if err := sysExportTemplateService.CreateSysExportTemplate(&sysExportTemplate); err != nil {
|
||||
global.GVA_LOG.Error("创建失败!", zap.Error(err))
|
||||
response.FailWithMessage("创建失败", c)
|
||||
} else {
|
||||
response.OkWithMessage("创建成功", c)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteSysExportTemplate 删除导出模板
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 删除导出模板
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body system.SysExportTemplate true "删除导出模板"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
|
||||
// @Router /sysExportTemplate/deleteSysExportTemplate [delete]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) DeleteSysExportTemplate(c *gin.Context) {
|
||||
var sysExportTemplate system.SysExportTemplate
|
||||
err := c.ShouldBindJSON(&sysExportTemplate)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if err := sysExportTemplateService.DeleteSysExportTemplate(sysExportTemplate); err != nil {
|
||||
global.GVA_LOG.Error("删除失败!", zap.Error(err))
|
||||
response.FailWithMessage("删除失败", c)
|
||||
} else {
|
||||
response.OkWithMessage("删除成功", c)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteSysExportTemplateByIds 批量删除导出模板
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 批量删除导出模板
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body request.IdsReq true "批量删除导出模板"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
|
||||
// @Router /sysExportTemplate/deleteSysExportTemplateByIds [delete]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) DeleteSysExportTemplateByIds(c *gin.Context) {
|
||||
var IDS request.IdsReq
|
||||
err := c.ShouldBindJSON(&IDS)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if err := sysExportTemplateService.DeleteSysExportTemplateByIds(IDS); err != nil {
|
||||
global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
|
||||
response.FailWithMessage("批量删除失败", c)
|
||||
} else {
|
||||
response.OkWithMessage("批量删除成功", c)
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateSysExportTemplate 更新导出模板
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 更新导出模板
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body system.SysExportTemplate true "更新导出模板"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
|
||||
// @Router /sysExportTemplate/updateSysExportTemplate [put]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) UpdateSysExportTemplate(c *gin.Context) {
|
||||
var sysExportTemplate system.SysExportTemplate
|
||||
err := c.ShouldBindJSON(&sysExportTemplate)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
verify := utils.Rules{
|
||||
"Name": {utils.NotEmpty()},
|
||||
}
|
||||
if err := utils.Verify(sysExportTemplate, verify); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if err := sysExportTemplateService.UpdateSysExportTemplate(sysExportTemplate); err != nil {
|
||||
global.GVA_LOG.Error("更新失败!", zap.Error(err))
|
||||
response.FailWithMessage("更新失败", c)
|
||||
} else {
|
||||
response.OkWithMessage("更新成功", c)
|
||||
}
|
||||
}
|
||||
|
||||
// FindSysExportTemplate 用id查询导出模板
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 用id查询导出模板
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query system.SysExportTemplate true "用id查询导出模板"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
|
||||
// @Router /sysExportTemplate/findSysExportTemplate [get]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) FindSysExportTemplate(c *gin.Context) {
|
||||
var sysExportTemplate system.SysExportTemplate
|
||||
err := c.ShouldBindQuery(&sysExportTemplate)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if resysExportTemplate, err := sysExportTemplateService.GetSysExportTemplate(sysExportTemplate.ID); err != nil {
|
||||
global.GVA_LOG.Error("查询失败!", zap.Error(err))
|
||||
response.FailWithMessage("查询失败", c)
|
||||
} else {
|
||||
response.OkWithData(gin.H{"resysExportTemplate": resysExportTemplate}, c)
|
||||
}
|
||||
}
|
||||
|
||||
// GetSysExportTemplateList 分页获取导出模板列表
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 分页获取导出模板列表
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query systemReq.SysExportTemplateSearch true "分页获取导出模板列表"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
|
||||
// @Router /sysExportTemplate/getSysExportTemplateList [get]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) GetSysExportTemplateList(c *gin.Context) {
|
||||
var pageInfo systemReq.SysExportTemplateSearch
|
||||
err := c.ShouldBindQuery(&pageInfo)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if list, total, err := sysExportTemplateService.GetSysExportTemplateInfoList(pageInfo); err != nil {
|
||||
global.GVA_LOG.Error("获取失败!", zap.Error(err))
|
||||
response.FailWithMessage("获取失败", c)
|
||||
} else {
|
||||
response.OkWithDetailed(response.PageResult{
|
||||
List: list,
|
||||
Total: total,
|
||||
Page: pageInfo.Page,
|
||||
PageSize: pageInfo.PageSize,
|
||||
}, "获取成功", c)
|
||||
}
|
||||
}
|
||||
|
||||
// ExportExcel 导出表格
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 导出表格
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Router /sysExportTemplate/exportExcel [get]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) ExportExcel(c *gin.Context) {
|
||||
templateID := c.Query("templateID")
|
||||
if templateID == "" {
|
||||
response.FailWithMessage("模板ID不能为空", c)
|
||||
return
|
||||
}
|
||||
if file, name, err := sysExportTemplateService.ExportExcel(templateID); err != nil {
|
||||
global.GVA_LOG.Error("获取失败!", zap.Error(err))
|
||||
response.FailWithMessage("获取失败", c)
|
||||
} else {
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", name+utils.RandomString(6)+".xlsx")) // 对下载的文件重命名
|
||||
c.Header("success", "true")
|
||||
c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", file.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
// ExportExcel 导出表格模板
|
||||
// @Tags SysExportTemplate
|
||||
// @Summary 导出表格模板
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Router /sysExportTemplate/exportExcel [get]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) ExportTemplate(c *gin.Context) {
|
||||
templateID := c.Query("templateID")
|
||||
if templateID == "" {
|
||||
response.FailWithMessage("模板ID不能为空", c)
|
||||
return
|
||||
}
|
||||
if file, name, err := sysExportTemplateService.ExportTemplate(templateID); err != nil {
|
||||
global.GVA_LOG.Error("获取失败!", zap.Error(err))
|
||||
response.FailWithMessage("获取失败", c)
|
||||
} else {
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", name+"模板.xlsx")) // 对下载的文件重命名
|
||||
c.Header("success", "true")
|
||||
c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", file.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
// ExportExcel 导入表格
|
||||
// @Tags SysImportTemplate
|
||||
// @Summary 导入表格
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Router /sysExportTemplate/importExcel [post]
|
||||
func (sysExportTemplateApi *SysExportTemplateApi) ImportExcel(c *gin.Context) {
|
||||
templateID := c.Query("templateID")
|
||||
if templateID == "" {
|
||||
response.FailWithMessage("模板ID不能为空", c)
|
||||
return
|
||||
}
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("文件获取失败!", zap.Error(err))
|
||||
response.FailWithMessage("文件获取失败", c)
|
||||
return
|
||||
}
|
||||
if err := sysExportTemplateService.ImportExcel(templateID, file); err != nil {
|
||||
global.GVA_LOG.Error(err.Error(), zap.Error(err))
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
} else {
|
||||
response.OkWithMessage("导入成功", c)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -19,7 +20,7 @@ type JwtApi struct{}
|
||||
// @Success 200 {object} response.Response{msg=string} "jwt加入黑名单"
|
||||
// @Router /jwt/jsonInBlacklist [post]
|
||||
func (j *JwtApi) JsonInBlacklist(c *gin.Context) {
|
||||
token := c.Request.Header.Get("x-token")
|
||||
token := utils.GetToken(c)
|
||||
jwt := system.JwtBlacklist{Jwt: token}
|
||||
err := jwtService.JsonInBlacklist(jwt)
|
||||
if err != nil {
|
||||
@@ -27,5 +28,6 @@ func (j *JwtApi) JsonInBlacklist(c *gin.Context) {
|
||||
response.FailWithMessage("jwt作废失败", c)
|
||||
return
|
||||
}
|
||||
utils.ClearToken(c)
|
||||
response.OkWithMessage("jwt作废成功", c)
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ func (a *AuthorityMenuApi) GetMenu(c *gin.Context) {
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("获取失败!", zap.Error(err))
|
||||
response.FailWithMessage("获取失败", c)
|
||||
return
|
||||
}
|
||||
if menus == nil {
|
||||
menus = []system.SysMenu{}
|
||||
|
||||
@@ -2,6 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -26,6 +27,8 @@ import (
|
||||
func (b *BaseApi) Login(c *gin.Context) {
|
||||
var l systemReq.Login
|
||||
err := c.ShouldBindJSON(&l)
|
||||
key := c.ClientIP()
|
||||
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
@@ -35,22 +38,39 @@ func (b *BaseApi) Login(c *gin.Context) {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if store.Verify(l.CaptchaId, l.Captcha, true) {
|
||||
|
||||
// 判断验证码是否开启
|
||||
openCaptcha := global.GVA_CONFIG.Captcha.OpenCaptcha // 是否开启防爆次数
|
||||
openCaptchaTimeOut := global.GVA_CONFIG.Captcha.OpenCaptchaTimeOut // 缓存超时时间
|
||||
v, ok := global.BlackCache.Get(key)
|
||||
if !ok {
|
||||
global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
|
||||
}
|
||||
|
||||
var oc bool = openCaptcha == 0 || openCaptcha < interfaceToInt(v)
|
||||
|
||||
if !oc || (l.CaptchaId != "" && l.Captcha != "" && store.Verify(l.CaptchaId, l.Captcha, true)) {
|
||||
u := &system.SysUser{Username: l.Username, Password: l.Password}
|
||||
user, err := userService.Login(u)
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
|
||||
// 验证码次数+1
|
||||
global.BlackCache.Increment(key, 1)
|
||||
response.FailWithMessage("用户名不存在或者密码错误", c)
|
||||
return
|
||||
}
|
||||
if user.Enable != 1 {
|
||||
global.GVA_LOG.Error("登陆失败! 用户被禁止登录!")
|
||||
// 验证码次数+1
|
||||
global.BlackCache.Increment(key, 1)
|
||||
response.FailWithMessage("用户被禁止登录", c)
|
||||
return
|
||||
}
|
||||
b.TokenNext(c, *user)
|
||||
return
|
||||
}
|
||||
// 验证码次数+1
|
||||
global.BlackCache.Increment(key, 1)
|
||||
response.FailWithMessage("验证码错误", c)
|
||||
}
|
||||
|
||||
@@ -71,10 +91,11 @@ func (b *BaseApi) TokenNext(c *gin.Context, user system.SysUser) {
|
||||
return
|
||||
}
|
||||
if !global.GVA_CONFIG.System.UseMultipoint {
|
||||
utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
|
||||
response.OkWithDetailed(systemRes.LoginResponse{
|
||||
User: user,
|
||||
Token: token,
|
||||
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
|
||||
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
|
||||
}, "登录成功", c)
|
||||
return
|
||||
}
|
||||
@@ -85,10 +106,11 @@ func (b *BaseApi) TokenNext(c *gin.Context, user system.SysUser) {
|
||||
response.FailWithMessage("设置登录状态失败", c)
|
||||
return
|
||||
}
|
||||
utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
|
||||
response.OkWithDetailed(systemRes.LoginResponse{
|
||||
User: user,
|
||||
Token: token,
|
||||
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
|
||||
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
|
||||
}, "登录成功", c)
|
||||
} else if err != nil {
|
||||
global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
|
||||
@@ -104,10 +126,11 @@ func (b *BaseApi) TokenNext(c *gin.Context, user system.SysUser) {
|
||||
response.FailWithMessage("设置登录状态失败", c)
|
||||
return
|
||||
}
|
||||
utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
|
||||
response.OkWithDetailed(systemRes.LoginResponse{
|
||||
User: user,
|
||||
Token: token,
|
||||
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
|
||||
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
|
||||
}, "登录成功", c)
|
||||
}
|
||||
}
|
||||
@@ -248,7 +271,8 @@ func (b *BaseApi) SetUserAuthority(c *gin.Context) {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
} else {
|
||||
c.Header("new-token", token)
|
||||
c.Header("new-expires-at", strconv.FormatInt(claims.ExpiresAt, 10))
|
||||
c.Header("new-expires-at", strconv.FormatInt(claims.ExpiresAt.Unix(), 10))
|
||||
utils.SetToken(c, token, int((claims.ExpiresAt.Unix()-time.Now().Unix())/60))
|
||||
response.OkWithMessage("修改成功", c)
|
||||
}
|
||||
}
|
||||
@@ -379,7 +403,7 @@ func (b *BaseApi) SetSelfInfo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
user.ID = utils.GetUserID(c)
|
||||
err = userService.SetUserInfo(system.SysUser{
|
||||
err = userService.SetSelfInfo(system.SysUser{
|
||||
GVA_MODEL: global.GVA_MODEL{
|
||||
ID: user.ID,
|
||||
},
|
||||
|
||||
@@ -23,6 +23,22 @@ redis:
|
||||
addr: 177.7.0.14:6379
|
||||
password: ""
|
||||
|
||||
# mongo configuration
|
||||
mongo:
|
||||
coll: ''
|
||||
options: ''
|
||||
database: ''
|
||||
username: ''
|
||||
password: ''
|
||||
min-pool-size: 0
|
||||
max-pool-size: 100
|
||||
socket-timeout-ms: 0
|
||||
connect-timeout-ms: 0
|
||||
is-zap: false
|
||||
hosts:
|
||||
- host: ''
|
||||
port: ''
|
||||
|
||||
# email configuration
|
||||
email:
|
||||
to: xxx@qq.com
|
||||
@@ -40,6 +56,7 @@ system:
|
||||
db-type: mysql
|
||||
oss-type: local # 控制oss选择走本地还是 七牛等其他仓 自行增加其他oss仓可以在 server/utils/upload/upload.go 中 NewOss函数配置
|
||||
use-redis: false # 使用redis
|
||||
use-mongo: false # 使用mongo
|
||||
use-multipoint: false
|
||||
# IP限制次数 一个小时15000次
|
||||
iplimit-count: 15000
|
||||
@@ -51,6 +68,8 @@ captcha:
|
||||
key-long: 6
|
||||
img-width: 240
|
||||
img-height: 80
|
||||
open-captcha: 0 # 0代表一直开启,大于0代表限制次数
|
||||
open-captcha-timeout: 3600 # open-captcha大于0时才生效
|
||||
|
||||
# mysql connect configuration
|
||||
# 未初始化之前请勿手动修改数据库信息!!!如果一定要手动初始化请看(https://gin-vue-admin.com/docs/first_master)
|
||||
@@ -185,7 +204,7 @@ Timer:
|
||||
interval: 168h
|
||||
|
||||
# 跨域配置
|
||||
# 需要配合 server/initialize/router.go#L32 使用
|
||||
# 需要配合 server/initialize/router.go -> `Router.Use(middleware.CorsByRules())` 使用
|
||||
cors:
|
||||
mode: whitelist # 放行模式: allow-all, 放行全部; whitelist, 白名单模式, 来自白名单内域名的请求添加 cors 头; strict-whitelist 严格白名单模式, 白名单外的请求一律拒绝
|
||||
whitelist:
|
||||
|
||||
+60
-19
@@ -23,6 +23,23 @@ redis:
|
||||
addr: 127.0.0.1:6379
|
||||
password: ""
|
||||
|
||||
# mongo configuration
|
||||
mongo:
|
||||
coll: ''
|
||||
options: ''
|
||||
database: ''
|
||||
username: ''
|
||||
password: ''
|
||||
auth-source: ''
|
||||
min-pool-size: 0
|
||||
max-pool-size: 100
|
||||
socket-timeout-ms: 0
|
||||
connect-timeout-ms: 0
|
||||
is-zap: false
|
||||
hosts:
|
||||
- host: ''
|
||||
port: ''
|
||||
|
||||
# email configuration
|
||||
email:
|
||||
to: xxx@qq.com
|
||||
@@ -35,22 +52,27 @@ email:
|
||||
|
||||
# system configuration
|
||||
system:
|
||||
env: public # Change to "develop" to skip authentication for development mode
|
||||
env: local # 修改为public可以关闭路由日志输出
|
||||
addr: 8888
|
||||
db-type: mysql
|
||||
oss-type: local # 控制oss选择走本地还是 七牛等其他仓 自行增加其他oss仓可以在 server/utils/upload/upload.go 中 NewOss函数配置
|
||||
use-redis: false # 使用redis
|
||||
oss-type: local # 控制oss选择走本地还是 七牛等其他仓 自行增加其他oss仓可以在 server/utils/upload/upload.go 中 NewOss函数配置
|
||||
use-redis: false # 使用redis
|
||||
use-mongo: false # 使用mongo
|
||||
use-multipoint: false
|
||||
# IP限制次数 一个小时15000次
|
||||
iplimit-count: 15000
|
||||
# IP限制一个小时
|
||||
iplimit-time: 3600
|
||||
# 路由全局前缀
|
||||
router-prefix: ""
|
||||
|
||||
# captcha configuration
|
||||
captcha:
|
||||
key-long: 6
|
||||
img-width: 240
|
||||
img-height: 80
|
||||
open-captcha: 0 # 0代表一直开启,大于0代表限制次数
|
||||
open-captcha-timeout: 3600 # open-captcha大于0时才生效
|
||||
|
||||
# mysql connect configuration
|
||||
# 未初始化之前请勿手动修改数据库信息!!!如果一定要手动初始化请看(https://gin-vue-admin.com/docs/first_master)
|
||||
@@ -79,10 +101,42 @@ pgsql:
|
||||
max-open-conns: 100
|
||||
log-mode: ""
|
||||
log-zap: false
|
||||
|
||||
oracle:
|
||||
path: ""
|
||||
port: ""
|
||||
config: ""
|
||||
db-name: ""
|
||||
username: ""
|
||||
password: ""
|
||||
max-idle-conns: 10
|
||||
max-open-conns: 100
|
||||
log-mode: ""
|
||||
log-zap: false
|
||||
mssql:
|
||||
path: ""
|
||||
port: ""
|
||||
config: ""
|
||||
db-name: ""
|
||||
username: ""
|
||||
password: ""
|
||||
max-idle-conns: 10
|
||||
max-open-conns: 100
|
||||
log-mode: ""
|
||||
log-zap: false
|
||||
sqlite:
|
||||
path: ""
|
||||
port: ""
|
||||
config: ""
|
||||
db-name: ""
|
||||
username: ""
|
||||
password: ""
|
||||
max-idle-conns: 10
|
||||
max-open-conns: 100
|
||||
log-mode: ""
|
||||
log-zap: false
|
||||
db-list:
|
||||
- disable: true # 是否禁用
|
||||
type: "" # 数据库的类型,目前支持mysql、pgsql
|
||||
type: "" # 数据库的类型,目前支持mysql、pgsql、mssql、oracle
|
||||
alias-name: "" # 数据库的名称,注意: alias-name 需要在db-list中唯一
|
||||
path: ""
|
||||
port: ""
|
||||
@@ -95,7 +149,6 @@ db-list:
|
||||
log-mode: ""
|
||||
log-zap: false
|
||||
|
||||
|
||||
# local configuration
|
||||
local:
|
||||
path: uploads/file
|
||||
@@ -172,20 +225,8 @@ hua-wei-obs:
|
||||
excel:
|
||||
dir: ./resource/excel/
|
||||
|
||||
# timer task db clear table
|
||||
Timer:
|
||||
start: true
|
||||
spec: "@daily" # 定时任务详细配置参考 https://pkg.go.dev/github.com/robfig/cron/v3
|
||||
detail:
|
||||
- tableName: sys_operation_records
|
||||
compareField: created_at
|
||||
interval: 2160h
|
||||
- tableName: jwt_blacklists
|
||||
compareField: created_at
|
||||
interval: 168h
|
||||
|
||||
# 跨域配置
|
||||
# 需要配合 server/initialize/router.go#L32 使用
|
||||
# 需要配合 server/initialize/router.go -> `Router.Use(middleware.CorsByRules())` 使用
|
||||
cors:
|
||||
mode: strict-whitelist # 放行模式: allow-all, 放行全部; whitelist, 白名单模式, 来自白名单内域名的请求添加 cors 头; strict-whitelist 严格白名单模式, 白名单外的请求一律拒绝
|
||||
whitelist:
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
package config
|
||||
|
||||
type Autocode struct {
|
||||
TransferRestart bool `mapstructure:"transfer-restart" json:"transfer-restart" yaml:"transfer-restart"`
|
||||
Root string `mapstructure:"root" json:"root" yaml:"root"`
|
||||
SModel string `mapstructure:"server-model" json:"server-model" yaml:"server-model"`
|
||||
SRouter string `mapstructure:"server-router" json:"server-router" yaml:"server-router"`
|
||||
Server string `mapstructure:"server" json:"server" yaml:"server"`
|
||||
SApi string `mapstructure:"server-api" json:"server-api" yaml:"server-api"`
|
||||
SPlug string `mapstructure:"server-plug" json:"server-plug" yaml:"server-plug"`
|
||||
SInitialize string `mapstructure:"server-initialize" json:"server-initialize" yaml:"server-initialize"`
|
||||
SModel string `mapstructure:"server-model" json:"server-model" yaml:"server-model"`
|
||||
SRequest string `mapstructure:"server-request" json:"server-request" yaml:"server-request"`
|
||||
SRouter string `mapstructure:"server-router" json:"server-router" yaml:"server-router"`
|
||||
SService string `mapstructure:"server-service" json:"server-service" yaml:"server-service"`
|
||||
Root string `mapstructure:"root" json:"root" yaml:"root"`
|
||||
WTable string `mapstructure:"web-table" json:"web-table" yaml:"web-table"`
|
||||
Web string `mapstructure:"web" json:"web" yaml:"web"`
|
||||
SService string `mapstructure:"server-service" json:"server-service" yaml:"server-service"`
|
||||
SRequest string `mapstructure:"server-request" json:"server-request" yaml:"server-request"`
|
||||
WApi string `mapstructure:"web-api" json:"web-api" yaml:"web-api"`
|
||||
WForm string `mapstructure:"web-form" json:"web-form" yaml:"web-form"`
|
||||
WTable string `mapstructure:"web-table" json:"web-table" yaml:"web-table"`
|
||||
TransferRestart bool `mapstructure:"transfer-restart" json:"transfer-restart" yaml:"transfer-restart"`
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package config
|
||||
|
||||
type Captcha struct {
|
||||
KeyLong int `mapstructure:"key-long" json:"key-long" yaml:"key-long"` // 验证码长度
|
||||
ImgWidth int `mapstructure:"img-width" json:"img-width" yaml:"img-width"` // 验证码宽度
|
||||
ImgHeight int `mapstructure:"img-height" json:"img-height" yaml:"img-height"` // 验证码高度
|
||||
KeyLong int `mapstructure:"key-long" json:"key-long" yaml:"key-long"` // 验证码长度
|
||||
ImgWidth int `mapstructure:"img-width" json:"img-width" yaml:"img-width"` // 验证码宽度
|
||||
ImgHeight int `mapstructure:"img-height" json:"img-height" yaml:"img-height"` // 验证码高度
|
||||
OpenCaptcha int `mapstructure:"open-captcha" json:"open-captcha" yaml:"open-captcha"` // 防爆破验证码开启此数,0代表每次登录都需要验证码,其他数字代表错误密码此数,如3代表错误三次后出现验证码
|
||||
OpenCaptchaTimeOut int `mapstructure:"open-captcha-timeout" json:"open-captcha-timeout" yaml:"open-captcha-timeout"` // 防爆破验证码超时时间,单位:s(秒)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ type Server struct {
|
||||
JWT JWT `mapstructure:"jwt" json:"jwt" yaml:"jwt"`
|
||||
Zap Zap `mapstructure:"zap" json:"zap" yaml:"zap"`
|
||||
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
|
||||
Mongo Mongo `mapstructure:"mongo" json:"mongo" yaml:"mongo"`
|
||||
Email Email `mapstructure:"email" json:"email" yaml:"email"`
|
||||
System System `mapstructure:"system" json:"system" yaml:"system"`
|
||||
Captcha Captcha `mapstructure:"captcha" json:"captcha" yaml:"captcha"`
|
||||
@@ -11,8 +12,10 @@ type Server struct {
|
||||
AutoCode Autocode `mapstructure:"autocode" json:"autocode" yaml:"autocode"`
|
||||
// gorm
|
||||
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
|
||||
Mssql Mssql `mapstructure:"mssql" json:"mssql" yaml:"mssql"`
|
||||
Pgsql Pgsql `mapstructure:"pgsql" json:"pgsql" yaml:"pgsql"`
|
||||
Oracle Oracle `mapstructure:"oracle" json:"oracle" yaml:"oracle"`
|
||||
Sqlite Sqlite `mapstructure:"sqlite" json:"sqlite" yaml:"sqlite"`
|
||||
DBList []SpecializedDB `mapstructure:"db-list" json:"db-list" yaml:"db-list"`
|
||||
// oss
|
||||
Local Local `mapstructure:"local" json:"local" yaml:"local"`
|
||||
@@ -23,7 +26,6 @@ type Server struct {
|
||||
AwsS3 AwsS3 `mapstructure:"aws-s3" json:"aws-s3" yaml:"aws-s3"`
|
||||
|
||||
Excel Excel `mapstructure:"excel" json:"excel" yaml:"excel"`
|
||||
Timer Timer `mapstructure:"timer" json:"timer" yaml:"timer"`
|
||||
|
||||
// 跨域配置
|
||||
Cors CORS `mapstructure:"cors" json:"cors" yaml:"cors"`
|
||||
|
||||
+10
-10
@@ -9,24 +9,24 @@ type DsnProvider interface {
|
||||
|
||||
// GeneralDB 也被 Pgsql 和 Mysql 原样使用
|
||||
type GeneralDB struct {
|
||||
Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址:端口
|
||||
Port string `mapstructure:"port" json:"port" yaml:"port"` //:端口
|
||||
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
|
||||
Dbname string `mapstructure:"db-name" json:"db-name" yaml:"db-name"` // 数据库名
|
||||
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
|
||||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
|
||||
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` //全局表前缀,单独定义TableName则不生效
|
||||
Singular bool `mapstructure:"singular" json:"singular" yaml:"singular"` //是否开启全局禁用复数,true表示开启
|
||||
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"`
|
||||
Port string `mapstructure:"port" json:"port" yaml:"port"`
|
||||
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
|
||||
Dbname string `mapstructure:"db-name" json:"db-name" yaml:"db-name"` // 数据库名
|
||||
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库密码
|
||||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
|
||||
Path string `mapstructure:"path" json:"path" yaml:"path"`
|
||||
Engine string `mapstructure:"engine" json:"engine" yaml:"engine" default:"InnoDB"` //数据库引擎,默认InnoDB
|
||||
LogMode string `mapstructure:"log-mode" json:"log-mode" yaml:"log-mode"` // 是否开启Gorm全局日志
|
||||
MaxIdleConns int `mapstructure:"max-idle-conns" json:"max-idle-conns" yaml:"max-idle-conns"` // 空闲中的最大连接数
|
||||
MaxOpenConns int `mapstructure:"max-open-conns" json:"max-open-conns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
|
||||
LogMode string `mapstructure:"log-mode" json:"log-mode" yaml:"log-mode"` // 是否开启Gorm全局日志
|
||||
Singular bool `mapstructure:"singular" json:"singular" yaml:"singular"` //是否开启全局禁用复数,true表示开启
|
||||
LogZap bool `mapstructure:"log-zap" json:"log-zap" yaml:"log-zap"` // 是否通过zap写入日志文件
|
||||
}
|
||||
|
||||
type SpecializedDB struct {
|
||||
Disable bool `mapstructure:"disable" json:"disable" yaml:"disable"`
|
||||
Type string `mapstructure:"type" json:"type" yaml:"type"`
|
||||
AliasName string `mapstructure:"alias-name" json:"alias-name" yaml:"alias-name"`
|
||||
GeneralDB `yaml:",inline" mapstructure:",squash"`
|
||||
Disable bool `mapstructure:"disable" json:"disable" yaml:"disable"`
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package config
|
||||
|
||||
type Email struct {
|
||||
To string `mapstructure:"to" json:"to" yaml:"to"` // 收件人:多个以英文逗号分隔
|
||||
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口
|
||||
From string `mapstructure:"from" json:"from" yaml:"from"` // 收件人
|
||||
Host string `mapstructure:"host" json:"host" yaml:"host"` // 服务器地址
|
||||
IsSSL bool `mapstructure:"is-ssl" json:"is-ssl" yaml:"is-ssl"` // 是否SSL
|
||||
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` // 密钥
|
||||
Nickname string `mapstructure:"nickname" json:"nickname" yaml:"nickname"` // 昵称
|
||||
To string `mapstructure:"to" json:"to" yaml:"to"` // 收件人:多个以英文逗号分隔 例:a@qq.com b@qq.com 正式开发中请把此项目作为参数使用
|
||||
From string `mapstructure:"from" json:"from" yaml:"from"` // 发件人 你自己要发邮件的邮箱
|
||||
Host string `mapstructure:"host" json:"host" yaml:"host"` // 服务器地址 例如 smtp.qq.com 请前往QQ或者你要发邮件的邮箱查看其smtp协议
|
||||
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` // 密钥 用于登录的密钥 最好不要用邮箱密码 去邮箱smtp申请一个用于登录的密钥
|
||||
Nickname string `mapstructure:"nickname" json:"nickname" yaml:"nickname"` // 昵称 发件人昵称 通常为自己的邮箱
|
||||
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口 请前往QQ或者你要发邮件的邮箱查看其smtp协议 大多为 465
|
||||
IsSSL bool `mapstructure:"is-ssl" json:"is-ssl" yaml:"is-ssl"` // 是否SSL 是否开启SSL
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type Mssql struct {
|
||||
GeneralDB `yaml:",inline" mapstructure:",squash"`
|
||||
}
|
||||
//dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
|
||||
func (m *Mssql) Dsn() string {
|
||||
return "sqlserver://" + m.Username + ":" + m.Password + "@" + m.Path + ":" + m.Port + "?database=" + m.Dbname + "&encrypt=disable"
|
||||
}
|
||||
|
||||
func (m *Mssql) GetLogMode() string {
|
||||
return m.LogMode
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type Sqlite struct {
|
||||
GeneralDB `yaml:",inline" mapstructure:",squash"`
|
||||
}
|
||||
|
||||
func (s *Sqlite) Dsn() string {
|
||||
return filepath.Join(s.Path, s.Dbname+".db")
|
||||
}
|
||||
|
||||
func (s *Sqlite) GetLogMode() string {
|
||||
return s.LogMode
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Mongo struct {
|
||||
Coll string `json:"coll" yaml:"coll" mapstructure:"coll"` // collection name
|
||||
Options string `json:"options" yaml:"options" mapstructure:"options"` // mongodb options
|
||||
Database string `json:"database" yaml:"database" mapstructure:"database"` // database name
|
||||
Username string `json:"username" yaml:"username" mapstructure:"username"` // 用户名
|
||||
Password string `json:"password" yaml:"password" mapstructure:"password"` // 密码
|
||||
AuthSource string `json:"auth-source" yaml:"auth-source" mapstructure:"auth-source"` // 验证数据库
|
||||
MinPoolSize uint64 `json:"min-pool-size" yaml:"min-pool-size" mapstructure:"min-pool-size"` // 最小连接池
|
||||
MaxPoolSize uint64 `json:"max-pool-size" yaml:"max-pool-size" mapstructure:"max-pool-size"` // 最大连接池
|
||||
SocketTimeoutMs int64 `json:"socket-timeout-ms" yaml:"socket-timeout-ms" mapstructure:"socket-timeout-ms"` // socket超时时间
|
||||
ConnectTimeoutMs int64 `json:"connect-timeout-ms" yaml:"connect-timeout-ms" mapstructure:"connect-timeout-ms"` // 连接超时时间
|
||||
IsZap bool `json:"is-zap" yaml:"is-zap" mapstructure:"is-zap"` // 是否开启zap日志
|
||||
Hosts []*MongoHost `json:"hosts" yaml:"hosts" mapstructure:"hosts"` // 主机列表
|
||||
}
|
||||
|
||||
type MongoHost struct {
|
||||
Host string `json:"host" yaml:"host" mapstructure:"host"` // ip地址
|
||||
Port string `json:"port" yaml:"port" mapstructure:"port"` // 端口
|
||||
}
|
||||
|
||||
// Uri .
|
||||
func (x *Mongo) Uri() string {
|
||||
length := len(x.Hosts)
|
||||
hosts := make([]string, 0, length)
|
||||
for i := 0; i < length; i++ {
|
||||
if x.Hosts[i].Host != "" && x.Hosts[i].Port != "" {
|
||||
hosts = append(hosts, x.Hosts[i].Host+":"+x.Hosts[i].Port)
|
||||
}
|
||||
}
|
||||
if x.Options != "" {
|
||||
return fmt.Sprintf("mongodb://%s/%s?%s", strings.Join(hosts, ","), x.Database, x.Options)
|
||||
}
|
||||
return fmt.Sprintf("mongodb://%s/%s", strings.Join(hosts, ","), x.Database)
|
||||
}
|
||||
@@ -4,10 +4,10 @@ type AwsS3 struct {
|
||||
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"`
|
||||
Region string `mapstructure:"region" json:"region" yaml:"region"`
|
||||
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint"`
|
||||
S3ForcePathStyle bool `mapstructure:"s3-force-path-style" json:"s3-force-path-style" yaml:"s3-force-path-style"`
|
||||
DisableSSL bool `mapstructure:"disable-ssl" json:"disable-ssl" yaml:"disable-ssl"`
|
||||
SecretID string `mapstructure:"secret-id" json:"secret-id" yaml:"secret-id"`
|
||||
SecretKey string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"`
|
||||
BaseURL string `mapstructure:"base-url" json:"base-url" yaml:"base-url"`
|
||||
PathPrefix string `mapstructure:"path-prefix" json:"path-prefix" yaml:"path-prefix"`
|
||||
S3ForcePathStyle bool `mapstructure:"s3-force-path-style" json:"s3-force-path-style" yaml:"s3-force-path-style"`
|
||||
DisableSSL bool `mapstructure:"disable-ssl" json:"disable-ssl" yaml:"disable-ssl"`
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ type Qiniu struct {
|
||||
Zone string `mapstructure:"zone" json:"zone" yaml:"zone"` // 存储区域
|
||||
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"` // 空间名称
|
||||
ImgPath string `mapstructure:"img-path" json:"img-path" yaml:"img-path"` // CDN加速域名
|
||||
UseHTTPS bool `mapstructure:"use-https" json:"use-https" yaml:"use-https"` // 是否使用https
|
||||
AccessKey string `mapstructure:"access-key" json:"access-key" yaml:"access-key"` // 秘钥AK
|
||||
SecretKey string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"` // 秘钥SK
|
||||
UseHTTPS bool `mapstructure:"use-https" json:"use-https" yaml:"use-https"` // 是否使用https
|
||||
UseCdnDomains bool `mapstructure:"use-cdn-domains" json:"use-cdn-domains" yaml:"use-cdn-domains"` // 上传是否使用CDN上传加速
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package config
|
||||
|
||||
type Redis struct {
|
||||
DB int `mapstructure:"db" json:"db" yaml:"db"` // redis的哪个数据库
|
||||
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"` // 服务器地址:端口
|
||||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码
|
||||
DB int `mapstructure:"db" json:"db" yaml:"db"` // redis的哪个数据库
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package config
|
||||
|
||||
type System struct {
|
||||
Env string `mapstructure:"env" json:"env" yaml:"env"` // 环境值
|
||||
Addr int `mapstructure:"addr" json:"addr" yaml:"addr"` // 端口值
|
||||
DbType string `mapstructure:"db-type" json:"db-type" yaml:"db-type"` // 数据库类型:mysql(默认)|sqlite|sqlserver|postgresql
|
||||
OssType string `mapstructure:"oss-type" json:"oss-type" yaml:"oss-type"` // Oss类型
|
||||
UseMultipoint bool `mapstructure:"use-multipoint" json:"use-multipoint" yaml:"use-multipoint"` // 多点登录拦截
|
||||
UseRedis bool `mapstructure:"use-redis" json:"use-redis" yaml:"use-redis"` // 使用redis
|
||||
Env string `mapstructure:"env" json:"env" yaml:"env"` // 环境值
|
||||
DbType string `mapstructure:"db-type" json:"db-type" yaml:"db-type"` // 数据库类型:mysql(默认)|sqlite|sqlserver|postgresql
|
||||
OssType string `mapstructure:"oss-type" json:"oss-type" yaml:"oss-type"` // Oss类型
|
||||
RouterPrefix string `mapstructure:"router-prefix" json:"router-prefix" yaml:"router-prefix"`
|
||||
Addr int `mapstructure:"addr" json:"addr" yaml:"addr"` // 端口值
|
||||
LimitCountIP int `mapstructure:"iplimit-count" json:"iplimit-count" yaml:"iplimit-count"`
|
||||
LimitTimeIP int `mapstructure:"iplimit-time" json:"iplimit-time" yaml:"iplimit-time"`
|
||||
UseMultipoint bool `mapstructure:"use-multipoint" json:"use-multipoint" yaml:"use-multipoint"` // 多点登录拦截
|
||||
UseRedis bool `mapstructure:"use-redis" json:"use-redis" yaml:"use-redis"` // 使用redis
|
||||
UseMongo bool `mapstructure:"use-mongo" json:"use-mongo" yaml:"use-mongo"` // 使用mongo
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package config
|
||||
|
||||
type Timer struct {
|
||||
Start bool `mapstructure:"start" json:"start" yaml:"start"` // 是否启用
|
||||
Spec string `mapstructure:"spec" json:"spec" yaml:"spec"` // CRON表达式
|
||||
WithSeconds bool `mapstructure:"with_seconds" json:"with_seconds" yaml:"with_seconds"` // 是否精确到秒
|
||||
Detail []Detail `mapstructure:"detail" json:"detail" yaml:"detail"`
|
||||
}
|
||||
|
||||
type Detail struct {
|
||||
TableName string `mapstructure:"tableName" json:"tableName" yaml:"tableName"` // 需要清理的表名
|
||||
CompareField string `mapstructure:"compareField" json:"compareField" yaml:"compareField"` // 需要比较时间的字段
|
||||
Interval string `mapstructure:"interval" json:"interval" yaml:"interval"` // 时间间隔
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func (z *Zap) TransportLevel() zapcore.Level {
|
||||
case "warn":
|
||||
return zapcore.WarnLevel
|
||||
case "error":
|
||||
return zapcore.WarnLevel
|
||||
return zapcore.ErrorLevel
|
||||
case "dpanic":
|
||||
return zapcore.DPanicLevel
|
||||
case "panic":
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Cutter struct {
|
||||
level string // 日志级别(debug, info, warn, error, dpanic, panic, fatal)
|
||||
format string // 时间格式(2006-01-02)
|
||||
Director string // 日志文件夹
|
||||
file *os.File // 文件句柄
|
||||
mutex *sync.RWMutex // 读写锁
|
||||
}
|
||||
|
||||
type CutterOption func(*Cutter)
|
||||
|
||||
// WithCutterFormat 设置时间格式
|
||||
func WithCutterFormat(format string) CutterOption {
|
||||
return func(c *Cutter) {
|
||||
c.format = format
|
||||
}
|
||||
}
|
||||
|
||||
func NewCutter(director string, level string, options ...CutterOption) *Cutter {
|
||||
rotate := &Cutter{
|
||||
level: level,
|
||||
Director: director,
|
||||
mutex: new(sync.RWMutex),
|
||||
}
|
||||
for i := 0; i < len(options); i++ {
|
||||
options[i](rotate)
|
||||
}
|
||||
return rotate
|
||||
}
|
||||
|
||||
// Write satisfies the io.Writer interface. It writes to the
|
||||
// appropriate file handle that is currently being used.
|
||||
// If we have reached rotation time, the target file gets
|
||||
// automatically rotated, and also purged if necessary.
|
||||
func (c *Cutter) Write(bytes []byte) (n int, err error) {
|
||||
c.mutex.Lock()
|
||||
defer func() {
|
||||
if c.file != nil {
|
||||
_ = c.file.Close()
|
||||
c.file = nil
|
||||
}
|
||||
c.mutex.Unlock()
|
||||
}()
|
||||
var business string
|
||||
if strings.Contains(string(bytes), "business") {
|
||||
var compile *regexp.Regexp
|
||||
compile, err = regexp.Compile(`{"business": "([^,]+)"}`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if compile.Match(bytes) {
|
||||
finds := compile.FindSubmatch(bytes)
|
||||
business = string(finds[len(finds)-1])
|
||||
bytes = compile.ReplaceAll(bytes, []byte(""))
|
||||
}
|
||||
compile, err = regexp.Compile(`"business": "([^,]+)"`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if compile.Match(bytes) {
|
||||
finds := compile.FindSubmatch(bytes)
|
||||
business = string(finds[len(finds)-1])
|
||||
bytes = compile.ReplaceAll(bytes, []byte(""))
|
||||
}
|
||||
}
|
||||
format := time.Now().Format(c.format)
|
||||
formats := make([]string, 0, 4)
|
||||
formats = append(formats, c.Director)
|
||||
if format != "" {
|
||||
formats = append(formats, format)
|
||||
}
|
||||
if business != "" {
|
||||
formats = append(formats, business)
|
||||
}
|
||||
formats = append(formats, c.level+".log")
|
||||
filename := filepath.Join(formats...)
|
||||
dirname := filepath.Dir(filename)
|
||||
err = os.MkdirAll(dirname, 0755)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.file, err = os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return c.file.Write(bytes)
|
||||
}
|
||||
@@ -2,11 +2,8 @@ package internal
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"os"
|
||||
"path"
|
||||
"time"
|
||||
)
|
||||
|
||||
var FileRotatelogs = new(fileRotatelogs)
|
||||
@@ -15,15 +12,10 @@ type fileRotatelogs struct{}
|
||||
|
||||
// GetWriteSyncer 获取 zapcore.WriteSyncer
|
||||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||||
func (r *fileRotatelogs) GetWriteSyncer(level string) (zapcore.WriteSyncer, error) {
|
||||
fileWriter, err := rotatelogs.New(
|
||||
path.Join(global.GVA_CONFIG.Zap.Director, "%Y-%m-%d", level+".log"),
|
||||
rotatelogs.WithClock(rotatelogs.Local),
|
||||
rotatelogs.WithMaxAge(time.Duration(global.GVA_CONFIG.Zap.MaxAge)*24*time.Hour), // 日志留存时间
|
||||
rotatelogs.WithRotationTime(time.Hour*24),
|
||||
)
|
||||
func (r *fileRotatelogs) GetWriteSyncer(level string) zapcore.WriteSyncer {
|
||||
fileWriter := NewCutter(global.GVA_CONFIG.Zap.Director, level, WithCutterFormat("2006-01-02"))
|
||||
if global.GVA_CONFIG.Zap.LogInConsole {
|
||||
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err
|
||||
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter))
|
||||
}
|
||||
return zapcore.AddSync(fileWriter), err
|
||||
return zapcore.AddSync(fileWriter)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
@@ -42,12 +41,7 @@ func (z *_zap) GetEncoderConfig() zapcore.EncoderConfig {
|
||||
// GetEncoderCore 获取Encoder的 zapcore.Core
|
||||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||||
func (z *_zap) GetEncoderCore(l zapcore.Level, level zap.LevelEnablerFunc) zapcore.Core {
|
||||
writer, err := FileRotatelogs.GetWriteSyncer(l.String()) // 使用file-rotatelogs进行日志分割
|
||||
if err != nil {
|
||||
fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
|
||||
return nil
|
||||
}
|
||||
|
||||
writer := FileRotatelogs.GetWriteSyncer(l.String()) // 日志分割
|
||||
return zapcore.NewCore(z.GetEncoder(), writer, level)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,12 @@ func RunWindowsServer() {
|
||||
// 初始化redis服务
|
||||
initialize.Redis()
|
||||
}
|
||||
|
||||
if global.GVA_CONFIG.System.UseMongo {
|
||||
err := initialize.Mongo.Initialization()
|
||||
if err != nil {
|
||||
zap.L().Error(fmt.Sprintf("%+v", err))
|
||||
}
|
||||
}
|
||||
// 从db加载jwt数据
|
||||
if global.GVA_DB != nil {
|
||||
system.LoadAll()
|
||||
@@ -37,7 +42,7 @@ func RunWindowsServer() {
|
||||
|
||||
fmt.Printf(`
|
||||
欢迎使用 gin-vue-admin
|
||||
当前版本:v2.5.5
|
||||
当前版本:v2.6.0
|
||||
加群方式:微信号:shouzi_1994 QQ群:622360840
|
||||
插件市场:https://plugin.gin-vue-admin.com
|
||||
GVA讨论社区:https://support.qq.com/products/371961
|
||||
|
||||
@@ -65,7 +65,7 @@ func Viper(path ...string) *viper.Viper {
|
||||
}
|
||||
})
|
||||
if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
|
||||
fmt.Println(err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// root 适配性 根据root位置去找到对应迁移位置,保证root路径有效
|
||||
|
||||
+706
-528
File diff suppressed because it is too large
Load Diff
+694
-479
File diff suppressed because it is too large
Load Diff
+478
-328
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"github.com/qiniu/qmgo"
|
||||
"sync"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils/timer"
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/spf13/viper"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -21,6 +22,7 @@ var (
|
||||
GVA_DB *gorm.DB
|
||||
GVA_DBList map[string]*gorm.DB
|
||||
GVA_REDIS *redis.Client
|
||||
GVA_MONGO *qmgo.QmgoClient
|
||||
GVA_CONFIG config.Server
|
||||
GVA_VP *viper.Viper
|
||||
// GVA_LOG *oplogging.Logger
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
type GVA_MODEL struct {
|
||||
ID uint `gorm:"primarykey"` // 主键ID
|
||||
ID uint `gorm:"primarykey" json:"ID"` // 主键ID
|
||||
CreatedAt time.Time // 创建时间
|
||||
UpdatedAt time.Time // 更新时间
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` // 删除时间
|
||||
|
||||
+98
-89
@@ -1,133 +1,142 @@
|
||||
module github.com/flipped-aurora/gin-vue-admin/server
|
||||
|
||||
go 1.18
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
|
||||
github.com/aliyun/aliyun-oss-go-sdk v2.1.6+incompatible
|
||||
github.com/aws/aws-sdk-go v1.42.27
|
||||
github.com/casbin/casbin/v2 v2.51.0
|
||||
github.com/casbin/gorm-adapter/v3 v3.7.3
|
||||
github.com/aliyun/aliyun-oss-go-sdk v2.2.7+incompatible
|
||||
github.com/aws/aws-sdk-go v1.44.307
|
||||
github.com/casbin/casbin/v2 v2.71.1
|
||||
github.com/casbin/gorm-adapter/v3 v3.18.0
|
||||
github.com/flipped-aurora/ws v1.0.2
|
||||
github.com/fsnotify/fsnotify v1.4.9
|
||||
github.com/fsnotify/fsnotify v1.6.0
|
||||
github.com/fvbock/endless v0.0.0-20170109170031-447134032cb6
|
||||
github.com/gin-gonic/gin v1.7.0
|
||||
github.com/go-redis/redis/v8 v8.11.4
|
||||
github.com/go-sql-driver/mysql v1.6.0
|
||||
github.com/golang-jwt/jwt/v4 v4.3.0
|
||||
github.com/gookit/color v1.3.1
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/glebarez/sqlite v1.8.0
|
||||
github.com/go-sql-driver/mysql v1.7.1
|
||||
github.com/gofrs/uuid/v5 v5.0.0
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0
|
||||
github.com/gookit/color v1.5.4
|
||||
github.com/huaweicloud/huaweicloud-sdk-go-obs v3.21.8+incompatible
|
||||
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84
|
||||
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
|
||||
github.com/mojocn/base64Captcha v1.3.1
|
||||
github.com/mojocn/base64Captcha v1.3.5
|
||||
github.com/otiai10/copy v1.7.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/qiniu/api.v7/v7 v7.4.1
|
||||
github.com/qiniu/qmgo v1.1.8
|
||||
github.com/redis/go-redis/v9 v9.0.5
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/satori/go.uuid v1.2.0
|
||||
github.com/shirou/gopsutil/v3 v3.22.5
|
||||
github.com/songzhibin97/gkit v1.2.7
|
||||
github.com/spf13/viper v1.7.0
|
||||
github.com/stretchr/testify v1.7.1
|
||||
github.com/swaggo/gin-swagger v1.3.0
|
||||
github.com/swaggo/swag v1.7.0
|
||||
github.com/tencentyun/cos-go-sdk-v5 v0.7.19
|
||||
github.com/unrolled/secure v1.0.7
|
||||
go.uber.org/zap v1.16.0
|
||||
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
|
||||
golang.org/x/text v0.3.7
|
||||
gorm.io/driver/mysql v1.3.3
|
||||
gorm.io/driver/postgres v1.3.4
|
||||
gorm.io/gorm v1.23.4
|
||||
nhooyr.io/websocket v1.8.6
|
||||
github.com/shirou/gopsutil/v3 v3.23.6
|
||||
github.com/songzhibin97/gkit v1.2.11
|
||||
github.com/spf13/viper v1.16.0
|
||||
github.com/stretchr/testify v1.8.4
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.0
|
||||
github.com/swaggo/swag v1.16.2
|
||||
github.com/tencentyun/cos-go-sdk-v5 v0.7.42
|
||||
github.com/unrolled/secure v1.13.0
|
||||
github.com/xuri/excelize/v2 v2.8.0
|
||||
go.mongodb.org/mongo-driver v1.12.1
|
||||
go.uber.org/zap v1.24.0
|
||||
golang.org/x/crypto v0.16.0
|
||||
golang.org/x/sync v0.5.0
|
||||
golang.org/x/text v0.14.0
|
||||
gorm.io/driver/mysql v1.5.1
|
||||
gorm.io/driver/postgres v1.5.2
|
||||
gorm.io/driver/sqlserver v1.5.1
|
||||
gorm.io/gorm v1.25.2
|
||||
nhooyr.io/websocket v1.8.7
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||
github.com/clbanning/mxj v1.8.4 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/denisenkom/go-mssqldb v0.12.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.16.0 // indirect
|
||||
github.com/glebarez/sqlite v1.4.3 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.1 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.19.6 // indirect
|
||||
github.com/go-openapi/spec v0.20.3 // indirect
|
||||
github.com/go-openapi/swag v0.19.15 // indirect
|
||||
github.com/go-playground/locales v0.14.0 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.0 // indirect
|
||||
github.com/go-playground/validator/v10 v10.10.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.20.2 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.3 // indirect
|
||||
github.com/go-openapi/spec v0.20.12 // indirect
|
||||
github.com/go-openapi/swag v0.22.5 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
|
||||
github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188 // indirect
|
||||
github.com/golang-sql/sqlexp v0.1.0 // indirect
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/golang/snappy v0.0.1 // indirect
|
||||
github.com/google/go-querystring v1.0.0 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.11.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.10.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.15.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.3.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.13.6 // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
github.com/lestrrat-go/strftime v1.0.6 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/magiconair/properties v1.8.1 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||
github.com/mitchellh/mapstructure v1.2.2 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/microsoft/go-mssqldb v1.1.0 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
||||
github.com/montanaflynn/stats v0.7.0 // indirect
|
||||
github.com/mozillazg/go-httpheader v0.2.1 // indirect
|
||||
github.com/pelletier/go-toml v1.6.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
|
||||
github.com/richardlehane/mscfb v1.0.3 // indirect
|
||||
github.com/richardlehane/msoleps v1.0.1 // indirect
|
||||
github.com/spf13/afero v1.2.2 // indirect
|
||||
github.com/spf13/cast v1.3.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/richardlehane/mscfb v1.0.4 // indirect
|
||||
github.com/richardlehane/msoleps v1.0.3 // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/spf13/afero v1.9.5 // indirect
|
||||
github.com/spf13/cast v1.5.1 // indirect
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/subosito/gotenv v1.2.0 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.10 // indirect
|
||||
github.com/tklauser/numcpus v0.4.0 // indirect
|
||||
github.com/ugorji/go/codec v1.2.6 // indirect
|
||||
github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.2 // indirect
|
||||
go.uber.org/atomic v1.6.0 // indirect
|
||||
go.uber.org/multierr v1.5.0 // indirect
|
||||
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb // indirect
|
||||
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
|
||||
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect
|
||||
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect
|
||||
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 // indirect
|
||||
golang.org/x/tools v0.1.5 // indirect
|
||||
google.golang.org/protobuf v1.27.1 // indirect
|
||||
gopkg.in/ini.v1 v1.55.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.0 // indirect
|
||||
gorm.io/driver/sqlserver v1.3.2 // indirect
|
||||
gorm.io/plugin/dbresolver v1.1.0 // indirect
|
||||
modernc.org/libc v1.15.1 // indirect
|
||||
modernc.org/mathutil v1.4.1 // indirect
|
||||
modernc.org/memory v1.0.7 // indirect
|
||||
modernc.org/sqlite v1.16.0 // indirect
|
||||
github.com/subosito/gotenv v1.4.2 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.11 // indirect
|
||||
github.com/tklauser/numcpus v0.6.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.2 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
|
||||
github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca // indirect
|
||||
github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.8.0 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/image v0.11.0 // indirect
|
||||
golang.org/x/net v0.19.0 // indirect
|
||||
golang.org/x/sys v0.15.0 // indirect
|
||||
golang.org/x/time v0.1.0 // indirect
|
||||
golang.org/x/tools v0.16.1 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gorm.io/datatypes v1.2.0 // indirect
|
||||
gorm.io/plugin/dbresolver v1.4.1 // indirect
|
||||
modernc.org/libc v1.24.1 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.6.0 // indirect
|
||||
modernc.org/sqlite v1.23.0 // indirect
|
||||
)
|
||||
|
||||
+547
-642
File diff suppressed because it is too large
Load Diff
@@ -17,6 +17,8 @@ func DBList() {
|
||||
switch info.Type {
|
||||
case "mysql":
|
||||
dbMap[info.AliasName] = GormMysqlByConfig(config.Mysql{GeneralDB: info.GeneralDB})
|
||||
case "mssql":
|
||||
dbMap[info.AliasName] = GormMssqlByConfig(config.Mssql{GeneralDB: info.GeneralDB})
|
||||
case "pgsql":
|
||||
dbMap[info.AliasName] = GormPgSqlByConfig(config.Pgsql{GeneralDB: info.GeneralDB})
|
||||
case "oracle":
|
||||
|
||||
@@ -48,6 +48,7 @@ func (e *ensureTables) MigrateTable(ctx context.Context) (context.Context, error
|
||||
sysModel.SysBaseMenuBtn{},
|
||||
sysModel.SysAuthorityBtn{},
|
||||
sysModel.SysAutoCode{},
|
||||
sysModel.SysExportTemplate{},
|
||||
|
||||
adapter.CasbinRule{},
|
||||
|
||||
@@ -83,6 +84,7 @@ func (e *ensureTables) TableCreated(ctx context.Context) bool {
|
||||
sysModel.SysBaseMenuBtn{},
|
||||
sysModel.SysAuthorityBtn{},
|
||||
sysModel.SysAutoCode{},
|
||||
sysModel.SysExportTemplate{},
|
||||
|
||||
adapter.CasbinRule{},
|
||||
|
||||
|
||||
+10
-12
@@ -11,24 +11,27 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Gorm 初始化数据库并产生数据库全局变量
|
||||
// Author SliverHorn
|
||||
func Gorm() *gorm.DB {
|
||||
switch global.GVA_CONFIG.System.DbType {
|
||||
case "mysql":
|
||||
return GormMysql()
|
||||
case "pgsql":
|
||||
return GormPgSql()
|
||||
case "oracle":
|
||||
return GormOracle()
|
||||
case "mssql":
|
||||
return GormMssql()
|
||||
case "sqlite":
|
||||
return GormSqlite()
|
||||
default:
|
||||
return GormMysql()
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterTables 注册数据库表专用
|
||||
// Author SliverHorn
|
||||
func RegisterTables(db *gorm.DB) {
|
||||
func RegisterTables() {
|
||||
db := global.GVA_DB
|
||||
err := db.AutoMigrate(
|
||||
// 系统模块表
|
||||
|
||||
system.SysApi{},
|
||||
system.SysUser{},
|
||||
system.SysBaseMenu{},
|
||||
@@ -42,17 +45,12 @@ func RegisterTables(db *gorm.DB) {
|
||||
system.SysBaseMenuBtn{},
|
||||
system.SysAuthorityBtn{},
|
||||
system.SysAutoCode{},
|
||||
system.SysExportTemplate{},
|
||||
|
||||
// 示例模块表
|
||||
example.ExaFile{},
|
||||
example.ExaCustomer{},
|
||||
example.ExaFileChunk{},
|
||||
example.ExaFileUploadAndDownload{},
|
||||
|
||||
// 自动化模块表
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
|
||||
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
|
||||
)
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("register table failed", zap.Error(err))
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* @Author: 逆光飞翔 191180776@qq.com
|
||||
* @Date: 2022-12-08 17:25:49
|
||||
* @LastEditors: 逆光飞翔 191180776@qq.com
|
||||
* @LastEditTime: 2022-12-08 18:00:00
|
||||
* @FilePath: \server\initialize\gorm_mssql.go
|
||||
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
|
||||
*/
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
|
||||
"gorm.io/driver/sqlserver"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GormMssql 初始化Mssql数据库
|
||||
// Author [LouisZhang](191180776@qq.com)
|
||||
func GormMssql() *gorm.DB {
|
||||
m := global.GVA_CONFIG.Mssql
|
||||
if m.Dbname == "" {
|
||||
return nil
|
||||
}
|
||||
mssqlConfig := sqlserver.Config{
|
||||
DSN: m.Dsn(), // DSN data source name
|
||||
DefaultStringSize: 191, // string 类型字段的默认长度
|
||||
}
|
||||
if db, err := gorm.Open(sqlserver.New(mssqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
|
||||
return nil
|
||||
} else {
|
||||
db.InstanceSet("gorm:table_options", "ENGINE="+m.Engine)
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
|
||||
return db
|
||||
}
|
||||
}
|
||||
|
||||
// GormMssqlByConfig 初始化Mysql数据库用过传入配置
|
||||
func GormMssqlByConfig(m config.Mssql) *gorm.DB {
|
||||
if m.Dbname == "" {
|
||||
return nil
|
||||
}
|
||||
mssqlConfig := sqlserver.Config{
|
||||
DSN: m.Dsn(), // DSN data source name
|
||||
DefaultStringSize: 191, // string 类型字段的默认长度
|
||||
}
|
||||
if db, err := gorm.Open(sqlserver.New(mssqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
|
||||
return db
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -20,7 +21,6 @@ func GormMysql() *gorm.DB {
|
||||
DSN: m.Dsn(), // DSN data source name
|
||||
DefaultStringSize: 191, // string 类型字段的默认长度
|
||||
SkipInitializeWithVersion: false, // 根据版本自动配置
|
||||
|
||||
}
|
||||
if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
|
||||
return nil
|
||||
|
||||
@@ -40,7 +40,6 @@ func GormOracleByConfig(m config.Oracle) *gorm.DB {
|
||||
oracleConfig := mysql.Config{
|
||||
DSN: m.Dsn(), // DSN data source name
|
||||
DefaultStringSize: 191, // string 类型字段的默认长度
|
||||
|
||||
}
|
||||
if db, err := gorm.Open(mysql.New(oracleConfig), internal.Gorm.Config(m.Prefix, m.Singular)); err != nil {
|
||||
panic(err)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GormSqlite 初始化Sqlite数据库
|
||||
func GormSqlite() *gorm.DB {
|
||||
s := global.GVA_CONFIG.Sqlite
|
||||
if s.Dbname == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if db, err := gorm.Open(sqlite.Open(s.Dsn()), internal.Gorm.Config(s.Prefix, s.Singular)); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.SetMaxIdleConns(s.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(s.MaxOpenConns)
|
||||
return db
|
||||
}
|
||||
}
|
||||
|
||||
// GormSqliteByConfig 初始化Sqlite数据库用过传入配置
|
||||
func GormSqliteByConfig(s config.Sqlite) *gorm.DB {
|
||||
if s.Dbname == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if db, err := gorm.Open(sqlite.Open(s.Dsn()), internal.Gorm.Config(s.Prefix, s.Singular)); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.SetMaxIdleConns(s.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(s.MaxOpenConns)
|
||||
return db
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ func (g *_gorm) Config(prefix string, singular bool) *gorm.Config {
|
||||
},
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
}
|
||||
_default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{
|
||||
_default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
|
||||
SlowThreshold: 200 * time.Millisecond,
|
||||
LogLevel: logger.Warn,
|
||||
Colorful: true,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/qiniu/qmgo/options"
|
||||
"go.mongodb.org/mongo-driver/event"
|
||||
opt "go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var Mongo = new(mongo)
|
||||
|
||||
type mongo struct{}
|
||||
|
||||
func (m *mongo) GetClientOptions() []options.ClientOptions {
|
||||
cmdMonitor := &event.CommandMonitor{
|
||||
Started: func(ctx context.Context, event *event.CommandStartedEvent) {
|
||||
zap.L().Info(fmt.Sprintf("[MongoDB][RequestID:%d][database:%s] %s\n", event.RequestID, event.DatabaseName, event.Command), zap.String("business", "mongo"))
|
||||
},
|
||||
Succeeded: func(ctx context.Context, event *event.CommandSucceededEvent) {
|
||||
zap.L().Info(fmt.Sprintf("[MongoDB][RequestID:%d] [%s] %s\n", event.RequestID, event.Duration.String(), event.Reply), zap.String("business", "mongo"))
|
||||
},
|
||||
Failed: func(ctx context.Context, event *event.CommandFailedEvent) {
|
||||
zap.L().Error(fmt.Sprintf("[MongoDB][RequestID:%d] [%s] %s\n", event.RequestID, event.Duration.String(), event.Failure), zap.String("business", "mongo"))
|
||||
},
|
||||
}
|
||||
return []options.ClientOptions{{ClientOptions: &opt.ClientOptions{Monitor: cmdMonitor}}}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/qiniu/qmgo"
|
||||
"github.com/qiniu/qmgo/options"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
option "go.mongodb.org/mongo-driver/mongo/options"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var Mongo = new(mongo)
|
||||
|
||||
type (
|
||||
mongo struct{}
|
||||
Index struct {
|
||||
V any `bson:"v"`
|
||||
Ns any `bson:"ns"`
|
||||
Key []bson.E `bson:"key"`
|
||||
Name string `bson:"name"`
|
||||
}
|
||||
)
|
||||
|
||||
func (m *mongo) Indexes(ctx context.Context) error {
|
||||
// 表名:索引列表 列: "表名": [][]string{{"index1", "index2"}}
|
||||
indexMap := map[string][][]string{}
|
||||
for collection, indexes := range indexMap {
|
||||
err := m.CreateIndexes(ctx, collection, indexes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mongo) Initialization() error {
|
||||
var opts []options.ClientOptions
|
||||
if global.GVA_CONFIG.Mongo.IsZap {
|
||||
opts = internal.Mongo.GetClientOptions()
|
||||
}
|
||||
ctx := context.Background()
|
||||
client, err := qmgo.Open(ctx, &qmgo.Config{
|
||||
Uri: global.GVA_CONFIG.Mongo.Uri(),
|
||||
Coll: global.GVA_CONFIG.Mongo.Coll,
|
||||
Database: global.GVA_CONFIG.Mongo.Database,
|
||||
MinPoolSize: &global.GVA_CONFIG.Mongo.MinPoolSize,
|
||||
MaxPoolSize: &global.GVA_CONFIG.Mongo.MaxPoolSize,
|
||||
SocketTimeoutMS: &global.GVA_CONFIG.Mongo.SocketTimeoutMs,
|
||||
ConnectTimeoutMS: &global.GVA_CONFIG.Mongo.ConnectTimeoutMs,
|
||||
Auth: &qmgo.Credential{
|
||||
Username: global.GVA_CONFIG.Mongo.Username,
|
||||
Password: global.GVA_CONFIG.Mongo.Password,
|
||||
AuthSource: global.GVA_CONFIG.Mongo.AuthSource,
|
||||
},
|
||||
}, opts...)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "链接mongodb数据库失败!")
|
||||
}
|
||||
global.GVA_MONGO = client
|
||||
err = m.Indexes(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mongo) CreateIndexes(ctx context.Context, name string, indexes [][]string) error {
|
||||
collection, err := global.GVA_MONGO.Database.Collection(name).CloneCollection()
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "获取[%s]的表对象失败!", name)
|
||||
}
|
||||
list, err := collection.Indexes().List(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "获取[%s]的索引对象失败!", name)
|
||||
}
|
||||
var entities []Index
|
||||
err = list.All(ctx, &entities)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "获取[%s]的索引列表失败!", name)
|
||||
}
|
||||
length := len(indexes)
|
||||
indexMap1 := make(map[string][]string, length)
|
||||
for i := 0; i < length; i++ {
|
||||
sort.Strings(indexes[i]) // 对索引key进行排序, 在使用bson.M搜索时, bson会自动按照key的字母顺序进行排序
|
||||
length1 := len(indexes[i])
|
||||
keys := make([]string, 0, length1)
|
||||
for j := 0; j < length1; j++ {
|
||||
if indexes[i][i][0] == '-' {
|
||||
keys = append(keys, indexes[i][j], "-1")
|
||||
continue
|
||||
}
|
||||
keys = append(keys, indexes[i][j], "1")
|
||||
}
|
||||
key := strings.Join(keys, "_")
|
||||
_, o1 := indexMap1[key]
|
||||
if o1 {
|
||||
return errors.Errorf("索引[%s]重复!", key)
|
||||
}
|
||||
indexMap1[key] = indexes[i]
|
||||
}
|
||||
length = len(entities)
|
||||
indexMap2 := make(map[string]map[string]string, length)
|
||||
for i := 0; i < length; i++ {
|
||||
v1, o1 := indexMap2[entities[i].Name]
|
||||
if !o1 {
|
||||
keyLength := len(entities[i].Key)
|
||||
v1 = make(map[string]string, keyLength)
|
||||
for j := 0; j < keyLength; j++ {
|
||||
v2, o2 := v1[entities[i].Key[j].Key]
|
||||
if !o2 {
|
||||
v1 = make(map[string]string)
|
||||
}
|
||||
v2 = entities[i].Key[j].Key
|
||||
v1[entities[i].Key[j].Key] = v2
|
||||
indexMap2[entities[i].Name] = v1
|
||||
}
|
||||
}
|
||||
}
|
||||
for k1, v1 := range indexMap1 {
|
||||
_, o2 := indexMap2[k1]
|
||||
if o2 {
|
||||
continue
|
||||
} // 索引存在
|
||||
if len(fmt.Sprintf("%s.%s.$%s", collection.Name(), name, v1)) > 127 {
|
||||
err = global.GVA_MONGO.Database.Collection(name).CreateOneIndex(ctx, options.IndexModel{
|
||||
Key: v1,
|
||||
IndexOptions: option.Index().SetName(utils.MD5V([]byte(k1))),
|
||||
// IndexOptions: option.Index().SetName(utils.MD5V([]byte(k1))).SetExpireAfterSeconds(86400), // SetExpireAfterSeconds(86400) 设置索引过期时间, 86400 = 1天
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "创建索引[%s]失败!", k1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err = global.GVA_MONGO.Database.Collection(name).CreateOneIndex(ctx, options.IndexModel{
|
||||
Key: v1,
|
||||
IndexOptions: option.Index().SetExpireAfterSeconds(86400),
|
||||
// IndexOptions: option.Index().SetName(utils.MD5V([]byte(k1))).SetExpireAfterSeconds(86400), // SetExpireAfterSeconds(86400) 设置索引过期时间(秒), 86400 = 1天
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "创建索引[%s]失败!", k1)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/middleware"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/plugin/email"
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -19,6 +19,7 @@ func Redis() {
|
||||
pong, err := client.Ping(context.Background()).Result()
|
||||
if err != nil {
|
||||
global.GVA_LOG.Error("redis connect ping failed, err:", zap.Error(err))
|
||||
panic(err)
|
||||
} else {
|
||||
global.GVA_LOG.Info("redis connect ping response:", zap.String("pong", pong))
|
||||
global.GVA_REDIS = client
|
||||
|
||||
+39
-32
@@ -1,43 +1,55 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
"net/http"
|
||||
|
||||
_ "github.com/flipped-aurora/gin-vue-admin/server/docs"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/docs"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/middleware"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/router"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/swaggo/gin-swagger"
|
||||
"github.com/swaggo/gin-swagger/swaggerFiles"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
)
|
||||
|
||||
// 初始化总路由
|
||||
|
||||
func Routers() *gin.Engine {
|
||||
Router := gin.Default()
|
||||
|
||||
// 设置为发布模式
|
||||
if global.GVA_CONFIG.System.Env == "public" {
|
||||
gin.SetMode(gin.ReleaseMode) //DebugMode ReleaseMode TestMode
|
||||
}
|
||||
|
||||
Router := gin.New()
|
||||
Router.Use(gin.Recovery())
|
||||
if global.GVA_CONFIG.System.Env != "public" {
|
||||
Router.Use(gin.Logger())
|
||||
}
|
||||
|
||||
InstallPlugin(Router) // 安装插件
|
||||
systemRouter := router.RouterGroupApp.System
|
||||
exampleRouter := router.RouterGroupApp.Example
|
||||
// 如果想要不使用nginx代理前端网页,可以修改 web/.env.production 下的
|
||||
// VUE_APP_BASE_API = /
|
||||
// VUE_APP_BASE_PATH = http://localhost
|
||||
// 然后执行打包命令 npm run build。在打开下面4行注释
|
||||
// Router.LoadHTMLGlob("./dist/*.html") // npm打包成dist的路径
|
||||
// Router.Static("/favicon.ico", "./dist/favicon.ico")
|
||||
// Router.Static("/static", "./dist/assets") // dist里面的静态资源
|
||||
// Router.StaticFile("/", "./dist/index.html") // 前端网页入口页面
|
||||
// 然后执行打包命令 npm run build。在打开下面3行注释
|
||||
//Router.Static("/favicon.ico", "./dist/favicon.ico")
|
||||
//Router.Static("/static", "./dist/static") // dist里面的静态资源
|
||||
//Router.StaticFile("/", "./dist/index.html") // 前端网页入口页面
|
||||
|
||||
Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.StorePath)) // 为用户头像和文件提供静态地址
|
||||
Router.StaticFS(global.GVA_CONFIG.Local.StorePath, http.Dir(global.GVA_CONFIG.Local.StorePath)) // 为用户头像和文件提供静态地址
|
||||
// Router.Use(middleware.LoadTls()) // 如果需要使用https 请打开此中间件 然后前往 core/server.go 将启动模式 更变为 Router.RunTLS("端口","你的cre/pem文件","你的key文件")
|
||||
// 跨域,如需跨域可以打开下面的注释
|
||||
// Router.Use(middleware.Cors()) // 直接放行全部跨域请求
|
||||
// Router.Use(middleware.CorsByRules()) // 按照配置的规则放行跨域请求
|
||||
//global.GVA_LOG.Info("use middleware cors")
|
||||
Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
docs.SwaggerInfo.BasePath = global.GVA_CONFIG.System.RouterPrefix
|
||||
Router.GET(global.GVA_CONFIG.System.RouterPrefix+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
global.GVA_LOG.Info("register swagger handler")
|
||||
// 方便统一添加路由组前缀 多服务器上线使用
|
||||
|
||||
PublicGroup := Router.Group("")
|
||||
PublicGroup := Router.Group(global.GVA_CONFIG.System.RouterPrefix)
|
||||
{
|
||||
// 健康监测
|
||||
PublicGroup.GET("/health", func(c *gin.Context) {
|
||||
@@ -48,33 +60,28 @@ func Routers() *gin.Engine {
|
||||
systemRouter.InitBaseRouter(PublicGroup) // 注册基础功能路由 不做鉴权
|
||||
systemRouter.InitInitRouter(PublicGroup) // 自动初始化相关
|
||||
}
|
||||
PrivateGroup := Router.Group("")
|
||||
PrivateGroup := Router.Group(global.GVA_CONFIG.System.RouterPrefix)
|
||||
PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
|
||||
{
|
||||
systemRouter.InitApiRouter(PrivateGroup) // 注册功能api路由
|
||||
systemRouter.InitJwtRouter(PrivateGroup) // jwt相关路由
|
||||
systemRouter.InitUserRouter(PrivateGroup) // 注册用户路由
|
||||
systemRouter.InitMenuRouter(PrivateGroup) // 注册menu路由
|
||||
systemRouter.InitSystemRouter(PrivateGroup) // system相关路由
|
||||
systemRouter.InitCasbinRouter(PrivateGroup) // 权限相关路由
|
||||
systemRouter.InitAutoCodeRouter(PrivateGroup) // 创建自动化代码
|
||||
systemRouter.InitAuthorityRouter(PrivateGroup) // 注册角色路由
|
||||
systemRouter.InitSysDictionaryRouter(PrivateGroup) // 字典管理
|
||||
systemRouter.InitAutoCodeHistoryRouter(PrivateGroup) // 自动化代码历史
|
||||
systemRouter.InitSysOperationRecordRouter(PrivateGroup) // 操作记录
|
||||
systemRouter.InitSysDictionaryDetailRouter(PrivateGroup) // 字典详情管理
|
||||
systemRouter.InitAuthorityBtnRouterRouter(PrivateGroup) // 字典详情管理
|
||||
|
||||
systemRouter.InitApiRouter(PrivateGroup, PublicGroup) // 注册功能api路由
|
||||
systemRouter.InitJwtRouter(PrivateGroup) // jwt相关路由
|
||||
systemRouter.InitUserRouter(PrivateGroup) // 注册用户路由
|
||||
systemRouter.InitMenuRouter(PrivateGroup) // 注册menu路由
|
||||
systemRouter.InitSystemRouter(PrivateGroup) // system相关路由
|
||||
systemRouter.InitCasbinRouter(PrivateGroup) // 权限相关路由
|
||||
systemRouter.InitAutoCodeRouter(PrivateGroup) // 创建自动化代码
|
||||
systemRouter.InitAuthorityRouter(PrivateGroup) // 注册角色路由
|
||||
systemRouter.InitSysDictionaryRouter(PrivateGroup) // 字典管理
|
||||
systemRouter.InitAutoCodeHistoryRouter(PrivateGroup) // 自动化代码历史
|
||||
systemRouter.InitSysOperationRecordRouter(PrivateGroup) // 操作记录
|
||||
systemRouter.InitSysDictionaryDetailRouter(PrivateGroup) // 字典详情管理
|
||||
systemRouter.InitAuthorityBtnRouterRouter(PrivateGroup) // 字典详情管理
|
||||
systemRouter.InitSysExportTemplateRouter(PrivateGroup) // 导出模板
|
||||
exampleRouter.InitCustomerRouter(PrivateGroup) // 客户路由
|
||||
exampleRouter.InitFileUploadAndDownloadRouter(PrivateGroup) // 文件上传下载功能路由
|
||||
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
|
||||
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
|
||||
}
|
||||
|
||||
InstallPlugin(Router) // 安装插件
|
||||
|
||||
global.GVA_LOG.Info("router register success")
|
||||
return Router
|
||||
}
|
||||
|
||||
+24
-20
@@ -2,32 +2,36 @@ package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/task"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
)
|
||||
|
||||
func Timer() {
|
||||
if global.GVA_CONFIG.Timer.Start {
|
||||
for i := range global.GVA_CONFIG.Timer.Detail {
|
||||
go func(detail config.Detail) {
|
||||
var option []cron.Option
|
||||
if global.GVA_CONFIG.Timer.WithSeconds {
|
||||
option = append(option, cron.WithSeconds())
|
||||
}
|
||||
_, err := global.GVA_Timer.AddTaskByFunc("ClearDB", global.GVA_CONFIG.Timer.Spec, func() {
|
||||
err := utils.ClearTable(global.GVA_DB, detail.TableName, detail.CompareField, detail.Interval)
|
||||
if err != nil {
|
||||
fmt.Println("timer error:", err)
|
||||
}
|
||||
}, option...)
|
||||
if err != nil {
|
||||
fmt.Println("add timer error:", err)
|
||||
}
|
||||
}(global.GVA_CONFIG.Timer.Detail[i])
|
||||
go func() {
|
||||
var option []cron.Option
|
||||
option = append(option, cron.WithSeconds())
|
||||
// 清理DB定时任务
|
||||
_, err := global.GVA_Timer.AddTaskByFunc("ClearDB", "@daily", func() {
|
||||
err := task.ClearTable(global.GVA_DB) // 定时任务方法定在task文件包中
|
||||
if err != nil {
|
||||
fmt.Println("timer error:", err)
|
||||
}
|
||||
}, "定时清理数据库【日志,黑名单】内容", option...)
|
||||
if err != nil {
|
||||
fmt.Println("add timer error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 其他定时任务定在这里 参考上方使用方法
|
||||
|
||||
//_, err := global.GVA_Timer.AddTaskByFunc("定时任务标识", "corn表达式", func() {
|
||||
// 具体执行内容...
|
||||
// ......
|
||||
//}, option...)
|
||||
//if err != nil {
|
||||
// fmt.Println("add timer error:", err)
|
||||
//}
|
||||
}()
|
||||
}
|
||||
|
||||
+4
-4
@@ -13,9 +13,9 @@ import (
|
||||
//go:generate go mod tidy
|
||||
//go:generate go mod download
|
||||
|
||||
// @title Swagger Example API
|
||||
// @version 0.0.1
|
||||
// @description This is a sample Server pets
|
||||
// @title Gin-Vue-Admin Swagger API接口文档
|
||||
// @version v2.6.0
|
||||
// @description 使用gin+vue进行极速开发的全栈开发基础平台
|
||||
// @securityDefinitions.apikey ApiKeyAuth
|
||||
// @in header
|
||||
// @name x-token
|
||||
@@ -29,7 +29,7 @@ func main() {
|
||||
initialize.Timer()
|
||||
initialize.DBList()
|
||||
if global.GVA_DB != nil {
|
||||
initialize.RegisterTables(global.GVA_DB) // 初始化表
|
||||
initialize.RegisterTables() // 初始化表
|
||||
// 程序结束前关闭数据库链接
|
||||
db, _ := global.GVA_DB.DB()
|
||||
defer db.Close()
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/service"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var casbinService = service.ServiceGroupApp.SystemServiceGroup.CasbinService
|
||||
@@ -17,7 +19,8 @@ func CasbinHandler() gin.HandlerFunc {
|
||||
if global.GVA_CONFIG.System.Env != "develop" {
|
||||
waitUse, _ := utils.GetClaims(c)
|
||||
//获取请求的PATH
|
||||
obj := c.Request.URL.Path
|
||||
path := c.Request.URL.Path
|
||||
obj := strings.TrimPrefix(path, global.GVA_CONFIG.System.RouterPrefix)
|
||||
// 获取请求方法
|
||||
act := c.Request.Method
|
||||
// 获取用户的角色
|
||||
|
||||
+17
-12
@@ -1,18 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"go.uber.org/zap"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
|
||||
@@ -20,7 +21,7 @@ var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
|
||||
func JWTAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
|
||||
token := c.Request.Header.Get("x-token")
|
||||
token := utils.GetToken(c)
|
||||
if token == "" {
|
||||
response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
|
||||
c.Abort()
|
||||
@@ -28,6 +29,7 @@ func JWTAuth() gin.HandlerFunc {
|
||||
}
|
||||
if jwtService.IsBlacklist(token) {
|
||||
response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
|
||||
utils.ClearToken(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -35,12 +37,14 @@ func JWTAuth() gin.HandlerFunc {
|
||||
// parseToken 解析token包含的信息
|
||||
claims, err := j.ParseToken(token)
|
||||
if err != nil {
|
||||
if err == utils.TokenExpired {
|
||||
if errors.Is(err, utils.TokenExpired) {
|
||||
response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
|
||||
utils.ClearToken(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
|
||||
utils.ClearToken(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -53,13 +57,16 @@ func JWTAuth() gin.HandlerFunc {
|
||||
// response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
|
||||
// c.Abort()
|
||||
//}
|
||||
if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
|
||||
c.Set("claims", claims)
|
||||
c.Next()
|
||||
if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
|
||||
dr, _ := utils.ParseDuration(global.GVA_CONFIG.JWT.ExpiresTime)
|
||||
claims.ExpiresAt = time.Now().Add(dr).Unix()
|
||||
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(dr))
|
||||
newToken, _ := j.CreateTokenByOldToken(token, *claims)
|
||||
newClaims, _ := j.ParseToken(newToken)
|
||||
c.Header("new-token", newToken)
|
||||
c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))
|
||||
c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt.Unix(), 10))
|
||||
utils.SetToken(c, newToken, int(dr.Seconds()))
|
||||
if global.GVA_CONFIG.System.UseMultipoint {
|
||||
RedisJwtToken, err := jwtService.GetRedisJWT(newClaims.Username)
|
||||
if err != nil {
|
||||
@@ -71,7 +78,5 @@ func JWTAuth() gin.HandlerFunc {
|
||||
_ = jwtService.SetRedisJWT(newToken, newClaims.Username)
|
||||
}
|
||||
}
|
||||
c.Set("claims", claims)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 处理跨域请求,支持options访问
|
||||
func NeedInit() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if global.GVA_DB == nil {
|
||||
response.OkWithDetailed(gin.H{
|
||||
"needInit": true,
|
||||
}, "前往初始化数据库", c)
|
||||
c.Abort()
|
||||
} else {
|
||||
c.Next()
|
||||
}
|
||||
// 处理请求
|
||||
}
|
||||
}
|
||||
@@ -23,10 +23,11 @@ import (
|
||||
var operationRecordService = service.ServiceGroupApp.SystemServiceGroup.OperationRecordService
|
||||
|
||||
var respPool sync.Pool
|
||||
var bufferSize = 1024
|
||||
|
||||
func init() {
|
||||
respPool.New = func() interface{} {
|
||||
return make([]byte, 1024)
|
||||
return make([]byte, bufferSize)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +57,8 @@ func OperationRecord() gin.HandlerFunc {
|
||||
body, _ = json.Marshal(&m)
|
||||
}
|
||||
claims, _ := utils.GetClaims(c)
|
||||
if claims.ID != 0 {
|
||||
userId = int(claims.ID)
|
||||
if claims != nil && claims.BaseClaims.ID != 0 {
|
||||
userId = int(claims.BaseClaims.ID)
|
||||
} else {
|
||||
id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
|
||||
if err != nil {
|
||||
@@ -75,13 +76,9 @@ func OperationRecord() gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// 上传文件时候 中间件日志进行裁断操作
|
||||
if strings.Contains(c.GetHeader("Content-Type"), "multipart/form-data") {
|
||||
if len(record.Body) > 1024 {
|
||||
// 截断
|
||||
newBody := respPool.Get().([]byte)
|
||||
copy(newBody, record.Body)
|
||||
record.Body = string(newBody)
|
||||
defer respPool.Put(newBody[:0])
|
||||
if strings.Contains(c.GetHeader("Content-Type"), "multipart/form-data") {
|
||||
if len(record.Body) > bufferSize {
|
||||
record.Body = "[文件]"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,21 +97,18 @@ func OperationRecord() gin.HandlerFunc {
|
||||
record.Latency = latency
|
||||
record.Resp = writer.body.String()
|
||||
|
||||
if strings.Contains(c.Writer.Header().Get("Pragma"), "public") ||
|
||||
strings.Contains(c.Writer.Header().Get("Expires"), "0") ||
|
||||
if strings.Contains(c.Writer.Header().Get("Pragma"), "public") ||
|
||||
strings.Contains(c.Writer.Header().Get("Expires"), "0") ||
|
||||
strings.Contains(c.Writer.Header().Get("Cache-Control"), "must-revalidate, post-check=0, pre-check=0") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/force-download") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/octet-stream") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/vnd.ms-excel") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/download") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Disposition"), "attachment") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/force-download") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/octet-stream") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/vnd.ms-excel") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Type"), "application/download") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Disposition"), "attachment") ||
|
||||
strings.Contains(c.Writer.Header().Get("Content-Transfer-Encoding"), "binary") {
|
||||
if len(record.Resp) > 1024 {
|
||||
if len(record.Resp) > bufferSize {
|
||||
// 截断
|
||||
newBody := respPool.Get().([]byte)
|
||||
copy(newBody, record.Resp)
|
||||
record.Body = string(newBody)
|
||||
defer respPool.Put(newBody[:0])
|
||||
record.Body = "超出记录长度"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package common
|
||||
|
||||
type ClearDB struct {
|
||||
TableName string
|
||||
CompareField string
|
||||
Interval string
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"github.com/gofrs/uuid/v5"
|
||||
jwt "github.com/golang-jwt/jwt/v4"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
)
|
||||
|
||||
// Custom claims structure
|
||||
type CustomClaims struct {
|
||||
BaseClaims
|
||||
BufferTime int64
|
||||
jwt.StandardClaims
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type BaseClaims struct {
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
)
|
||||
|
||||
type SysDictionarySearch struct {
|
||||
system.SysDictionary
|
||||
request.PageInfo
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysExportTemplateSearch struct {
|
||||
system.SysExportTemplate
|
||||
StartCreatedAt *time.Time `json:"startCreatedAt" form:"startCreatedAt"`
|
||||
EndCreatedAt *time.Time `json:"endCreatedAt" form:"endCreatedAt"`
|
||||
request.PageInfo
|
||||
}
|
||||
@@ -2,17 +2,18 @@ package request
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
"os"
|
||||
)
|
||||
|
||||
type InitDB struct {
|
||||
DBType string `json:"dbType"` // 数据库类型
|
||||
Host string `json:"host"` // 服务器地址
|
||||
Port string `json:"port"` // 数据库连接端口
|
||||
UserName string `json:"userName" binding:"required"` // 数据库用户名
|
||||
Password string `json:"password"` // 数据库密码
|
||||
DBName string `json:"dbName" binding:"required"` // 数据库名
|
||||
DBType string `json:"dbType"` // 数据库类型
|
||||
Host string `json:"host"` // 服务器地址
|
||||
Port string `json:"port"` // 数据库连接端口
|
||||
UserName string `json:"userName"` // 数据库用户名
|
||||
Password string `json:"password"` // 数据库密码
|
||||
DBName string `json:"dbName" binding:"required"` // 数据库名
|
||||
DBPath string `json:"dbPath"` // sqlite数据库文件路径
|
||||
}
|
||||
|
||||
// MysqlEmptyDsn msyql 空数据库 建库链接
|
||||
@@ -39,6 +40,13 @@ func (i *InitDB) PgsqlEmptyDsn() string {
|
||||
return "host=" + i.Host + " user=" + i.UserName + " password=" + i.Password + " port=" + i.Port + " dbname=" + "postgres" + " " + "sslmode=disable TimeZone=Asia/Shanghai"
|
||||
}
|
||||
|
||||
// SqliteEmptyDsn sqlite 空数据库 建库链接
|
||||
// Author Kafumio
|
||||
func (i *InitDB) SqliteEmptyDsn() string {
|
||||
separator := string(os.PathSeparator)
|
||||
return i.DBPath + separator + i.DBName + ".db"
|
||||
}
|
||||
|
||||
// ToMysqlConfig 转换 config.Mysql
|
||||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||||
func (i *InitDB) ToMysqlConfig() config.Mysql {
|
||||
@@ -74,3 +82,21 @@ func (i *InitDB) ToPgsqlConfig() config.Pgsql {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ToSqliteConfig 转换 config.Sqlite
|
||||
// Author [Kafumio](https://github.com/Kafumio)
|
||||
func (i *InitDB) ToSqliteConfig() config.Sqlite {
|
||||
return config.Sqlite{
|
||||
GeneralDB: config.GeneralDB{
|
||||
Path: i.DBPath,
|
||||
Port: i.Port,
|
||||
Dbname: i.DBName,
|
||||
Username: i.UserName,
|
||||
Password: i.Password,
|
||||
MaxIdleConns: 10,
|
||||
MaxOpenConns: 100,
|
||||
LogMode: "error",
|
||||
Config: "",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,4 +13,5 @@ type Column struct {
|
||||
ColumnName string `json:"columnName" gorm:"column:column_name"`
|
||||
DataTypeLong string `json:"dataTypeLong" gorm:"column:data_type_long"`
|
||||
ColumnComment string `json:"columnComment" gorm:"column:column_comment"`
|
||||
PrimaryKey bool `json:"primaryKey" gorm:"column:primary_key"`
|
||||
}
|
||||
|
||||
@@ -4,4 +4,5 @@ type SysCaptchaResponse struct {
|
||||
CaptchaId string `json:"captchaId"`
|
||||
PicPath string `json:"picPath"`
|
||||
CaptchaLength int `json:"captchaLength"`
|
||||
OpenCaptcha bool `json:"openCaptcha"`
|
||||
}
|
||||
|
||||
@@ -20,13 +20,19 @@ type AutoCodeStruct struct {
|
||||
AutoCreateResource bool `json:"autoCreateResource"` // 是否自动创建资源标识
|
||||
AutoMoveFile bool `json:"autoMoveFile"` // 是否自动移动文件
|
||||
BusinessDB string `json:"businessDB"` // 业务数据库
|
||||
Fields []*Field `json:"fields,omitempty"`
|
||||
HasTimer bool
|
||||
GvaModel bool `json:"gvaModel"` // 是否使用gva默认Model
|
||||
Fields []*Field `json:"fields"`
|
||||
PrimaryField *Field `json:"primaryField"`
|
||||
HasTimer bool `json:"-"`
|
||||
HasSearchTimer bool `json:"-"`
|
||||
DictTypes []string `json:"-"`
|
||||
Package string `json:"package"`
|
||||
PackageT string `json:"-"`
|
||||
NeedValid bool `json:"-"`
|
||||
NeedSort bool `json:"-"`
|
||||
HasPic bool `json:"-"`
|
||||
HasRichText bool `json:"-"`
|
||||
HasFile bool `json:"-"`
|
||||
NeedJSON bool `json:"-"`
|
||||
}
|
||||
|
||||
func (a *AutoCodeStruct) Pretreatment() {
|
||||
@@ -64,6 +70,7 @@ type Field struct {
|
||||
ErrorText string `json:"errorText"` // 校验失败文字
|
||||
Clearable bool `json:"clearable"` // 是否可清空
|
||||
Sort bool `json:"sort"` // 是否增加排序
|
||||
PrimaryKey bool `json:"primaryKey"` // 是否主键
|
||||
}
|
||||
|
||||
var ErrAutoMove error = errors.New("创建代码成功并移动文件成功")
|
||||
|
||||
@@ -10,6 +10,7 @@ type SysDictionaryDetail struct {
|
||||
global.GVA_MODEL
|
||||
Label string `json:"label" form:"label" gorm:"column:label;comment:展示值"` // 展示值
|
||||
Value int `json:"value" form:"value" gorm:"column:value;comment:字典值"` // 字典值
|
||||
Extend string `json:"extend" form:"extend" gorm:"column:extend;comment:扩展值"` // 扩展值
|
||||
Status *bool `json:"status" form:"status" gorm:"column:status;comment:启用状态"` // 启用状态
|
||||
Sort int `json:"sort" form:"sort" gorm:"column:sort;comment:排序标记"` // 排序标记
|
||||
SysDictionaryID int `json:"sysDictionaryID" form:"sysDictionaryID" gorm:"column:sys_dictionary_id;comment:关联标记"` // 关联标记
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// 自动生成模板SysExportTemplate
|
||||
package system
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
)
|
||||
|
||||
// 导出模板 结构体 SysExportTemplate
|
||||
type SysExportTemplate struct {
|
||||
global.GVA_MODEL
|
||||
Name string `json:"name" form:"name" gorm:"column:name;comment:模板名称;"` //模板名称
|
||||
TableName string `json:"tableName" form:"tableName" gorm:"column:table_name;comment:表名称;"` //表名称
|
||||
TemplateID string `json:"templateID" form:"templateID" gorm:"column:template_id;comment:模板标识;"` //模板标识
|
||||
TemplateInfo string `json:"templateInfo" form:"templateInfo" gorm:"column:template_info;type:text;"` //模板信息
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/satori/go.uuid"
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
type SysUser struct {
|
||||
|
||||
@@ -3,15 +3,12 @@ package {{.Package}}
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/{{.Package}}"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
{{.Package}}Req "github.com/flipped-aurora/gin-vue-admin/server/model/{{.Package}}/request"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
{{- if .NeedValid }}
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
{{- else if .AutoCreateResource}}
|
||||
{{- if .AutoCreateResource}}
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
||||
{{- end }}
|
||||
)
|
||||
@@ -22,14 +19,14 @@ type {{.StructName}}Api struct {
|
||||
var {{.Abbreviation}}Service = service.ServiceGroupApp.{{.PackageT}}ServiceGroup.{{.StructName}}Service
|
||||
|
||||
|
||||
// Create{{.StructName}} 创建{{.StructName}}
|
||||
// Create{{.StructName}} 创建{{.Description}}
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 创建{{.StructName}}
|
||||
// @Summary 创建{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body {{.Package}}.{{.StructName}} true "创建{{.StructName}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
|
||||
// @Param data body {{.Package}}.{{.StructName}} true "创建{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
|
||||
// @Router /{{.Abbreviation}}/create{{.StructName}} [post]
|
||||
func ({{.Abbreviation}}Api *{{.StructName}}Api) Create{{.StructName}}(c *gin.Context) {
|
||||
var {{.Abbreviation}} {{.Package}}.{{.StructName}}
|
||||
@@ -41,20 +38,8 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Create{{.StructName}}(c *gin.Con
|
||||
{{- if .AutoCreateResource }}
|
||||
{{.Abbreviation}}.CreatedBy = utils.GetUserID(c)
|
||||
{{- end }}
|
||||
{{- if .NeedValid }}
|
||||
verify := utils.Rules{
|
||||
{{- range $index,$element := .Fields }}
|
||||
{{- if $element.Require }}
|
||||
"{{$element.FieldName}}":{utils.NotEmpty()},
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
}
|
||||
if err := utils.Verify({{.Abbreviation}}, verify); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
{{- end }}
|
||||
if err := {{.Abbreviation}}Service.Create{{.StructName}}({{.Abbreviation}}); err != nil {
|
||||
|
||||
if err := {{.Abbreviation}}Service.Create{{.StructName}}(&{{.Abbreviation}}); err != nil {
|
||||
global.GVA_LOG.Error("创建失败!", zap.Error(err))
|
||||
response.FailWithMessage("创建失败", c)
|
||||
} else {
|
||||
@@ -62,26 +47,21 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Create{{.StructName}}(c *gin.Con
|
||||
}
|
||||
}
|
||||
|
||||
// Delete{{.StructName}} 删除{{.StructName}}
|
||||
// Delete{{.StructName}} 删除{{.Description}}
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 删除{{.StructName}}
|
||||
// @Summary 删除{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body {{.Package}}.{{.StructName}} true "删除{{.StructName}}"
|
||||
// @Param data body {{.Package}}.{{.StructName}} true "删除{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
|
||||
// @Router /{{.Abbreviation}}/delete{{.StructName}} [delete]
|
||||
func ({{.Abbreviation}}Api *{{.StructName}}Api) Delete{{.StructName}}(c *gin.Context) {
|
||||
var {{.Abbreviation}} {{.Package}}.{{.StructName}}
|
||||
err := c.ShouldBindJSON(&{{.Abbreviation}})
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
{{.PrimaryField.FieldJson}} := c.Query("{{.PrimaryField.FieldJson}}")
|
||||
{{- if .AutoCreateResource }}
|
||||
{{.Abbreviation}}.DeletedBy = utils.GetUserID(c)
|
||||
userID := utils.GetUserID(c)
|
||||
{{- end }}
|
||||
if err := {{.Abbreviation}}Service.Delete{{.StructName}}({{.Abbreviation}}); err != nil {
|
||||
if err := {{.Abbreviation}}Service.Delete{{.StructName}}({{.PrimaryField.FieldJson}} {{- if .AutoCreateResource -}},userID{{- end -}}); err != nil {
|
||||
global.GVA_LOG.Error("删除失败!", zap.Error(err))
|
||||
response.FailWithMessage("删除失败", c)
|
||||
} else {
|
||||
@@ -89,26 +69,20 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Delete{{.StructName}}(c *gin.Con
|
||||
}
|
||||
}
|
||||
|
||||
// Delete{{.StructName}}ByIds 批量删除{{.StructName}}
|
||||
// Delete{{.StructName}}ByIds 批量删除{{.Description}}
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 批量删除{{.StructName}}
|
||||
// @Summary 批量删除{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body request.IdsReq true "批量删除{{.StructName}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
|
||||
// @Router /{{.Abbreviation}}/delete{{.StructName}}ByIds [delete]
|
||||
func ({{.Abbreviation}}Api *{{.StructName}}Api) Delete{{.StructName}}ByIds(c *gin.Context) {
|
||||
var IDS request.IdsReq
|
||||
err := c.ShouldBindJSON(&IDS)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
{{.PrimaryField.FieldJson}}s := c.QueryArray("{{.PrimaryField.FieldJson}}s[]")
|
||||
{{- if .AutoCreateResource }}
|
||||
deletedBy := utils.GetUserID(c)
|
||||
userID := utils.GetUserID(c)
|
||||
{{- end }}
|
||||
if err := {{.Abbreviation}}Service.Delete{{.StructName}}ByIds(IDS{{- if .AutoCreateResource }},deletedBy{{- end }}); err != nil {
|
||||
if err := {{.Abbreviation}}Service.Delete{{.StructName}}ByIds({{.PrimaryField.FieldJson}}s{{- if .AutoCreateResource }},userID{{- end }}); err != nil {
|
||||
global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
|
||||
response.FailWithMessage("批量删除失败", c)
|
||||
} else {
|
||||
@@ -116,13 +90,13 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Delete{{.StructName}}ByIds(c *gi
|
||||
}
|
||||
}
|
||||
|
||||
// Update{{.StructName}} 更新{{.StructName}}
|
||||
// Update{{.StructName}} 更新{{.Description}}
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 更新{{.StructName}}
|
||||
// @Summary 更新{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body {{.Package}}.{{.StructName}} true "更新{{.StructName}}"
|
||||
// @Param data body {{.Package}}.{{.StructName}} true "更新{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
|
||||
// @Router /{{.Abbreviation}}/update{{.StructName}} [put]
|
||||
func ({{.Abbreviation}}Api *{{.StructName}}Api) Update{{.StructName}}(c *gin.Context) {
|
||||
@@ -135,19 +109,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Update{{.StructName}}(c *gin.Con
|
||||
{{- if .AutoCreateResource }}
|
||||
{{.Abbreviation}}.UpdatedBy = utils.GetUserID(c)
|
||||
{{- end }}
|
||||
{{- if .NeedValid }}
|
||||
verify := utils.Rules{
|
||||
{{- range $index,$element := .Fields }}
|
||||
{{- if $element.Require }}
|
||||
"{{$element.FieldName}}":{utils.NotEmpty()},
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
}
|
||||
if err := utils.Verify({{.Abbreviation}}, verify); err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
{{- end }}
|
||||
|
||||
if err := {{.Abbreviation}}Service.Update{{.StructName}}({{.Abbreviation}}); err != nil {
|
||||
global.GVA_LOG.Error("更新失败!", zap.Error(err))
|
||||
response.FailWithMessage("更新失败", c)
|
||||
@@ -156,23 +118,18 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Update{{.StructName}}(c *gin.Con
|
||||
}
|
||||
}
|
||||
|
||||
// Find{{.StructName}} 用id查询{{.StructName}}
|
||||
// Find{{.StructName}} 用id查询{{.Description}}
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 用id查询{{.StructName}}
|
||||
// @Summary 用id查询{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query {{.Package}}.{{.StructName}} true "用id查询{{.StructName}}"
|
||||
// @Param data query {{.Package}}.{{.StructName}} true "用id查询{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
|
||||
// @Router /{{.Abbreviation}}/find{{.StructName}} [get]
|
||||
func ({{.Abbreviation}}Api *{{.StructName}}Api) Find{{.StructName}}(c *gin.Context) {
|
||||
var {{.Abbreviation}} {{.Package}}.{{.StructName}}
|
||||
err := c.ShouldBindQuery(&{{.Abbreviation}})
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
if re{{.Abbreviation}}, err := {{.Abbreviation}}Service.Get{{.StructName}}({{.Abbreviation}}.ID); err != nil {
|
||||
{{.PrimaryField.FieldJson}} := c.Query("{{.PrimaryField.FieldJson}}")
|
||||
if re{{.Abbreviation}}, err := {{.Abbreviation}}Service.Get{{.StructName}}({{.PrimaryField.FieldJson}}); err != nil {
|
||||
global.GVA_LOG.Error("查询失败!", zap.Error(err))
|
||||
response.FailWithMessage("查询失败", c)
|
||||
} else {
|
||||
@@ -180,13 +137,13 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Find{{.StructName}}(c *gin.Conte
|
||||
}
|
||||
}
|
||||
|
||||
// Get{{.StructName}}List 分页获取{{.StructName}}列表
|
||||
// Get{{.StructName}}List 分页获取{{.Description}}列表
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 分页获取{{.StructName}}列表
|
||||
// @Summary 分页获取{{.Description}}列表
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query {{.Package}}Req.{{.StructName}}Search true "分页获取{{.StructName}}列表"
|
||||
// @Param data query {{.Package}}Req.{{.StructName}}Search true "分页获取{{.Description}}列表"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
|
||||
// @Router /{{.Abbreviation}}/get{{.StructName}}List [get]
|
||||
func ({{.Abbreviation}}Api *{{.StructName}}Api) Get{{.StructName}}List(c *gin.Context) {
|
||||
|
||||
@@ -2,20 +2,32 @@
|
||||
package {{.Package}}
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
{{ if .HasTimer }}"time"{{ end }}
|
||||
{{ if .GvaModel }}"github.com/flipped-aurora/gin-vue-admin/server/global"{{ end }}
|
||||
{{ if or .HasTimer }}"time"{{ end }}
|
||||
{{ if .NeedJSON }}"gorm.io/datatypes"{{ end }}
|
||||
)
|
||||
|
||||
// {{.StructName}} 结构体
|
||||
// {{.Description}} 结构体 {{.StructName}}
|
||||
type {{.StructName}} struct {
|
||||
global.GVA_MODEL {{- range .Fields}}
|
||||
{{ if .GvaModel }} global.GVA_MODEL {{ end }}
|
||||
{{- range .Fields}}
|
||||
{{- if eq .FieldType "enum" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"column:{{.ColumnName}};type:enum({{.DataTypeLong}});comment:{{.Comment}};"`
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};type:enum({{.DataTypeLong}});comment:{{.Comment}};" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else if eq .FieldType "picture" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else if eq .FieldType "video" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else if eq .FieldType "file" }}
|
||||
{{.FieldName}} datatypes.JSON `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else if eq .FieldType "pictures" }}
|
||||
{{.FieldName}} datatypes.JSON `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else if eq .FieldType "richtext" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}type:text;" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else if ne .FieldType "string" }}
|
||||
{{.FieldName}} *{{.FieldType}} `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}"`
|
||||
{{.FieldName}} *{{.FieldType}} `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- else }}
|
||||
{{.FieldName}} {{.FieldType}} `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}"`
|
||||
{{- end }} {{- end }}
|
||||
{{.FieldName}} {{.FieldType}} `json:"{{.FieldJson}}" form:"{{.FieldJson}}" gorm:"{{- if .PrimaryKey -}}primarykey;{{- end -}}column:{{.ColumnName}};comment:{{.Comment}};{{- if .DataTypeLong -}}size:{{.DataTypeLong}};{{- end -}}" {{- if .Require -}}binding:"required"{{- end -}}`
|
||||
{{- end }} {{ if .FieldDesc }}//{{.FieldDesc}} {{ end }} {{- end }}
|
||||
{{- if .AutoCreateResource }}
|
||||
CreatedBy uint `gorm:"column:created_by;comment:创建者"`
|
||||
UpdatedBy uint `gorm:"column:updated_by;comment:更新者"`
|
||||
@@ -24,7 +36,7 @@ type {{.StructName}} struct {
|
||||
}
|
||||
|
||||
{{ if .TableName }}
|
||||
// TableName {{.StructName}} 表名
|
||||
// TableName {{.Description}} {{.StructName}}自定义表名 {{.TableName}}
|
||||
func ({{.StructName}}) TableName() string {
|
||||
return "{{.TableName}}"
|
||||
}
|
||||
|
||||
@@ -1,20 +1,41 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/{{.Package}}"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
"time"
|
||||
{{ if or .HasSearchTimer .GvaModel}}"time"{{ end }}
|
||||
{{ if .NeedJSON }}"gorm.io/datatypes"{{ end }}
|
||||
)
|
||||
|
||||
type {{.StructName}}Search struct{
|
||||
{{.Package}}.{{.StructName}}
|
||||
StartCreatedAt *time.Time `json:"startCreatedAt" form:"startCreatedAt"`
|
||||
EndCreatedAt *time.Time `json:"endCreatedAt" form:"endCreatedAt"`
|
||||
{{ if .GvaModel }}
|
||||
StartCreatedAt *time.Time `json:"startCreatedAt" form:"startCreatedAt"`
|
||||
EndCreatedAt *time.Time `json:"endCreatedAt" form:"endCreatedAt"`
|
||||
{{ end }}
|
||||
{{- range .Fields}}
|
||||
{{- if eq .FieldSearchType "BETWEEN" "NOT BETWEEN"}}
|
||||
Start{{.FieldName}} *{{.FieldType}} `json:"start{{.FieldName}}" form:"start{{.FieldName}}"`
|
||||
End{{.FieldName}} *{{.FieldType}} `json:"end{{.FieldName}}" form:"end{{.FieldName}}"`
|
||||
{{- end }}
|
||||
{{- if ne .FieldSearchType ""}}
|
||||
{{- if eq .FieldSearchType "BETWEEN" "NOT BETWEEN"}}
|
||||
Start{{.FieldName}} *{{.FieldType}} `json:"start{{.FieldName}}" form:"start{{.FieldName}}"`
|
||||
End{{.FieldName}} *{{.FieldType}} `json:"end{{.FieldName}}" form:"end{{.FieldName}}"`
|
||||
{{- else }}
|
||||
{{- if eq .FieldType "enum" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}"`
|
||||
{{- else if eq .FieldType "picture" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- else if eq .FieldType "video" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- else if eq .FieldType "file" }}
|
||||
{{.FieldName}} datatypes.JSON `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- else if eq .FieldType "pictures" }}
|
||||
{{.FieldName}} datatypes.JSON `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- else if eq .FieldType "richtext" }}
|
||||
{{.FieldName}} string `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- else if ne .FieldType "string" }}
|
||||
{{.FieldName}} *{{.FieldType}} `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- else }}
|
||||
{{.FieldName}} {{.FieldType}} `json:"{{.FieldJson}}" form:"{{.FieldJson}}" `
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end}}
|
||||
{{- end }}
|
||||
request.PageInfo
|
||||
{{- if .NeedSort}}
|
||||
|
||||
@@ -9,19 +9,19 @@ import (
|
||||
type {{.StructName}}Router struct {
|
||||
}
|
||||
|
||||
// Init{{.StructName}}Router 初始化 {{.StructName}} 路由信息
|
||||
// Init{{.StructName}}Router 初始化 {{.Description}} 路由信息
|
||||
func (s *{{.StructName}}Router) Init{{.StructName}}Router(Router *gin.RouterGroup) {
|
||||
{{.Abbreviation}}Router := Router.Group("{{.Abbreviation}}").Use(middleware.OperationRecord())
|
||||
{{.Abbreviation}}RouterWithoutRecord := Router.Group("{{.Abbreviation}}")
|
||||
var {{.Abbreviation}}Api = v1.ApiGroupApp.{{.PackageT}}ApiGroup.{{.StructName}}Api
|
||||
{
|
||||
{{.Abbreviation}}Router.POST("create{{.StructName}}", {{.Abbreviation}}Api.Create{{.StructName}}) // 新建{{.StructName}}
|
||||
{{.Abbreviation}}Router.DELETE("delete{{.StructName}}", {{.Abbreviation}}Api.Delete{{.StructName}}) // 删除{{.StructName}}
|
||||
{{.Abbreviation}}Router.DELETE("delete{{.StructName}}ByIds", {{.Abbreviation}}Api.Delete{{.StructName}}ByIds) // 批量删除{{.StructName}}
|
||||
{{.Abbreviation}}Router.PUT("update{{.StructName}}", {{.Abbreviation}}Api.Update{{.StructName}}) // 更新{{.StructName}}
|
||||
{{.Abbreviation}}Router.POST("create{{.StructName}}", {{.Abbreviation}}Api.Create{{.StructName}}) // 新建{{.Description}}
|
||||
{{.Abbreviation}}Router.DELETE("delete{{.StructName}}", {{.Abbreviation}}Api.Delete{{.StructName}}) // 删除{{.Description}}
|
||||
{{.Abbreviation}}Router.DELETE("delete{{.StructName}}ByIds", {{.Abbreviation}}Api.Delete{{.StructName}}ByIds) // 批量删除{{.Description}}
|
||||
{{.Abbreviation}}Router.PUT("update{{.StructName}}", {{.Abbreviation}}Api.Update{{.StructName}}) // 更新{{.Description}}
|
||||
}
|
||||
{
|
||||
{{.Abbreviation}}RouterWithoutRecord.GET("find{{.StructName}}", {{.Abbreviation}}Api.Find{{.StructName}}) // 根据ID获取{{.StructName}}
|
||||
{{.Abbreviation}}RouterWithoutRecord.GET("get{{.StructName}}List", {{.Abbreviation}}Api.Get{{.StructName}}List) // 获取{{.StructName}}列表
|
||||
{{.Abbreviation}}RouterWithoutRecord.GET("find{{.StructName}}", {{.Abbreviation}}Api.Find{{.StructName}}) // 根据ID获取{{.Description}}
|
||||
{{.Abbreviation}}RouterWithoutRecord.GET("get{{.StructName}}List", {{.Abbreviation}}Api.Get{{.StructName}}List) // 获取{{.Description}}列表
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package {{.Package}}
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/{{.Package}}"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
|
||||
{{.Package}}Req "github.com/flipped-aurora/gin-vue-admin/server/model/{{.Package}}/request"
|
||||
{{- if .AutoCreateResource }}
|
||||
"gorm.io/gorm"
|
||||
@@ -20,66 +19,66 @@ type {{.StructName}}Service struct {
|
||||
{{- $db = printf "global.MustGetGlobalDBByDBName(\"%s\")" .BusinessDB }}
|
||||
{{- end}}
|
||||
|
||||
// Create{{.StructName}} 创建{{.StructName}}记录
|
||||
// Create{{.StructName}} 创建{{.Description}}记录
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service) Create{{.StructName}}({{.Abbreviation}} {{.Package}}.{{.StructName}}) (err error) {
|
||||
err = {{$db}}.Create(&{{.Abbreviation}}).Error
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service) Create{{.StructName}}({{.Abbreviation}} *{{.Package}}.{{.StructName}}) (err error) {
|
||||
err = {{$db}}.Create({{.Abbreviation}}).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete{{.StructName}} 删除{{.StructName}}记录
|
||||
// Delete{{.StructName}} 删除{{.Description}}记录
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Delete{{.StructName}}({{.Abbreviation}} {{.Package}}.{{.StructName}}) (err error) {
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Delete{{.StructName}}({{.PrimaryField.FieldJson}} string{{- if .AutoCreateResource -}},userID uint{{- end -}}) (err error) {
|
||||
{{- if .AutoCreateResource }}
|
||||
err = {{$db}}.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&{{.Package}}.{{.StructName}}{}).Where("id = ?", {{.Abbreviation}}.ID).Update("deleted_by", {{.Abbreviation}}.DeletedBy).Error; err != nil {
|
||||
if err := tx.Model(&{{.Package}}.{{.StructName}}{}).Where("{{.PrimaryField.ColumnName}} = ?", {{.PrimaryField.FieldJson}}).Update("deleted_by", userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Delete(&{{.Abbreviation}}).Error; err != nil {
|
||||
if err = tx.Delete(&{{.Package}}.{{.StructName}}{},"{{.PrimaryField.ColumnName}} = ?",{{.PrimaryField.FieldJson}}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
{{- else }}
|
||||
err = {{$db}}.Delete(&{{.Abbreviation}}).Error
|
||||
err = {{$db}}.Delete(&{{.Package}}.{{.StructName}}{},"{{.PrimaryField.ColumnName}} = ?",{{.PrimaryField.FieldJson}}).Error
|
||||
{{- end }}
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete{{.StructName}}ByIds 批量删除{{.StructName}}记录
|
||||
// Delete{{.StructName}}ByIds 批量删除{{.Description}}记录
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Delete{{.StructName}}ByIds(ids request.IdsReq{{- if .AutoCreateResource }},deleted_by uint{{- end}}) (err error) {
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Delete{{.StructName}}ByIds({{.PrimaryField.FieldJson}}s []string {{- if .AutoCreateResource }},deleted_by uint{{- end}}) (err error) {
|
||||
{{- if .AutoCreateResource }}
|
||||
err = {{$db}}.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&{{.Package}}.{{.StructName}}{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
|
||||
if err := tx.Model(&{{.Package}}.{{.StructName}}{}).Where("{{.PrimaryField.ColumnName}} in ?", {{.PrimaryField.FieldJson}}s).Update("deleted_by", deleted_by).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("id in ?", ids.Ids).Delete(&{{.Package}}.{{.StructName}}{}).Error; err != nil {
|
||||
if err := tx.Where("{{.PrimaryField.ColumnName}} in ?", {{.PrimaryField.FieldJson}}s).Delete(&{{.Package}}.{{.StructName}}{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
{{- else}}
|
||||
err = {{$db}}.Delete(&[]{{.Package}}.{{.StructName}}{},"id in ?",ids.Ids).Error
|
||||
err = {{$db}}.Delete(&[]{{.Package}}.{{.StructName}}{},"{{.PrimaryField.ColumnName}} in ?",{{.PrimaryField.FieldJson}}s).Error
|
||||
{{- end}}
|
||||
return err
|
||||
}
|
||||
|
||||
// Update{{.StructName}} 更新{{.StructName}}记录
|
||||
// Update{{.StructName}} 更新{{.Description}}记录
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Update{{.StructName}}({{.Abbreviation}} {{.Package}}.{{.StructName}}) (err error) {
|
||||
err = {{$db}}.Save(&{{.Abbreviation}}).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// Get{{.StructName}} 根据id获取{{.StructName}}记录
|
||||
// Get{{.StructName}} 根据{{.PrimaryField.FieldJson}}获取{{.Description}}记录
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}(id uint) ({{.Abbreviation}} {{.Package}}.{{.StructName}}, err error) {
|
||||
err = {{$db}}.Where("id = ?", id).First(&{{.Abbreviation}}).Error
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}({{.PrimaryField.FieldJson}} string) ({{.Abbreviation}} {{.Package}}.{{.StructName}}, err error) {
|
||||
err = {{$db}}.Where("{{.PrimaryField.ColumnName}} = ?", {{.PrimaryField.FieldJson}}).First(&{{.Abbreviation}}).Error
|
||||
return
|
||||
}
|
||||
|
||||
// Get{{.StructName}}InfoList 分页获取{{.StructName}}记录
|
||||
// Get{{.StructName}}InfoList 分页获取{{.Description}}记录
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}InfoList(info {{.Package}}Req.{{.StructName}}Search) (list []{{.Package}}.{{.StructName}}, total int64, err error) {
|
||||
limit := info.PageSize
|
||||
@@ -88,12 +87,14 @@ func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}InfoLis
|
||||
db := {{$db}}.Model(&{{.Package}}.{{.StructName}}{})
|
||||
var {{.Abbreviation}}s []{{.Package}}.{{.StructName}}
|
||||
// 如果有条件搜索 下方会自动创建搜索语句
|
||||
{{- if .GvaModel }}
|
||||
if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
|
||||
db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
|
||||
}
|
||||
{{- end }}
|
||||
{{- range .Fields}}
|
||||
{{- if .FieldSearchType}}
|
||||
{{- if eq .FieldType "string" }}
|
||||
{{- if or (eq .FieldType "string") (eq .FieldType "enum") (eq .FieldType "picture") (eq .FieldType "video") (eq .FieldType "richtext") }}
|
||||
if info.{{.FieldName}} != "" {
|
||||
db = db.Where("{{.ColumnName}} {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+ {{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
|
||||
}
|
||||
@@ -117,7 +118,7 @@ func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}InfoLis
|
||||
orderMap := make(map[string]bool)
|
||||
{{- range .Fields}}
|
||||
{{- if .Sort}}
|
||||
orderMap["{{.FieldJson}}"] = true
|
||||
orderMap["{{.ColumnName}}"] = true
|
||||
{{- end}}
|
||||
{{- end}}
|
||||
if orderMap[info.Sort] {
|
||||
@@ -129,6 +130,10 @@ func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}InfoLis
|
||||
}
|
||||
{{- end}}
|
||||
|
||||
err = db.Limit(limit).Offset(offset).Find(&{{.Abbreviation}}s).Error
|
||||
if limit != 0 {
|
||||
db = db.Limit(limit).Offset(offset)
|
||||
}
|
||||
|
||||
err = db.Find(&{{.Abbreviation}}s).Error
|
||||
return {{.Abbreviation}}s, total, err
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
package {{ .PackageName }}
|
||||
|
||||
type ApiGroup struct {
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
|
||||
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
package {{ .PackageName }}
|
||||
|
||||
type RouterGroup struct {
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
|
||||
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
|
||||
}
|
||||
|
||||
@@ -2,8 +2,5 @@ package {{ .PackageName }}
|
||||
|
||||
|
||||
type ServiceGroup struct {
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
|
||||
|
||||
// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import service from '@/utils/request'
|
||||
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 创建{{.StructName}}
|
||||
// @Summary 创建{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body model.{{.StructName}} true "创建{{.StructName}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
|
||||
// @Param data body model.{{.StructName}} true "创建{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
|
||||
// @Router /{{.Abbreviation}}/create{{.StructName}} [post]
|
||||
export const create{{.StructName}} = (data) => {
|
||||
return service({
|
||||
@@ -17,43 +17,43 @@ export const create{{.StructName}} = (data) => {
|
||||
}
|
||||
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 删除{{.StructName}}
|
||||
// @Summary 删除{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body model.{{.StructName}} true "删除{{.StructName}}"
|
||||
// @Param data body model.{{.StructName}} true "删除{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
|
||||
// @Router /{{.Abbreviation}}/delete{{.StructName}} [delete]
|
||||
export const delete{{.StructName}} = (data) => {
|
||||
export const delete{{.StructName}} = (params) => {
|
||||
return service({
|
||||
url: '/{{.Abbreviation}}/delete{{.StructName}}',
|
||||
method: 'delete',
|
||||
data
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 删除{{.StructName}}
|
||||
// @Summary 批量删除{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body request.IdsReq true "批量删除{{.StructName}}"
|
||||
// @Param data body request.IdsReq true "批量删除{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
|
||||
// @Router /{{.Abbreviation}}/delete{{.StructName}} [delete]
|
||||
export const delete{{.StructName}}ByIds = (data) => {
|
||||
export const delete{{.StructName}}ByIds = (params) => {
|
||||
return service({
|
||||
url: '/{{.Abbreviation}}/delete{{.StructName}}ByIds',
|
||||
method: 'delete',
|
||||
data
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 更新{{.StructName}}
|
||||
// @Summary 更新{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body model.{{.StructName}} true "更新{{.StructName}}"
|
||||
// @Param data body model.{{.StructName}} true "更新{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
|
||||
// @Router /{{.Abbreviation}}/update{{.StructName}} [put]
|
||||
export const update{{.StructName}} = (data) => {
|
||||
@@ -65,11 +65,11 @@ export const update{{.StructName}} = (data) => {
|
||||
}
|
||||
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 用id查询{{.StructName}}
|
||||
// @Summary 用id查询{{.Description}}
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query model.{{.StructName}} true "用id查询{{.StructName}}"
|
||||
// @Param data query model.{{.StructName}} true "用id查询{{.Description}}"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
|
||||
// @Router /{{.Abbreviation}}/find{{.StructName}} [get]
|
||||
export const find{{.StructName}} = (params) => {
|
||||
@@ -81,11 +81,11 @@ export const find{{.StructName}} = (params) => {
|
||||
}
|
||||
|
||||
// @Tags {{.StructName}}
|
||||
// @Summary 分页获取{{.StructName}}列表
|
||||
// @Summary 分页获取{{.Description}}列表
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query request.PageInfo true "分页获取{{.StructName}}列表"
|
||||
// @Param data query request.PageInfo true "分页获取{{.Description}}列表"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
|
||||
// @Router /{{.Abbreviation}}/get{{.StructName}}List [get]
|
||||
export const get{{.StructName}}List = (params) => {
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
{{- if eq .FieldType "string" }}
|
||||
<el-input v-model="formData.{{.FieldJson}}" :clearable="{{.Clearable}}" placeholder="请输入" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "richtext" }}
|
||||
<RichEdit v-model="formData.{{.FieldJson}}"/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "int" }}
|
||||
{{- if .DictType }}
|
||||
<el-select v-model="formData.{{ .FieldJson }}" placeholder="请选择" :clearable="{{.Clearable}}">
|
||||
@@ -30,23 +33,29 @@
|
||||
<el-option v-for="item in [{{ .DataTypeLong }}]" :key="item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
{{- end }}
|
||||
</el-form-item>
|
||||
{{- if eq .FieldType "picture" }}
|
||||
<SelectImage v-model="formData.{{ .FieldJson }}" file-type="image"/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "video" }}
|
||||
<SelectImage v-model="formData.{{ .FieldJson }}" file-type="video"/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "pictures" }}
|
||||
<SelectImage v-model="formData.{{ .FieldJson }}" multiple file-type="image"/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "file" }}
|
||||
<SelectFile v-model="formData.{{ .FieldJson }}" />
|
||||
{{- end }}
|
||||
</el-form-item>
|
||||
{{- end }}
|
||||
<el-form-item>
|
||||
<el-button size="small" type="primary" @click="save">保存</el-button>
|
||||
<el-button size="small" type="primary" @click="back">返回</el-button>
|
||||
<el-button type="primary" @click="save">保存</el-button>
|
||||
<el-button type="primary" @click="back">返回</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: '{{.StructName}}'
|
||||
}
|
||||
</script>
|
||||
|
||||
<script setup>
|
||||
import {
|
||||
create{{.StructName}},
|
||||
@@ -54,11 +63,27 @@ import {
|
||||
find{{.StructName}}
|
||||
} from '@/api/{{.PackageName}}'
|
||||
|
||||
defineOptions({
|
||||
name: '{{.StructName}}Form'
|
||||
})
|
||||
|
||||
// 自动获取字典
|
||||
import { getDictFunc } from '@/utils/format'
|
||||
import { useRoute, useRouter } from "vue-router"
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ref, reactive } from 'vue'
|
||||
{{- if .HasPic }}
|
||||
import SelectImage from '@/components/selectImage/selectImage.vue'
|
||||
{{- end }}
|
||||
{{- if .HasFile }}
|
||||
import SelectFile from '@/components/selectFile/selectFile.vue'
|
||||
{{- end }}
|
||||
|
||||
{{- if .HasRichText }}
|
||||
// 富文本组件
|
||||
import RichEdit from '@/components/richtext/rich-edit.vue'
|
||||
{{- end }}
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
@@ -74,6 +99,9 @@ const formData = ref({
|
||||
{{- if eq .FieldType "string" }}
|
||||
{{.FieldJson}}: '',
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "richtext" }}
|
||||
{{.FieldJson}}: '',
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "int" }}
|
||||
{{.FieldJson}}: {{- if .DictType }} undefined{{ else }} 0{{- end }},
|
||||
{{- end }}
|
||||
@@ -83,6 +111,18 @@ const formData = ref({
|
||||
{{- if eq .FieldType "float64" }}
|
||||
{{.FieldJson}}: 0,
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "picture" }}
|
||||
{{.FieldJson}}: "",
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "video" }}
|
||||
{{.FieldJson}}: "",
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "pictures" }}
|
||||
{{.FieldJson}}: [],
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "file" }}
|
||||
{{.FieldJson}}: [],
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
})
|
||||
// 验证规则
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="gva-search-box">
|
||||
<el-form :inline="true" :model="searchInfo" class="demo-form-inline">
|
||||
<el-form-item label="创建时间">
|
||||
<el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始时间"></el-date-picker>
|
||||
<el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
|
||||
{{- if .GvaModel }}
|
||||
<el-form-item label="创建日期" prop="createdAt">
|
||||
<template #label>
|
||||
<span>
|
||||
创建日期
|
||||
<el-tooltip content="搜索范围是开始日期(包含)至结束日期(不包含)">
|
||||
<el-icon><QuestionFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</span>
|
||||
</template>
|
||||
<el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
|
||||
—
|
||||
<el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束时间"></el-date-picker>
|
||||
<el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
|
||||
</el-form-item>
|
||||
{{ end -}}
|
||||
{{- range .Fields}} {{- if .FieldSearchType}} {{- if eq .FieldType "bool" }}
|
||||
<el-form-item label="{{.FieldDesc}}" prop="{{.FieldJson}}">
|
||||
<el-select v-model="searchInfo.{{.FieldJson}}" clearable placeholder="请选择">
|
||||
@@ -29,14 +39,14 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
{{- else}}
|
||||
<el-form-item label="{{.FieldDesc}}">
|
||||
<el-form-item label="{{.FieldDesc}}" prop="{{.FieldJson}}">
|
||||
|
||||
|
||||
{{- if eq .FieldType "float64" "int"}}
|
||||
{{if eq .FieldSearchType "BETWEEN" "NOT BETWEEN"}}
|
||||
<el-input v-model.number="searchInfo.start{{.FieldName}}" placeholder="搜索条件(起)" />
|
||||
<el-input v-model.number="searchInfo.start{{.FieldName}}" placeholder="最小值" />
|
||||
—
|
||||
<el-input v-model.number="searchInfo.end{{.FieldName}}" placeholder="搜索条件(止)" />
|
||||
<el-input v-model.number="searchInfo.end{{.FieldName}}" placeholder="最大值" />
|
||||
{{- else}}
|
||||
{{- if .DictType}}
|
||||
<el-select v-model="searchInfo.{{.FieldJson}}" placeholder="请选择" style="width:100%" :clearable="true" >
|
||||
@@ -48,9 +58,17 @@
|
||||
{{- end}}
|
||||
{{- else if eq .FieldType "time.Time"}}
|
||||
{{if eq .FieldSearchType "BETWEEN" "NOT BETWEEN"}}
|
||||
<el-date-picker v-model="searchInfo.start{{.FieldName}}" type="datetime" placeholder="搜索条件(起)"></el-date-picker>
|
||||
<template #label>
|
||||
<span>
|
||||
{{.FieldDesc}}
|
||||
<el-tooltip content="搜索范围是开始日期(包含)至结束日期(不包含)">
|
||||
<el-icon><QuestionFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</span>
|
||||
</template>
|
||||
<el-date-picker v-model="searchInfo.start{{.FieldName}}" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.end{{.FieldName}} ? time.getTime() > searchInfo.end{{.FieldName}}.getTime() : false"></el-date-picker>
|
||||
—
|
||||
<el-date-picker v-model="searchInfo.end{{.FieldName}}" type="datetime" placeholder="搜索条件(止)"></el-date-picker>
|
||||
<el-date-picker v-model="searchInfo.end{{.FieldName}}" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.start{{.FieldName}} ? time.getTime() < searchInfo.start{{.FieldName}}.getTime() : false"></el-date-picker>
|
||||
{{- else}}
|
||||
<el-date-picker v-model="searchInfo.{{.FieldJson}}" type="datetime" placeholder="搜索条件"></el-date-picker>
|
||||
{{- end}}
|
||||
@@ -60,22 +78,22 @@
|
||||
|
||||
</el-form-item>{{ end }}{{ end }}{{ end }}
|
||||
<el-form-item>
|
||||
<el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
|
||||
<el-button size="small" icon="refresh" @click="onReset">重置</el-button>
|
||||
<el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
|
||||
<el-button icon="refresh" @click="onReset">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</div>
|
||||
<div class="gva-table-box">
|
||||
<div class="gva-btn-list">
|
||||
<el-button size="small" type="primary" icon="plus" @click="openDialog">新增</el-button>
|
||||
<el-popover v-model:visible="deleteVisible" placement="top" width="160">
|
||||
<el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
|
||||
<el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
|
||||
<p>确定要删除吗?</p>
|
||||
<div style="text-align: right; margin-top: 8px;">
|
||||
<el-button size="small" type="primary" link @click="deleteVisible = false">取消</el-button>
|
||||
<el-button size="small" type="primary" @click="onDelete">确定</el-button>
|
||||
<el-button type="primary" link @click="deleteVisible = false">取消</el-button>
|
||||
<el-button type="primary" @click="onDelete">确定</el-button>
|
||||
</div>
|
||||
<template #reference>
|
||||
<el-button icon="delete" size="small" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
|
||||
<el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
|
||||
</template>
|
||||
</el-popover>
|
||||
</div>
|
||||
@@ -84,16 +102,18 @@
|
||||
style="width: 100%"
|
||||
tooltip-effect="dark"
|
||||
:data="tableData"
|
||||
row-key="ID"
|
||||
row-key="{{.PrimaryField.FieldJson}}"
|
||||
@selection-change="handleSelectionChange"
|
||||
{{- if .NeedSort}}
|
||||
@sort-change="sortChange"
|
||||
{{- end}}
|
||||
>
|
||||
<el-table-column type="selection" width="55" />
|
||||
{{ if .GvaModel }}
|
||||
<el-table-column align="left" label="日期" width="180">
|
||||
<template #default="scope">{{ "{{ formatDate(scope.row.CreatedAt) }}" }}</template>
|
||||
</el-table-column>
|
||||
{{ end }}
|
||||
{{- range .Fields}}
|
||||
{{- if .DictType}}
|
||||
<el-table-column {{- if .Sort}} sortable{{- end}} align="left" label="{{.FieldDesc}}" prop="{{.FieldJson}}" width="120">
|
||||
@@ -109,14 +129,58 @@
|
||||
<el-table-column {{- if .Sort}} sortable{{- end}} align="left" label="{{.FieldDesc}}" width="180">
|
||||
<template #default="scope">{{"{{"}} formatDate(scope.row.{{.FieldJson}}) {{"}}"}}</template>
|
||||
</el-table-column>
|
||||
{{- else if eq .FieldType "picture" }}
|
||||
<el-table-column label="{{.FieldDesc}}" width="200">
|
||||
<template #default="scope">
|
||||
<el-image style="width: 100px; height: 100px" :src="getUrl(scope.row.{{.FieldJson}})" fit="cover"/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
{{- else if eq .FieldType "pictures" }}
|
||||
<el-table-column label="{{.FieldDesc}}" width="200">
|
||||
<template #default="scope">
|
||||
<div class="multiple-img-box">
|
||||
<el-image v-for="(item,index) in scope.row.{{.FieldJson}}" style="width: 80px; height: 80px" :src="getUrl(item)" fit="cover"/>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
{{- else if eq .FieldType "video" }}
|
||||
<el-table-column label="{{.FieldDesc}}" width="200">
|
||||
<template #default="scope">
|
||||
<video
|
||||
style="width: 100px; height: 100px"
|
||||
muted
|
||||
preload="metadata"
|
||||
>
|
||||
<source :src="getUrl(scope.row.{{.FieldJson}}) + '#t=1'">
|
||||
</video>
|
||||
</template>
|
||||
</el-table-column>
|
||||
{{- else if eq .FieldType "richtext" }}
|
||||
<el-table-column label="{{.FieldDesc}}" width="200">
|
||||
<template #default="scope">
|
||||
[富文本内容]
|
||||
</template>
|
||||
</el-table-column>
|
||||
{{- else if eq .FieldType "file" }}
|
||||
<el-table-column label="{{.FieldDesc}}" width="200">
|
||||
<template #default="scope">
|
||||
<div class="file-list">
|
||||
<el-tag v-for="file in scope.row.{{.FieldJson}}" :key="file.uid">{{"{{"}}file.name{{"}}"}}</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
{{- else }}
|
||||
<el-table-column {{- if .Sort}} sortable{{- end}} align="left" label="{{.FieldDesc}}" prop="{{.FieldJson}}" width="120" />
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
<el-table-column align="left" label="按钮组">
|
||||
<el-table-column align="left" label="操作" fixed="right" min-width="240">
|
||||
<template #default="scope">
|
||||
<el-button type="primary" link icon="edit" size="small" class="table-button" @click="update{{.StructName}}Func(scope.row)">变更</el-button>
|
||||
<el-button type="primary" link icon="delete" size="small" @click="deleteRow(scope.row)">删除</el-button>
|
||||
<el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
|
||||
<el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
|
||||
查看详情
|
||||
</el-button>
|
||||
<el-button type="primary" link icon="edit" class="table-button" @click="update{{.StructName}}Func(scope.row)">变更</el-button>
|
||||
<el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
@@ -132,55 +196,117 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="弹窗操作">
|
||||
<el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="80px">
|
||||
{{- range .Fields}}
|
||||
<el-form-item label="{{.FieldDesc}}:" prop="{{.FieldJson}}" >
|
||||
{{- if eq .FieldType "bool" }}
|
||||
<el-switch v-model="formData.{{.FieldJson}}" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" clearable ></el-switch>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "string" }}
|
||||
<el-input v-model="formData.{{.FieldJson}}" :clearable="{{.Clearable}}" placeholder="请输入" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "int" }}
|
||||
{{- if .DictType}}
|
||||
<el-select v-model="formData.{{ .FieldJson }}" placeholder="请选择" style="width:100%" :clearable="{{.Clearable}}" >
|
||||
<el-option v-for="(item,key) in {{ .DictType }}Options" :key="key" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
{{- else }}
|
||||
<el-input v-model.number="formData.{{ .FieldJson }}" :clearable="{{.Clearable}}" placeholder="请输入" />
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "time.Time" }}
|
||||
<el-date-picker v-model="formData.{{ .FieldJson }}" type="date" style="width:100%" placeholder="选择日期" :clearable="{{.Clearable}}" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "float64" }}
|
||||
<el-input-number v-model="formData.{{ .FieldJson }}" style="width:100%" :precision="2" :clearable="{{.Clearable}}" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "enum" }}
|
||||
<el-select v-model="formData.{{ .FieldJson }}" placeholder="请选择" style="width:100%" :clearable="{{.Clearable}}" >
|
||||
<el-option v-for="item in [{{.DataTypeLong}}]" :key="item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
{{- end }}
|
||||
</el-form-item>
|
||||
{{- end }}
|
||||
</el-form>
|
||||
<el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
|
||||
<el-scrollbar height="500px">
|
||||
<el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="80px">
|
||||
{{- range .Fields}}
|
||||
<el-form-item label="{{.FieldDesc}}:" prop="{{.FieldJson}}" >
|
||||
{{- if eq .FieldType "bool" }}
|
||||
<el-switch v-model="formData.{{.FieldJson}}" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" clearable ></el-switch>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "string" }}
|
||||
<el-input v-model="formData.{{.FieldJson}}" :clearable="{{.Clearable}}" placeholder="请输入{{.FieldDesc}}" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "richtext" }}
|
||||
<RichEdit v-model="formData.{{.FieldJson}}"/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "int" }}
|
||||
{{- if .DictType}}
|
||||
<el-select v-model="formData.{{ .FieldJson }}" placeholder="请选择{{.FieldDesc}}" style="width:100%" :clearable="{{.Clearable}}" >
|
||||
<el-option v-for="(item,key) in {{ .DictType }}Options" :key="key" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
{{- else }}
|
||||
<el-input v-model.number="formData.{{ .FieldJson }}" :clearable="{{.Clearable}}" placeholder="请输入{{.FieldDesc}}" />
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "time.Time" }}
|
||||
<el-date-picker v-model="formData.{{ .FieldJson }}" type="date" style="width:100%" placeholder="选择日期" :clearable="{{.Clearable}}" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "float64" }}
|
||||
<el-input-number v-model="formData.{{ .FieldJson }}" style="width:100%" :precision="2" :clearable="{{.Clearable}}" />
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "enum" }}
|
||||
<el-select v-model="formData.{{ .FieldJson }}" placeholder="请选择{{.FieldDesc}}" style="width:100%" :clearable="{{.Clearable}}" >
|
||||
<el-option v-for="item in [{{.DataTypeLong}}]" :key="item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "picture" }}
|
||||
<SelectImage
|
||||
v-model="formData.{{ .FieldJson }}"
|
||||
file-type="image"
|
||||
/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "pictures" }}
|
||||
<SelectImage
|
||||
multiple
|
||||
v-model="formData.{{ .FieldJson }}"
|
||||
file-type="image"
|
||||
/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "video" }}
|
||||
<SelectImage
|
||||
v-model="formData.{{ .FieldJson }}"
|
||||
file-type="video"
|
||||
/>
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "file" }}
|
||||
<SelectFile v-model="formData.{{ .FieldJson }}" />
|
||||
{{- end }}
|
||||
</el-form-item>
|
||||
{{- end }}
|
||||
</el-form>
|
||||
</el-scrollbar>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button size="small" @click="closeDialog">取 消</el-button>
|
||||
<el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
|
||||
<el-button @click="closeDialog">取 消</el-button>
|
||||
<el-button type="primary" @click="enterDialog">确 定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="detailShow" style="width: 800px" lock-scroll :before-close="closeDetailShow" title="查看详情" destroy-on-close>
|
||||
<el-scrollbar height="550px">
|
||||
<el-descriptions column="1" border>
|
||||
{{- range .Fields}}
|
||||
<el-descriptions-item label="{{ .FieldDesc }}">
|
||||
{{- if .DictType}}
|
||||
{{"{{"}} filterDict(formData.{{.FieldJson}},{{.DictType}}Options) {{"}}"}}
|
||||
{{- else if eq .FieldType "picture" }}
|
||||
<el-image style="width: 50px; height: 50px" :preview-src-list="ReturnArrImg(formData.{{ .FieldJson }})" :src="getUrl(formData.{{ .FieldJson }})" fit="cover" />
|
||||
{{- else if eq .FieldType "video" }}
|
||||
<video
|
||||
style="width: 50px; height: 50px"
|
||||
muted
|
||||
preload="metadata"
|
||||
>
|
||||
<source :src="getUrl(formData.{{ .FieldJson }}) + '#t=1'">
|
||||
</video>
|
||||
{{- else if eq .FieldType "pictures" }}
|
||||
<el-image style="width: 50px; height: 50px; margin-right: 10px" :preview-src-list="ReturnArrImg(formData.{{ .FieldJson }})" :initial-index="index" v-for="(item,index) in formData.{{ .FieldJson }}" :key="index" :src="getUrl(item)" fit="cover" />
|
||||
{{- else if eq .FieldType "file" }}
|
||||
<div class="fileBtn" v-for="(item,index) in formData.{{ .FieldJson }}" :key="index">
|
||||
<el-button type="primary" text bg @click="onDownloadFile(item.url)">
|
||||
<el-icon style="margin-right: 5px"><Download /></el-icon>
|
||||
{{"{{"}} item.name {{"}}"}}
|
||||
</el-button>
|
||||
</div>
|
||||
{{- else if eq .FieldType "bool" }}
|
||||
{{"{{"}} formatBoolean(formData.{{.FieldJson}}) {{"}}"}}
|
||||
{{- else if eq .FieldType "time.Time" }}
|
||||
{{"{{"}} formatDate(formData.{{.FieldJson}}) {{"}}"}}
|
||||
{{- else if eq .FieldType "richtext" }}
|
||||
[富文本内容]
|
||||
{{- else}}
|
||||
{{"{{"}} formData.{{.FieldJson}} {{"}}"}}
|
||||
{{- end }}
|
||||
</el-descriptions-item>
|
||||
{{- end }}
|
||||
</el-descriptions>
|
||||
</el-scrollbar>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: '{{.StructName}}'
|
||||
}
|
||||
</script>
|
||||
|
||||
<script setup>
|
||||
import {
|
||||
create{{.StructName}},
|
||||
@@ -191,11 +317,34 @@ import {
|
||||
get{{.StructName}}List
|
||||
} from '@/api/{{.PackageName}}'
|
||||
|
||||
{{- if or .HasPic .HasFile}}
|
||||
import { getUrl } from '@/utils/image'
|
||||
{{- end }}
|
||||
{{- if .HasPic }}
|
||||
// 图片选择组件
|
||||
import SelectImage from '@/components/selectImage/selectImage.vue'
|
||||
{{- end }}
|
||||
|
||||
{{- if .HasRichText }}
|
||||
// 富文本组件
|
||||
import RichEdit from '@/components/richtext/rich-edit.vue'
|
||||
{{- end }}
|
||||
|
||||
|
||||
{{- if .HasFile }}
|
||||
// 文件选择组件
|
||||
import SelectFile from '@/components/selectFile/selectFile.vue'
|
||||
{{- end }}
|
||||
|
||||
// 全量引入格式化工具 请按需保留
|
||||
import { getDictFunc, formatDate, formatBoolean, filterDict } from '@/utils/format'
|
||||
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
defineOptions({
|
||||
name: '{{.StructName}}'
|
||||
})
|
||||
|
||||
// 自动化生成的字典(可能为空)以及字段
|
||||
{{- range $index, $element := .DictTypes}}
|
||||
const {{ $element }}Options = ref([])
|
||||
@@ -208,6 +357,9 @@ const formData = ref({
|
||||
{{- if eq .FieldType "string" }}
|
||||
{{.FieldJson}}: '',
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "richtext" }}
|
||||
{{.FieldJson}}: '',
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "int" }}
|
||||
{{.FieldJson}}: {{- if .DictType }} undefined{{ else }} 0{{- end }},
|
||||
{{- end }}
|
||||
@@ -217,9 +369,22 @@ const formData = ref({
|
||||
{{- if eq .FieldType "float64" }}
|
||||
{{.FieldJson}}: 0,
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "picture" }}
|
||||
{{.FieldJson}}: "",
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "video" }}
|
||||
{{.FieldJson}}: "",
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "pictures" }}
|
||||
{{.FieldJson}}: [],
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "file" }}
|
||||
{{.FieldJson}}: [],
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
})
|
||||
|
||||
|
||||
// 验证规则
|
||||
const rule = reactive({
|
||||
{{- range .Fields }}
|
||||
@@ -228,13 +393,54 @@ const rule = reactive({
|
||||
required: true,
|
||||
message: '{{ .ErrorText }}',
|
||||
trigger: ['input','blur'],
|
||||
}],
|
||||
},
|
||||
{{- if eq .FieldType "string" }}
|
||||
{
|
||||
whitespace: true,
|
||||
message: '不能只输入空格',
|
||||
trigger: ['input', 'blur'],
|
||||
}
|
||||
{{- end }}
|
||||
],
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
})
|
||||
|
||||
const elFormRef = ref()
|
||||
const searchRule = reactive({
|
||||
createdAt: [
|
||||
{ validator: (rule, value, callback) => {
|
||||
if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
|
||||
callback(new Error('请填写结束日期'))
|
||||
} else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
|
||||
callback(new Error('请填写开始日期'))
|
||||
} else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
|
||||
callback(new Error('开始日期应当早于结束日期'))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}, trigger: 'change' }
|
||||
],
|
||||
{{- range .Fields }}
|
||||
{{- if .FieldSearchType}}
|
||||
{{- if eq .FieldType "time.Time" }}
|
||||
{{.FieldJson }} : [{ validator: (rule, value, callback) => {
|
||||
if (searchInfo.value.start{{.FieldName}} && !searchInfo.value.end{{.FieldName}}) {
|
||||
callback(new Error('请填写结束日期'))
|
||||
} else if (!searchInfo.value.start{{.FieldName}} && searchInfo.value.end{{.FieldName}}) {
|
||||
callback(new Error('请填写开始日期'))
|
||||
} else if (searchInfo.value.start{{.FieldName}} && searchInfo.value.end{{.FieldName}} && (searchInfo.value.start{{.FieldName}}.getTime() === searchInfo.value.end{{.FieldName}}.getTime() || searchInfo.value.start{{.FieldName}}.getTime() > searchInfo.value.end{{.FieldName}}.getTime())) {
|
||||
callback(new Error('开始日期应当早于结束日期'))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}, trigger: 'change' }],
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
})
|
||||
|
||||
const elFormRef = ref()
|
||||
const elSearchFormRef = ref()
|
||||
|
||||
// =========== 表格控制部分 ===========
|
||||
const page = ref(1)
|
||||
@@ -260,13 +466,16 @@ const onReset = () => {
|
||||
|
||||
// 搜索
|
||||
const onSubmit = () => {
|
||||
page.value = 1
|
||||
pageSize.value = 10
|
||||
{{- range .Fields}}{{- if eq .FieldType "bool" }}
|
||||
if (searchInfo.value.{{.FieldJson}} === ""){
|
||||
searchInfo.value.{{.FieldJson}}=null
|
||||
}{{ end }}{{ end }}
|
||||
getTableData()
|
||||
elSearchFormRef.value?.validate(async(valid) => {
|
||||
if (!valid) return
|
||||
page.value = 1
|
||||
pageSize.value = 10
|
||||
{{- range .Fields}}{{- if eq .FieldType "bool" }}
|
||||
if (searchInfo.value.{{.FieldJson}} === ""){
|
||||
searchInfo.value.{{.FieldJson}}=null
|
||||
}{{ end }}{{ end }}
|
||||
getTableData()
|
||||
})
|
||||
}
|
||||
|
||||
// 分页
|
||||
@@ -331,7 +540,7 @@ const deleteVisible = ref(false)
|
||||
|
||||
// 多选删除
|
||||
const onDelete = async() => {
|
||||
const ids = []
|
||||
const {{.PrimaryField.FieldJson}}s = []
|
||||
if (multipleSelection.value.length === 0) {
|
||||
ElMessage({
|
||||
type: 'warning',
|
||||
@@ -341,15 +550,15 @@ const onDelete = async() => {
|
||||
}
|
||||
multipleSelection.value &&
|
||||
multipleSelection.value.map(item => {
|
||||
ids.push(item.ID)
|
||||
{{.PrimaryField.FieldJson}}s.push(item.{{.PrimaryField.FieldJson}})
|
||||
})
|
||||
const res = await delete{{.StructName}}ByIds({ ids })
|
||||
const res = await delete{{.StructName}}ByIds({ {{.PrimaryField.FieldJson}}s })
|
||||
if (res.code === 0) {
|
||||
ElMessage({
|
||||
type: 'success',
|
||||
message: '删除成功'
|
||||
})
|
||||
if (tableData.value.length === ids.length && page.value > 1) {
|
||||
if (tableData.value.length === {{.PrimaryField.FieldJson}}s.length && page.value > 1) {
|
||||
page.value--
|
||||
}
|
||||
deleteVisible.value = false
|
||||
@@ -362,7 +571,7 @@ const type = ref('')
|
||||
|
||||
// 更新行
|
||||
const update{{.StructName}}Func = async(row) => {
|
||||
const res = await find{{.StructName}}({ ID: row.ID })
|
||||
const res = await find{{.StructName}}({ {{.PrimaryField.FieldJson}}: row.{{.PrimaryField.FieldJson}} })
|
||||
type.value = 'update'
|
||||
if (res.code === 0) {
|
||||
formData.value = res.data.re{{.Abbreviation}}
|
||||
@@ -373,7 +582,7 @@ const update{{.StructName}}Func = async(row) => {
|
||||
|
||||
// 删除行
|
||||
const delete{{.StructName}}Func = async (row) => {
|
||||
const res = await delete{{.StructName}}({ ID: row.ID })
|
||||
const res = await delete{{.StructName}}({ {{.PrimaryField.FieldJson}}: row.{{.PrimaryField.FieldJson}} })
|
||||
if (res.code === 0) {
|
||||
ElMessage({
|
||||
type: 'success',
|
||||
@@ -389,6 +598,53 @@ const delete{{.StructName}}Func = async (row) => {
|
||||
// 弹窗控制标记
|
||||
const dialogFormVisible = ref(false)
|
||||
|
||||
|
||||
// 查看详情控制标记
|
||||
const detailShow = ref(false)
|
||||
|
||||
|
||||
// 打开详情弹窗
|
||||
const openDetailShow = () => {
|
||||
detailShow.value = true
|
||||
}
|
||||
|
||||
|
||||
// 打开详情
|
||||
const getDetails = async (row) => {
|
||||
// 打开弹窗
|
||||
const res = await find{{.StructName}}({ {{.PrimaryField.FieldJson}}: row.{{.PrimaryField.FieldJson}} })
|
||||
if (res.code === 0) {
|
||||
formData.value = res.data.re{{.Abbreviation}}
|
||||
openDetailShow()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 关闭详情弹窗
|
||||
const closeDetailShow = () => {
|
||||
detailShow.value = false
|
||||
formData.value = {
|
||||
{{- range .Fields}}
|
||||
{{- if eq .FieldType "bool" }}
|
||||
{{.FieldJson}}: false,
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "string" }}
|
||||
{{.FieldJson}}: '',
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "int" }}
|
||||
{{.FieldJson}}: {{- if .DictType }} undefined{{ else }} 0{{- end }},
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "time.Time" }}
|
||||
{{.FieldJson}}: new Date(),
|
||||
{{- end }}
|
||||
{{- if eq .FieldType "float64" }}
|
||||
{{.FieldJson}}: 0,
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 打开弹窗
|
||||
const openDialog = () => {
|
||||
type.value = 'create'
|
||||
@@ -444,7 +700,27 @@ const enterDialog = async () => {
|
||||
}
|
||||
})
|
||||
}
|
||||
{{if .HasFile }}
|
||||
const downloadFile = (url) => {
|
||||
window.open(getUrl(url), '_blank')
|
||||
}
|
||||
{{end}}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
{{if .HasFile }}
|
||||
.file-list{
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.fileBtn{
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.fileBtn:last-child{
|
||||
margin-bottom: 0;
|
||||
}
|
||||
{{end}}
|
||||
</style>
|
||||
|
||||
@@ -15,4 +15,5 @@ type RouterGroup struct {
|
||||
OperationRecordRouter
|
||||
DictionaryDetailRouter
|
||||
AuthorityBtnRouter
|
||||
SysExportTemplateRouter
|
||||
}
|
||||
|
||||
@@ -8,9 +8,11 @@ import (
|
||||
|
||||
type ApiRouter struct{}
|
||||
|
||||
func (s *ApiRouter) InitApiRouter(Router *gin.RouterGroup) {
|
||||
func (s *ApiRouter) InitApiRouter(Router *gin.RouterGroup, RouterPub *gin.RouterGroup) {
|
||||
apiRouter := Router.Group("api").Use(middleware.OperationRecord())
|
||||
apiRouterWithoutRecord := Router.Group("api")
|
||||
|
||||
apiPublicRouterWithoutRecord := RouterPub.Group("api")
|
||||
apiRouterApi := v1.ApiGroupApp.SystemApiGroup.SystemApiApi
|
||||
{
|
||||
apiRouter.POST("createApi", apiRouterApi.CreateApi) // 创建Api
|
||||
@@ -23,4 +25,7 @@ func (s *ApiRouter) InitApiRouter(Router *gin.RouterGroup) {
|
||||
apiRouterWithoutRecord.POST("getAllApis", apiRouterApi.GetAllApis) // 获取所有api
|
||||
apiRouterWithoutRecord.POST("getApiList", apiRouterApi.GetApiList) // 获取Api列表
|
||||
}
|
||||
{
|
||||
apiPublicRouterWithoutRecord.GET("freshCasbin", apiRouterApi.FreshCasbin) // 刷新casbin权限
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,5 +21,6 @@ func (s *AutoCodeRouter) InitAutoCodeRouter(Router *gin.RouterGroup) {
|
||||
autoCodeRouter.POST("delPackage", autoCodeApi.DelPackage) // 删除package包
|
||||
autoCodeRouter.POST("createPlug", autoCodeApi.AutoPlug) // 自动插件包模板
|
||||
autoCodeRouter.POST("installPlugin", autoCodeApi.InstallPlugin) // 自动安装插件
|
||||
autoCodeRouter.POST("pubPlug", autoCodeApi.PubPlug) // 打包插件
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/api/v1"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SysExportTemplateRouter struct {
|
||||
}
|
||||
|
||||
// InitSysExportTemplateRouter 初始化 导出模板 路由信息
|
||||
func (s *SysExportTemplateRouter) InitSysExportTemplateRouter(Router *gin.RouterGroup) {
|
||||
sysExportTemplateRouter := Router.Group("sysExportTemplate").Use(middleware.OperationRecord())
|
||||
sysExportTemplateRouterWithoutRecord := Router.Group("sysExportTemplate")
|
||||
var sysExportTemplateApi = v1.ApiGroupApp.SystemApiGroup.SysExportTemplateApi
|
||||
{
|
||||
sysExportTemplateRouter.POST("createSysExportTemplate", sysExportTemplateApi.CreateSysExportTemplate) // 新建导出模板
|
||||
sysExportTemplateRouter.DELETE("deleteSysExportTemplate", sysExportTemplateApi.DeleteSysExportTemplate) // 删除导出模板
|
||||
sysExportTemplateRouter.DELETE("deleteSysExportTemplateByIds", sysExportTemplateApi.DeleteSysExportTemplateByIds) // 批量删除导出模板
|
||||
sysExportTemplateRouter.PUT("updateSysExportTemplate", sysExportTemplateApi.UpdateSysExportTemplate) // 更新导出模板
|
||||
sysExportTemplateRouter.POST("importExcel", sysExportTemplateApi.ImportExcel) // 更新导出模板
|
||||
}
|
||||
{
|
||||
sysExportTemplateRouterWithoutRecord.GET("findSysExportTemplate", sysExportTemplateApi.FindSysExportTemplate) // 根据ID获取导出模板
|
||||
sysExportTemplateRouterWithoutRecord.GET("getSysExportTemplateList", sysExportTemplateApi.GetSysExportTemplateList) // 获取导出模板列表
|
||||
sysExportTemplateRouterWithoutRecord.GET("exportExcel", sysExportTemplateApi.ExportExcel) // 导出表格
|
||||
sysExportTemplateRouterWithoutRecord.GET("exportTemplate", sysExportTemplateApi.ExportTemplate) // 导出表格模板
|
||||
}
|
||||
}
|
||||
@@ -92,17 +92,17 @@ func (e *FileUploadAndDownloadService) UploadFile(header *multipart.FileHeader,
|
||||
oss := upload.NewOss()
|
||||
filePath, key, uploadErr := oss.UploadFile(header)
|
||||
if uploadErr != nil {
|
||||
panic(err)
|
||||
panic(uploadErr)
|
||||
}
|
||||
s := strings.Split(header.Filename, ".")
|
||||
f := example.ExaFileUploadAndDownload{
|
||||
Url: filePath,
|
||||
Name: header.Filename,
|
||||
Tag: s[len(s)-1],
|
||||
Key: key,
|
||||
}
|
||||
if noSave == "0" {
|
||||
s := strings.Split(header.Filename, ".")
|
||||
f := example.ExaFileUploadAndDownload{
|
||||
Url: filePath,
|
||||
Name: header.Filename,
|
||||
Tag: s[len(s)-1],
|
||||
Key: key,
|
||||
}
|
||||
return f, e.Upload(f)
|
||||
}
|
||||
return
|
||||
return f, nil
|
||||
}
|
||||
|
||||
@@ -16,4 +16,5 @@ type ServiceGroup struct {
|
||||
OperationRecordService
|
||||
DictionaryDetailService
|
||||
AuthorityBtnService
|
||||
SysExportTemplateService
|
||||
}
|
||||
|
||||
@@ -43,12 +43,7 @@ func (apiService *ApiService) DeleteApi(api system.SysApi) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
success := CasbinServiceApp.ClearCasbin(1, entity.Path, entity.Method)
|
||||
if !success {
|
||||
return errors.New(entity.Path + ":" + entity.Method + "casbin同步清理失败")
|
||||
}
|
||||
e := CasbinServiceApp.Casbin()
|
||||
err = e.InvalidateCache()
|
||||
CasbinServiceApp.ClearCasbin(1, entity.Path, entity.Method)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -105,7 +100,7 @@ func (apiService *ApiService) GetAPIInfoList(api system.SysApi, info request.Pag
|
||||
} else {
|
||||
OrderStr = order
|
||||
}
|
||||
} else { // didn't matched any order key in `orderMap`
|
||||
} else { // didn't match any order key in `orderMap`
|
||||
err = fmt.Errorf("非法的排序字段: %v", order)
|
||||
return apiList, total, err
|
||||
}
|
||||
@@ -179,13 +174,8 @@ func (apiService *ApiService) DeleteApisByIds(ids request.IdsReq) (err error) {
|
||||
return err
|
||||
} else {
|
||||
for _, sysApi := range apis {
|
||||
success := CasbinServiceApp.ClearCasbin(1, sysApi.Path, sysApi.Method)
|
||||
if !success {
|
||||
return errors.New(sysApi.Path + ":" + sysApi.Method + "casbin同步清理失败")
|
||||
}
|
||||
CasbinServiceApp.ClearCasbin(1, sysApi.Path, sysApi.Method)
|
||||
}
|
||||
e := CasbinServiceApp.Casbin()
|
||||
err = e.InvalidateCache()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"errors"
|
||||
systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
|
||||
"strconv"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
@@ -24,12 +25,31 @@ type AuthorityService struct{}
|
||||
var AuthorityServiceApp = new(AuthorityService)
|
||||
|
||||
func (authorityService *AuthorityService) CreateAuthority(auth system.SysAuthority) (authority system.SysAuthority, err error) {
|
||||
var authorityBox system.SysAuthority
|
||||
if !errors.Is(global.GVA_DB.Where("authority_id = ?", auth.AuthorityId).First(&authorityBox).Error, gorm.ErrRecordNotFound) {
|
||||
|
||||
if err = global.GVA_DB.Where("authority_id = ?", auth.AuthorityId).First(&system.SysAuthority{}).Error; !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return auth, ErrRoleExistence
|
||||
}
|
||||
err = global.GVA_DB.Create(&auth).Error
|
||||
return auth, err
|
||||
|
||||
e := global.GVA_DB.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
if err = tx.Create(&auth).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
auth.SysBaseMenus = systemReq.DefaultMenu()
|
||||
if err = tx.Model(&auth).Association("SysBaseMenus").Replace(&auth.SysBaseMenus); err != nil {
|
||||
return err
|
||||
}
|
||||
casbinInfos := systemReq.DefaultCasbin()
|
||||
authorityId := strconv.Itoa(int(auth.AuthorityId))
|
||||
rules := [][]string{}
|
||||
for _, v := range casbinInfos {
|
||||
rules = append(rules, []string{authorityId, v.Path, v.Method})
|
||||
}
|
||||
return CasbinServiceApp.AddPolicies(tx, rules)
|
||||
})
|
||||
|
||||
return auth, e
|
||||
}
|
||||
|
||||
//@author: [piexlmax](https://github.com/piexlmax)
|
||||
@@ -101,7 +121,7 @@ func (authorityService *AuthorityService) UpdateAuthority(auth system.SysAuthori
|
||||
//@param: auth *model.SysAuthority
|
||||
//@return: err error
|
||||
|
||||
func (authorityService *AuthorityService) DeleteAuthority(auth *system.SysAuthority) (err error) {
|
||||
func (authorityService *AuthorityService) DeleteAuthority(auth *system.SysAuthority) error {
|
||||
if errors.Is(global.GVA_DB.Debug().Preload("Users").First(&auth).Error, gorm.ErrRecordNotFound) {
|
||||
return errors.New("该角色不存在")
|
||||
}
|
||||
@@ -114,29 +134,40 @@ func (authorityService *AuthorityService) DeleteAuthority(auth *system.SysAuthor
|
||||
if !errors.Is(global.GVA_DB.Where("parent_id = ?", auth.AuthorityId).First(&system.SysAuthority{}).Error, gorm.ErrRecordNotFound) {
|
||||
return errors.New("此角色存在子角色不允许删除")
|
||||
}
|
||||
db := global.GVA_DB.Preload("SysBaseMenus").Where("authority_id = ?", auth.AuthorityId).First(auth)
|
||||
err = db.Unscoped().Delete(auth).Error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if len(auth.SysBaseMenus) > 0 {
|
||||
err = global.GVA_DB.Model(auth).Association("SysBaseMenus").Delete(auth.SysBaseMenus)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
if err = tx.Preload("SysBaseMenus").Preload("DataAuthorityId").Where("authority_id = ?", auth.AuthorityId).First(auth).Unscoped().Delete(auth).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// err = db.Association("SysBaseMenus").Delete(&auth)
|
||||
}
|
||||
err = global.GVA_DB.Delete(&[]system.SysUserAuthority{}, "sys_authority_authority_id = ?", auth.AuthorityId).Error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = global.GVA_DB.Delete(&[]system.SysAuthorityBtn{}, "authority_id = ?", auth.AuthorityId).Error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
authorityId := strconv.Itoa(int(auth.AuthorityId))
|
||||
CasbinServiceApp.ClearCasbin(0, authorityId)
|
||||
return err
|
||||
|
||||
if len(auth.SysBaseMenus) > 0 {
|
||||
if err = tx.Model(auth).Association("SysBaseMenus").Delete(auth.SysBaseMenus); err != nil {
|
||||
return err
|
||||
}
|
||||
// err = db.Association("SysBaseMenus").Delete(&auth)
|
||||
}
|
||||
if len(auth.DataAuthorityId) > 0 {
|
||||
if err = tx.Model(auth).Association("DataAuthorityId").Delete(auth.DataAuthorityId); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err = tx.Delete(&system.SysUserAuthority{}, "sys_authority_authority_id = ?", auth.AuthorityId).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Where("authority_id = ?", auth.AuthorityId).Delete(&[]system.SysAuthorityBtn{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
authorityId := strconv.Itoa(int(auth.AuthorityId))
|
||||
|
||||
if err = CasbinServiceApp.RemoveFilteredPolicy(tx, authorityId); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
//@author: [piexlmax](https://github.com/piexlmax)
|
||||
|
||||
@@ -1,29 +1,24 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"archive/zip"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/format"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
cp "github.com/otiai10/copy"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/text/cases"
|
||||
"golang.org/x/text/language"
|
||||
ast2 "github.com/flipped-aurora/gin-vue-admin/server/utils/ast"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/resource/autocode_template/subcontract"
|
||||
cp "github.com/otiai10/copy"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
|
||||
@@ -53,23 +48,10 @@ type autoPackage struct {
|
||||
var (
|
||||
packageInjectionMap map[string]astInjectionMeta
|
||||
injectionPaths []injectionMeta
|
||||
caser = cases.Title(language.English)
|
||||
)
|
||||
|
||||
func Init(Package string) {
|
||||
injectionPaths = []injectionMeta{
|
||||
{
|
||||
path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go"),
|
||||
funcName: "MysqlTables",
|
||||
structNameF: Package + ".%s{},",
|
||||
},
|
||||
{
|
||||
path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go"),
|
||||
funcName: "Routers",
|
||||
structNameF: Package + "Router.Init%sRouter(PrivateGroup)",
|
||||
},
|
||||
{
|
||||
path: filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, fmt.Sprintf(global.GVA_CONFIG.AutoCode.SApi, Package), "enter.go"),
|
||||
@@ -144,26 +126,55 @@ type AutoCodeService struct{}
|
||||
|
||||
var AutoCodeServiceApp = new(AutoCodeService)
|
||||
|
||||
//@author: [songzhibin97](https://github.com/songzhibin97)
|
||||
//@function: PreviewTemp
|
||||
//@description: 预览创建代码
|
||||
//@param: model.AutoCodeStruct
|
||||
//@return: map[string]string, error
|
||||
// @author: [songzhibin97](https://github.com/songzhibin97)
|
||||
// @function: PreviewTemp
|
||||
// @description: 预览创建代码
|
||||
// @param: model.AutoCodeStruct
|
||||
// @return: map[string]string, error
|
||||
|
||||
func (autoCodeService *AutoCodeService) PreviewTemp(autoCode system.AutoCodeStruct) (map[string]string, error) {
|
||||
makeDictTypes(&autoCode)
|
||||
for i := range autoCode.Fields {
|
||||
if autoCode.Fields[i].FieldType == "time.Time" {
|
||||
autoCode.HasTimer = true
|
||||
break
|
||||
}
|
||||
if autoCode.Fields[i].Require {
|
||||
autoCode.NeedValid = true
|
||||
break
|
||||
if autoCode.Fields[i].FieldSearchType != "" {
|
||||
autoCode.HasSearchTimer = true
|
||||
}
|
||||
}
|
||||
if autoCode.Fields[i].Sort {
|
||||
autoCode.NeedSort = true
|
||||
break
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "picture" {
|
||||
autoCode.HasPic = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "video" {
|
||||
autoCode.HasPic = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "richtext" {
|
||||
autoCode.HasRichText = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "pictures" {
|
||||
autoCode.HasPic = true
|
||||
autoCode.NeedJSON = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "file" {
|
||||
autoCode.HasFile = true
|
||||
autoCode.NeedJSON = true
|
||||
}
|
||||
|
||||
if autoCode.GvaModel {
|
||||
autoCode.PrimaryField = &system.Field{
|
||||
FieldName: "ID",
|
||||
FieldType: "uint",
|
||||
FieldDesc: "ID",
|
||||
FieldJson: "ID",
|
||||
DataTypeLong: "20",
|
||||
Comment: "主键ID",
|
||||
ColumnName: "id",
|
||||
}
|
||||
}
|
||||
if !autoCode.GvaModel && autoCode.PrimaryField == nil && autoCode.Fields[i].PrimaryKey {
|
||||
autoCode.PrimaryField = autoCode.Fields[i]
|
||||
}
|
||||
}
|
||||
dataList, _, needMkdir, err := autoCodeService.getNeedList(&autoCode)
|
||||
@@ -237,26 +248,54 @@ func makeDictTypes(autoCode *system.AutoCodeStruct) {
|
||||
}
|
||||
}
|
||||
|
||||
//@author: [piexlmax](https://github.com/piexlmax)
|
||||
//@function: CreateTemp
|
||||
//@description: 创建代码
|
||||
//@param: model.AutoCodeStruct
|
||||
//@return: err error
|
||||
// @author: [piexlmax](https://github.com/piexlmax)
|
||||
// @function: CreateTemp
|
||||
// @description: 创建代码
|
||||
// @param: model.AutoCodeStruct
|
||||
// @return: err error
|
||||
|
||||
func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruct, ids ...uint) (err error) {
|
||||
makeDictTypes(&autoCode)
|
||||
for i := range autoCode.Fields {
|
||||
if autoCode.Fields[i].FieldType == "time.Time" {
|
||||
autoCode.HasTimer = true
|
||||
break
|
||||
}
|
||||
if autoCode.Fields[i].Require {
|
||||
autoCode.NeedValid = true
|
||||
break
|
||||
if autoCode.Fields[i].FieldSearchType != "" {
|
||||
autoCode.HasSearchTimer = true
|
||||
}
|
||||
}
|
||||
if autoCode.Fields[i].Sort {
|
||||
autoCode.NeedSort = true
|
||||
break
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "picture" {
|
||||
autoCode.HasPic = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "video" {
|
||||
autoCode.HasPic = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "richtext" {
|
||||
autoCode.HasRichText = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "pictures" {
|
||||
autoCode.NeedJSON = true
|
||||
autoCode.HasPic = true
|
||||
}
|
||||
if autoCode.Fields[i].FieldType == "file" {
|
||||
autoCode.NeedJSON = true
|
||||
autoCode.HasFile = true
|
||||
}
|
||||
if autoCode.GvaModel {
|
||||
autoCode.PrimaryField = &system.Field{
|
||||
FieldName: "ID",
|
||||
FieldType: "uint",
|
||||
FieldDesc: "ID",
|
||||
FieldJson: "ID",
|
||||
DataTypeLong: "20",
|
||||
Comment: "主键ID",
|
||||
ColumnName: "id",
|
||||
}
|
||||
}
|
||||
if !autoCode.GvaModel && autoCode.PrimaryField == nil && autoCode.Fields[i].PrimaryKey {
|
||||
autoCode.PrimaryField = autoCode.Fields[i]
|
||||
}
|
||||
}
|
||||
// 增加判断: 重复创建struct
|
||||
@@ -268,6 +307,12 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
|
||||
return err
|
||||
}
|
||||
meta, _ := json.Marshal(autoCode)
|
||||
|
||||
// 增加判断:Package不为空
|
||||
if autoCode.Package == "" {
|
||||
return errors.New("Package为空\n")
|
||||
}
|
||||
|
||||
// 写入文件前,先创建文件夹
|
||||
if err = utils.CreateDir(needMkdir...); err != nil {
|
||||
return err
|
||||
@@ -313,6 +358,22 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// 在gorm.go 注入 自动迁移
|
||||
path := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
|
||||
varDB := utils.MaheHump(autoCode.BusinessDB)
|
||||
ast2.AddRegisterTablesAst(path, "RegisterTables", autoCode.Package, varDB, autoCode.BusinessDB, autoCode.StructName)
|
||||
}
|
||||
|
||||
{
|
||||
// router.go 注入 自动迁移
|
||||
path := filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
|
||||
ast2.AddRouterCode(path, "Routers", autoCode.Package, autoCode.StructName)
|
||||
}
|
||||
// 给各个enter进行注入
|
||||
err = injectionCode(autoCode.StructName, &injectionCodeMeta)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -324,15 +385,6 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
|
||||
bf.WriteString(";")
|
||||
}
|
||||
}
|
||||
|
||||
var gormPath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "gorm.go")
|
||||
var routePath = filepath.Join(global.GVA_CONFIG.AutoCode.Root,
|
||||
global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.SInitialize, "router.go")
|
||||
var imporStr = fmt.Sprintf("github.com/flipped-aurora/gin-vue-admin/server/model/%s", autoCode.Package)
|
||||
_ = ImportReference(routePath, "", "", autoCode.Package, "")
|
||||
_ = ImportReference(gormPath, imporStr, "", "", "")
|
||||
|
||||
} else { // 打包
|
||||
if err = utils.ZipFiles("./ginvueadmin.zip", fileList, ".", "."); err != nil {
|
||||
return err
|
||||
@@ -349,6 +401,7 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
|
||||
autoCode.TableName,
|
||||
idBf.String(),
|
||||
autoCode.Package,
|
||||
autoCode.BusinessDB,
|
||||
)
|
||||
} else {
|
||||
err = AutoCodeHistoryServiceApp.CreateAutoCodeHistory(
|
||||
@@ -360,6 +413,7 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
|
||||
autoCode.StructName,
|
||||
idBf.String(),
|
||||
autoCode.Package,
|
||||
autoCode.BusinessDB,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -372,11 +426,11 @@ func (autoCodeService *AutoCodeService) CreateTemp(autoCode system.AutoCodeStruc
|
||||
return nil
|
||||
}
|
||||
|
||||
//@author: [piexlmax](https://github.com/piexlmax)
|
||||
//@function: GetAllTplFile
|
||||
//@description: 获取 pathName 文件夹下所有 tpl 文件
|
||||
//@param: pathName string, fileList []string
|
||||
//@return: []string, error
|
||||
// @author: [piexlmax](https://github.com/piexlmax)
|
||||
// @function: GetAllTplFile
|
||||
// @description: 获取 pathName 文件夹下所有 tpl 文件
|
||||
// @param: pathName string, fileList []string
|
||||
// @return: []string, error
|
||||
|
||||
func (autoCodeService *AutoCodeService) GetAllTplFile(pathName string, fileList []string) ([]string, error) {
|
||||
files, err := os.ReadDir(pathName)
|
||||
@@ -395,11 +449,11 @@ func (autoCodeService *AutoCodeService) GetAllTplFile(pathName string, fileList
|
||||
return fileList, err
|
||||
}
|
||||
|
||||
//@author: [piexlmax](https://github.com/piexlmax)
|
||||
//@function: GetDB
|
||||
//@description: 获取指定数据库和指定数据表的所有字段名,类型值等
|
||||
//@param: tableName string, dbName string
|
||||
//@return: err error, Columns []request.ColumnReq
|
||||
// @author: [piexlmax](https://github.com/piexlmax)
|
||||
// @function: GetDB
|
||||
// @description: 获取指定数据库和指定数据表的所有字段名,类型值等
|
||||
// @param: tableName string, dbName string
|
||||
// @return: err error, Columns []request.ColumnReq
|
||||
|
||||
func (autoCodeService *AutoCodeService) DropTable(BusinessDb, tableName string) error {
|
||||
if BusinessDb != "" {
|
||||
@@ -409,12 +463,12 @@ func (autoCodeService *AutoCodeService) DropTable(BusinessDb, tableName string)
|
||||
}
|
||||
}
|
||||
|
||||
//@author: [SliverHorn](https://github.com/SliverHorn)
|
||||
//@author: [songzhibin97](https://github.com/songzhibin97)
|
||||
//@function: addAutoMoveFile
|
||||
//@description: 生成对应的迁移文件路径
|
||||
//@param: *tplData
|
||||
//@return: null
|
||||
// @author: [SliverHorn](https://github.com/SliverHorn)
|
||||
// @author: [songzhibin97](https://github.com/songzhibin97)
|
||||
// @function: addAutoMoveFile
|
||||
// @description: 生成对应的迁移文件路径
|
||||
// @param: *tplData
|
||||
// @return: null
|
||||
|
||||
func (autoCodeService *AutoCodeService) addAutoMoveFile(data *tplData) {
|
||||
base := filepath.Base(data.autoCodePath)
|
||||
@@ -454,49 +508,49 @@ func (autoCodeService *AutoCodeService) addAutoMoveFile(data *tplData) {
|
||||
}
|
||||
}
|
||||
|
||||
//@author: [piexlmax](https://github.com/piexlmax)
|
||||
//@author: [SliverHorn](https://github.com/SliverHorn)
|
||||
//@function: CreateApi
|
||||
//@description: 自动创建api数据,
|
||||
//@param: a *model.AutoCodeStruct
|
||||
//@return: err error
|
||||
// @author: [piexlmax](https://github.com/piexlmax)
|
||||
// @author: [SliverHorn](https://github.com/SliverHorn)
|
||||
// @function: CreateApi
|
||||
// @description: 自动创建api数据,
|
||||
// @param: a *model.AutoCodeStruct
|
||||
// @return: err error
|
||||
|
||||
func (autoCodeService *AutoCodeService) AutoCreateApi(a *system.AutoCodeStruct) (ids []uint, err error) {
|
||||
apiList := []system.SysApi{
|
||||
{
|
||||
Path: "/" + a.Abbreviation + "/" + "create" + a.StructName,
|
||||
Description: "新增" + a.Description,
|
||||
ApiGroup: a.Abbreviation,
|
||||
ApiGroup: a.Description,
|
||||
Method: "POST",
|
||||
},
|
||||
{
|
||||
Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName,
|
||||
Description: "删除" + a.Description,
|
||||
ApiGroup: a.Abbreviation,
|
||||
ApiGroup: a.Description,
|
||||
Method: "DELETE",
|
||||
},
|
||||
{
|
||||
Path: "/" + a.Abbreviation + "/" + "delete" + a.StructName + "ByIds",
|
||||
Description: "批量删除" + a.Description,
|
||||
ApiGroup: a.Abbreviation,
|
||||
ApiGroup: a.Description,
|
||||
Method: "DELETE",
|
||||
},
|
||||
{
|
||||
Path: "/" + a.Abbreviation + "/" + "update" + a.StructName,
|
||||
Description: "更新" + a.Description,
|
||||
ApiGroup: a.Abbreviation,
|
||||
ApiGroup: a.Description,
|
||||
Method: "PUT",
|
||||
},
|
||||
{
|
||||
Path: "/" + a.Abbreviation + "/" + "find" + a.StructName,
|
||||
Description: "根据ID获取" + a.Description,
|
||||
ApiGroup: a.Abbreviation,
|
||||
ApiGroup: a.Description,
|
||||
Method: "GET",
|
||||
},
|
||||
{
|
||||
Path: "/" + a.Abbreviation + "/" + "get" + a.StructName + "List",
|
||||
Description: "获取" + a.Description + "列表",
|
||||
ApiGroup: a.Abbreviation,
|
||||
ApiGroup: a.Description,
|
||||
Method: "GET",
|
||||
},
|
||||
}
|
||||
@@ -581,9 +635,7 @@ func (autoCodeService *AutoCodeService) getNeedList(autoCode *system.AutoCodeStr
|
||||
func injectionCode(structName string, bf *strings.Builder) error {
|
||||
for _, meta := range injectionPaths {
|
||||
code := fmt.Sprintf(meta.structNameF, structName)
|
||||
if err := utils.AutoInjectionCode(meta.path, meta.funcName, code); err != nil {
|
||||
return err
|
||||
}
|
||||
ast2.ImportForAutoEnter(meta.path, meta.funcName, code)
|
||||
bf.WriteString(fmt.Sprintf("%s@%s@%s;", meta.path, meta.funcName, code))
|
||||
}
|
||||
return nil
|
||||
@@ -657,179 +709,13 @@ func (autoCodeService *AutoCodeService) CreatePackageTemp(packageName string) er
|
||||
// 创建完成后在对应的位置插入结构代码
|
||||
for _, v := range pendingTemp {
|
||||
meta := packageInjectionMap[v.name]
|
||||
if err := ImportReference(meta.path, fmt.Sprintf(meta.importCodeF, v.name, packageName), fmt.Sprintf(meta.structNameF, caser.String(packageName)), fmt.Sprintf(meta.packageNameF, packageName), meta.groupName); err != nil {
|
||||
if err := ast2.ImportReference(meta.path, fmt.Sprintf(meta.importCodeF, v.name, packageName), fmt.Sprintf(meta.structNameF, utils.FirstUpper(packageName)), fmt.Sprintf(meta.packageNameF, packageName), meta.groupName); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Visitor struct {
|
||||
ImportCode string
|
||||
StructName string
|
||||
PackageName string
|
||||
GroupName string
|
||||
}
|
||||
|
||||
func (vi *Visitor) Visit(node ast.Node) ast.Visitor {
|
||||
switch n := node.(type) {
|
||||
case *ast.GenDecl:
|
||||
// 查找有没有import context包
|
||||
// Notice:没有考虑没有import任何包的情况
|
||||
if n.Tok == token.IMPORT && vi.ImportCode != "" {
|
||||
vi.addImport(n)
|
||||
// 不需要再遍历子树
|
||||
return nil
|
||||
}
|
||||
if n.Tok == token.TYPE && vi.StructName != "" && vi.PackageName != "" && vi.GroupName != "" {
|
||||
vi.addStruct(n)
|
||||
return nil
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
if n.Name.Name == "Routers" {
|
||||
vi.addFuncBodyVar(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
}
|
||||
return vi
|
||||
}
|
||||
|
||||
func (vi *Visitor) addStruct(genDecl *ast.GenDecl) ast.Visitor {
|
||||
for i := range genDecl.Specs {
|
||||
switch n := genDecl.Specs[i].(type) {
|
||||
case *ast.TypeSpec:
|
||||
if strings.Index(n.Name.Name, "Group") > -1 {
|
||||
switch t := n.Type.(type) {
|
||||
case *ast.StructType:
|
||||
f := &ast.Field{
|
||||
Names: []*ast.Ident{
|
||||
{
|
||||
Name: vi.StructName,
|
||||
Obj: &ast.Object{
|
||||
Kind: ast.Var,
|
||||
Name: vi.StructName,
|
||||
},
|
||||
},
|
||||
},
|
||||
Type: &ast.SelectorExpr{
|
||||
X: &ast.Ident{
|
||||
Name: vi.PackageName,
|
||||
},
|
||||
Sel: &ast.Ident{
|
||||
Name: vi.GroupName,
|
||||
},
|
||||
},
|
||||
}
|
||||
t.Fields.List = append(t.Fields.List, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return vi
|
||||
}
|
||||
|
||||
func (vi *Visitor) addImport(genDecl *ast.GenDecl) ast.Visitor {
|
||||
// 是否已经import
|
||||
hasImported := false
|
||||
for _, v := range genDecl.Specs {
|
||||
importSpec := v.(*ast.ImportSpec)
|
||||
// 如果已经包含
|
||||
if importSpec.Path.Value == strconv.Quote(vi.ImportCode) {
|
||||
hasImported = true
|
||||
}
|
||||
}
|
||||
if !hasImported {
|
||||
genDecl.Specs = append(genDecl.Specs, &ast.ImportSpec{
|
||||
Path: &ast.BasicLit{
|
||||
Kind: token.STRING,
|
||||
Value: strconv.Quote(vi.ImportCode),
|
||||
},
|
||||
})
|
||||
}
|
||||
return vi
|
||||
}
|
||||
|
||||
func (vi *Visitor) addFuncBodyVar(funDecl *ast.FuncDecl) ast.Visitor {
|
||||
hasVar := false
|
||||
for _, v := range funDecl.Body.List {
|
||||
switch varSpec := v.(type) {
|
||||
case *ast.AssignStmt:
|
||||
for i := range varSpec.Lhs {
|
||||
switch nn := varSpec.Lhs[i].(type) {
|
||||
case *ast.Ident:
|
||||
if nn.Name == vi.PackageName+"Router" {
|
||||
hasVar = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasVar {
|
||||
assignStmt := &ast.AssignStmt{
|
||||
Lhs: []ast.Expr{
|
||||
&ast.Ident{
|
||||
Name: vi.PackageName + "Router",
|
||||
Obj: &ast.Object{
|
||||
Kind: ast.Var,
|
||||
Name: vi.PackageName + "Router",
|
||||
},
|
||||
},
|
||||
},
|
||||
Tok: token.DEFINE,
|
||||
Rhs: []ast.Expr{
|
||||
&ast.SelectorExpr{
|
||||
X: &ast.SelectorExpr{
|
||||
X: &ast.Ident{
|
||||
Name: "router",
|
||||
},
|
||||
Sel: &ast.Ident{
|
||||
Name: "RouterGroupApp",
|
||||
},
|
||||
},
|
||||
Sel: &ast.Ident{
|
||||
Name: caser.String(vi.PackageName),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
funDecl.Body.List = append(funDecl.Body.List, funDecl.Body.List[1])
|
||||
index := 1
|
||||
copy(funDecl.Body.List[index+1:], funDecl.Body.List[index:])
|
||||
funDecl.Body.List[index] = assignStmt
|
||||
}
|
||||
return vi
|
||||
}
|
||||
|
||||
func ImportReference(filepath, importCode, structName, packageName, groupName string) error {
|
||||
fSet := token.NewFileSet()
|
||||
fParser, err := parser.ParseFile(fSet, filepath, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
importCode = strings.TrimSpace(importCode)
|
||||
v := &Visitor{
|
||||
ImportCode: importCode,
|
||||
StructName: structName,
|
||||
PackageName: packageName,
|
||||
GroupName: groupName,
|
||||
}
|
||||
if importCode == "" {
|
||||
ast.Print(fSet, fParser)
|
||||
}
|
||||
|
||||
ast.Walk(v, fParser)
|
||||
|
||||
var output []byte
|
||||
buffer := bytes.NewBuffer(output)
|
||||
err = format.Node(buffer, fSet, fParser)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// 写回数据
|
||||
return os.WriteFile(filepath, buffer.Bytes(), 0o600)
|
||||
}
|
||||
|
||||
// CreatePlug 自动创建插件模板
|
||||
func (autoCodeService *AutoCodeService) CreatePlug(plug system.AutoPlugReq) error {
|
||||
// 检查列表参数是否有效
|
||||
@@ -889,36 +775,44 @@ func (autoCodeService *AutoCodeService) InstallPlugin(file *multipart.FileHeader
|
||||
paths = filterFile(paths)
|
||||
var webIndex = -1
|
||||
var serverIndex = -1
|
||||
webPlugin := ""
|
||||
serverPlugin := ""
|
||||
|
||||
for i := range paths {
|
||||
paths[i] = filepath.ToSlash(paths[i])
|
||||
pathArr := strings.Split(paths[i], "/")
|
||||
ln := len(pathArr)
|
||||
if ln < 2 {
|
||||
|
||||
if ln < 4 {
|
||||
continue
|
||||
}
|
||||
if pathArr[ln-2] == "server" && pathArr[ln-1] == "plugin" {
|
||||
serverIndex = i
|
||||
if pathArr[2]+"/"+pathArr[3] == `server/plugin` && len(serverPlugin) == 0 {
|
||||
serverPlugin = path.Join(pathArr[0], pathArr[1], pathArr[2], pathArr[3])
|
||||
}
|
||||
if pathArr[ln-2] == "web" && pathArr[ln-1] == "plugin" {
|
||||
webIndex = i
|
||||
if pathArr[2]+"/"+pathArr[3] == `web/plugin` && len(webPlugin) == 0 {
|
||||
webPlugin = path.Join(pathArr[0], pathArr[1], pathArr[2], pathArr[3])
|
||||
}
|
||||
}
|
||||
if webIndex == -1 && serverIndex == -1 {
|
||||
if len(serverPlugin) == 0 && len(webPlugin) == 0 {
|
||||
zap.L().Error("非标准插件,请按照文档自动迁移使用")
|
||||
return webIndex, serverIndex, errors.New("非标准插件,请按照文档自动迁移使用")
|
||||
}
|
||||
|
||||
if webIndex != -1 {
|
||||
err = installation(paths[webIndex], global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.Web)
|
||||
if len(serverPlugin) != 0 {
|
||||
err = installation(serverPlugin, global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.Server)
|
||||
if err != nil {
|
||||
return webIndex, serverIndex, err
|
||||
}
|
||||
}
|
||||
|
||||
if serverIndex != -1 {
|
||||
err = installation(paths[serverIndex], global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.Server)
|
||||
if len(webPlugin) != 0 {
|
||||
err = installation(webPlugin, global.GVA_CONFIG.AutoCode.Server, global.GVA_CONFIG.AutoCode.Web)
|
||||
if err != nil {
|
||||
return webIndex, serverIndex, err
|
||||
}
|
||||
}
|
||||
return webIndex, serverIndex, err
|
||||
|
||||
return 1, 1, err
|
||||
}
|
||||
|
||||
func installation(path string, formPath string, toPath string) error {
|
||||
@@ -956,3 +850,111 @@ func skipMacSpecialDocument(src string) (bool, error) {
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (autoCodeService *AutoCodeService) PubPlug(plugName string) (zipPath string, err error) {
|
||||
if plugName == "" {
|
||||
return "", errors.New("插件名称不能为空")
|
||||
}
|
||||
|
||||
// 防止路径穿越
|
||||
plugName = filepath.Clean(plugName)
|
||||
|
||||
webPath := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Web, "plugin", plugName)
|
||||
serverPath := filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server, "plugin", plugName)
|
||||
// 创建一个新的zip文件
|
||||
|
||||
// 判断目录是否存在
|
||||
_, err = os.Stat(webPath)
|
||||
if err != nil {
|
||||
return "", errors.New("web路径不存在")
|
||||
}
|
||||
_, err = os.Stat(serverPath)
|
||||
if err != nil {
|
||||
return "", errors.New("server路径不存在")
|
||||
}
|
||||
|
||||
fileName := plugName + ".zip"
|
||||
// 创建一个新的zip文件
|
||||
zipFile, err := os.Create(fileName)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer zipFile.Close()
|
||||
|
||||
// 创建一个zip写入器
|
||||
zipWriter := zip.NewWriter(zipFile)
|
||||
defer zipWriter.Close()
|
||||
|
||||
webHeaderName := filepath.Join(plugName, "web", "plugin", plugName)
|
||||
err = autoCodeService.doZip(zipWriter, webPath, webHeaderName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
serverHeaderName := filepath.Join(plugName, "server", "plugin", plugName)
|
||||
err = autoCodeService.doZip(zipWriter, serverPath, serverHeaderName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return filepath.Join(global.GVA_CONFIG.AutoCode.Root, global.GVA_CONFIG.AutoCode.Server, fileName), nil
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
|
||||
zipWriter zip写入器
|
||||
serverPath 存储的路径
|
||||
headerName 写有zip的路径
|
||||
|
||||
*
|
||||
*/
|
||||
func (autoCodeService *AutoCodeService) doZip(zipWriter *zip.Writer, serverPath, headerName string) (err error) {
|
||||
// 遍历serverPath目录并将所有非隐藏文件添加到zip归档中
|
||||
err = filepath.Walk(serverPath, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 跳过隐藏文件和目录
|
||||
if strings.HasPrefix(info.Name(), ".") {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 创建一个新的文件头
|
||||
header, err := zip.FileInfoHeader(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 将文件头的名称设置为文件的相对路径
|
||||
rel, _ := filepath.Rel(serverPath, path)
|
||||
header.Name = filepath.Join(headerName, rel)
|
||||
// 目录需要拼上一个 "/" ,否则会出现一个和目录一样的文件在压缩包中
|
||||
if info.IsDir() {
|
||||
header.Name += "/"
|
||||
}
|
||||
// 将文件添加到zip归档中
|
||||
writer, err := zipWriter.CreateHeader(header)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 打开文件并将其内容复制到zip归档中
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
_, err = io.Copy(writer, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -19,20 +19,25 @@ func (autoCodeService *AutoCodeService) Database(businessDB string) Database {
|
||||
return AutoCodeMysql
|
||||
case "pgsql":
|
||||
return AutoCodePgsql
|
||||
case "sqlite":
|
||||
return AutoCodeSqlite
|
||||
default:
|
||||
return AutoCodeMysql
|
||||
}
|
||||
} else {
|
||||
for _, info := range global.GVA_CONFIG.DBList {
|
||||
if info.AliasName == businessDB {
|
||||
|
||||
switch info.Type {
|
||||
case "mysql":
|
||||
return AutoCodeMysql
|
||||
case "mssql":
|
||||
return AutoCodeMssql
|
||||
case "pgsql":
|
||||
return AutoCodePgsql
|
||||
case "oracle":
|
||||
return AutoCodeOracle
|
||||
case "sqlite":
|
||||
return AutoCodeSqlite
|
||||
default:
|
||||
return AutoCodeMysql
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
|
||||
)
|
||||
|
||||
var AutoCodeMssql = new(autoCodeMssql)
|
||||
|
||||
type autoCodeMssql struct{}
|
||||
|
||||
// GetDB 获取数据库的所有数据库名
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||||
func (s *autoCodeMssql) GetDB(businessDB string) (data []response.Db, err error) {
|
||||
var entities []response.Db
|
||||
sql := "select name AS 'database' from sysdatabases;"
|
||||
if businessDB == "" {
|
||||
err = global.GVA_DB.Raw(sql).Scan(&entities).Error
|
||||
} else {
|
||||
err = global.GVA_DBList[businessDB].Raw(sql).Scan(&entities).Error
|
||||
}
|
||||
return entities, err
|
||||
}
|
||||
|
||||
// GetTables 获取数据库的所有表名
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||||
func (s *autoCodeMssql) GetTables(businessDB string, dbName string) (data []response.Table, err error) {
|
||||
var entities []response.Table
|
||||
|
||||
sql := fmt.Sprintf(`select name as 'table_name' from %s.DBO.sysobjects where xtype='U'`, dbName)
|
||||
if businessDB == "" {
|
||||
err = global.GVA_DB.Raw(sql).Scan(&entities).Error
|
||||
} else {
|
||||
err = global.GVA_DBList[businessDB].Raw(sql).Scan(&entities).Error
|
||||
}
|
||||
|
||||
return entities, err
|
||||
}
|
||||
|
||||
// GetColumn 获取指定数据库和指定数据表的所有字段名,类型值等
|
||||
// Author [piexlmax](https://github.com/piexlmax)
|
||||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||||
func (s *autoCodeMssql) GetColumn(businessDB string, tableName string, dbName string) (data []response.Column, err error) {
|
||||
var entities []response.Column
|
||||
sql := fmt.Sprintf(`
|
||||
SELECT
|
||||
sc.name AS column_name,
|
||||
st.name AS data_type,
|
||||
sc.length AS data_type_long,
|
||||
CASE
|
||||
WHEN pk.index_id IS NOT NULL THEN 1
|
||||
ELSE 0
|
||||
END AS primary_key
|
||||
FROM
|
||||
%s.DBO.syscolumns sc
|
||||
JOIN
|
||||
systypes st ON sc.xtype=st.xtype
|
||||
LEFT JOIN
|
||||
%s.DBO.sysobjects so ON so.name='%s' AND so.xtype='U'
|
||||
LEFT JOIN
|
||||
%s.DBO.sysindexes si ON si.id = so.id AND si.indid < 2
|
||||
LEFT JOIN
|
||||
%s.DBO.sysindexkeys sik ON sik.id = si.id AND sik.indid = si.indid AND sik.colid = sc.colid
|
||||
LEFT JOIN
|
||||
%s.DBO.syskeyconstraints pk ON pk.constid = sik.constid
|
||||
WHERE
|
||||
st.usertype=0 AND sc.id = so.id
|
||||
`, dbName, dbName, tableName, dbName, dbName, dbName)
|
||||
|
||||
if businessDB == "" {
|
||||
err = global.GVA_DB.Raw(sql).Scan(&entities).Error
|
||||
} else {
|
||||
err = global.GVA_DBList[businessDB].Raw(sql).Scan(&entities).Error
|
||||
}
|
||||
|
||||
return entities, err
|
||||
}
|
||||
@@ -44,21 +44,32 @@ func (s *autoCodeMysql) GetTables(businessDB string, dbName string) (data []resp
|
||||
func (s *autoCodeMysql) GetColumn(businessDB string, tableName string, dbName string) (data []response.Column, err error) {
|
||||
var entities []response.Column
|
||||
sql := `
|
||||
SELECT COLUMN_NAME column_name,
|
||||
DATA_TYPE data_type,
|
||||
CASE DATA_TYPE
|
||||
WHEN 'longtext' THEN c.CHARACTER_MAXIMUM_LENGTH
|
||||
WHEN 'varchar' THEN c.CHARACTER_MAXIMUM_LENGTH
|
||||
WHEN 'double' THEN CONCAT_WS(',', c.NUMERIC_PRECISION, c.NUMERIC_SCALE)
|
||||
WHEN 'decimal' THEN CONCAT_WS(',', c.NUMERIC_PRECISION, c.NUMERIC_SCALE)
|
||||
WHEN 'int' THEN c.NUMERIC_PRECISION
|
||||
WHEN 'bigint' THEN c.NUMERIC_PRECISION
|
||||
ELSE '' END AS data_type_long,
|
||||
COLUMN_COMMENT column_comment
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c
|
||||
WHERE table_name = ?
|
||||
AND table_schema = ?
|
||||
`
|
||||
SELECT
|
||||
c.COLUMN_NAME column_name,
|
||||
c.DATA_TYPE data_type,
|
||||
CASE c.DATA_TYPE
|
||||
WHEN 'longtext' THEN c.CHARACTER_MAXIMUM_LENGTH
|
||||
WHEN 'varchar' THEN c.CHARACTER_MAXIMUM_LENGTH
|
||||
WHEN 'double' THEN CONCAT_WS(',', c.NUMERIC_PRECISION, c.NUMERIC_SCALE)
|
||||
WHEN 'decimal' THEN CONCAT_WS(',', c.NUMERIC_PRECISION, c.NUMERIC_SCALE)
|
||||
WHEN 'int' THEN c.NUMERIC_PRECISION
|
||||
WHEN 'bigint' THEN c.NUMERIC_PRECISION
|
||||
ELSE ''
|
||||
END AS data_type_long,
|
||||
c.COLUMN_COMMENT column_comment,
|
||||
CASE WHEN kcu.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS primary_key
|
||||
FROM
|
||||
INFORMATION_SCHEMA.COLUMNS c
|
||||
LEFT JOIN
|
||||
INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
|
||||
ON
|
||||
c.TABLE_SCHEMA = kcu.TABLE_SCHEMA
|
||||
AND c.TABLE_NAME = kcu.TABLE_NAME
|
||||
AND c.COLUMN_NAME = kcu.COLUMN_NAME
|
||||
AND kcu.CONSTRAINT_NAME = 'PRIMARY'
|
||||
WHERE
|
||||
c.TABLE_NAME = ?
|
||||
AND c.TABLE_SCHEMA = ?;`
|
||||
if businessDB == "" {
|
||||
err = global.GVA_DB.Raw(sql, tableName, dbName).Scan(&entities).Error
|
||||
} else {
|
||||
|
||||
@@ -15,7 +15,6 @@ type autoCodeOracle struct{}
|
||||
func (s *autoCodeOracle) GetDB(businessDB string) (data []response.Db, err error) {
|
||||
var entities []response.Db
|
||||
sql := `SELECT lower(username) AS "database" FROM all_users`
|
||||
|
||||
err = global.GVA_DBList[businessDB].Raw(sql).Scan(&entities).Error
|
||||
return entities, err
|
||||
}
|
||||
@@ -37,16 +36,32 @@ func (s *autoCodeOracle) GetTables(businessDB string, dbName string) (data []res
|
||||
func (s *autoCodeOracle) GetColumn(businessDB string, tableName string, dbName string) (data []response.Column, err error) {
|
||||
var entities []response.Column
|
||||
sql := `
|
||||
select lower(a.COLUMN_NAME) as "column_name",
|
||||
(CASE WHEN a.DATA_TYPE = 'NUMBER' AND a.DATA_SCALE=0 THEN 'int' else lower(a.DATA_TYPE) end) as "data_type",
|
||||
(CASE WHEN a.DATA_TYPE = 'NUMBER' THEN a.DATA_PRECISION else a.DATA_LENGTH end) as "data_type_long",
|
||||
b.COMMENTS as "column_comment"
|
||||
from all_tab_columns a , all_col_comments b
|
||||
where a.OWNER = b.OWNER
|
||||
and a.TABLE_NAME = b.TABLE_NAME
|
||||
and a.COLUMN_NAME = b.COLUMN_NAME
|
||||
and lower(a.table_name) = ?
|
||||
and lower(a.OWNER) = ?
|
||||
SELECT
|
||||
lower(a.COLUMN_NAME) as "column_name",
|
||||
(CASE WHEN a.DATA_TYPE = 'NUMBER' AND a.DATA_SCALE=0 THEN 'int' else lower(a.DATA_TYPE) end) as "data_type",
|
||||
(CASE WHEN a.DATA_TYPE = 'NUMBER' THEN a.DATA_PRECISION else a.DATA_LENGTH end) as "data_type_long",
|
||||
b.COMMENTS as "column_comment",
|
||||
(CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END) as "primary_key"
|
||||
FROM
|
||||
all_tab_columns a
|
||||
JOIN
|
||||
all_col_comments b ON a.OWNER = b.OWNER AND a.TABLE_NAME = b.TABLE_NAME AND a.COLUMN_NAME = b.COLUMN_NAME
|
||||
LEFT JOIN
|
||||
(
|
||||
SELECT
|
||||
acc.OWNER,
|
||||
acc.TABLE_NAME,
|
||||
acc.COLUMN_NAME
|
||||
FROM
|
||||
all_cons_columns acc
|
||||
JOIN
|
||||
all_constraints ac ON acc.OWNER = ac.OWNER AND acc.CONSTRAINT_NAME = ac.CONSTRAINT_NAME
|
||||
WHERE
|
||||
ac.CONSTRAINT_TYPE = 'P'
|
||||
) pk ON a.OWNER = pk.OWNER AND a.TABLE_NAME = pk.TABLE_NAME AND a.COLUMN_NAME = pk.COLUMN_NAME
|
||||
WHERE
|
||||
lower(a.table_name) = ?
|
||||
AND lower(a.OWNER) = ?;
|
||||
`
|
||||
|
||||
err = global.GVA_DBList[businessDB].Raw(sql, tableName, dbName).Scan(&entities).Error
|
||||
|
||||
@@ -3,10 +3,6 @@ package system
|
||||
import (
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var AutoCodePgsql = new(autoCodePgsql)
|
||||
@@ -34,9 +30,10 @@ func (a *autoCodePgsql) GetDB(businessDB string) (data []response.Db, err error)
|
||||
func (a *autoCodePgsql) GetTables(businessDB string, dbName string) (data []response.Table, err error) {
|
||||
var entities []response.Table
|
||||
sql := `select table_name as table_name from information_schema.tables where table_catalog = ? and table_schema = ?`
|
||||
db, _err := gorm.Open(postgres.Open(global.GVA_CONFIG.Pgsql.LinkDsn(dbName)), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
|
||||
if _err != nil {
|
||||
return nil, errors.Wrapf(err, "[pgsql] 连接 数据库(%s)的表失败!", dbName)
|
||||
|
||||
db := global.GVA_DB
|
||||
if businessDB != "" {
|
||||
db = global.GVA_DBList[businessDB]
|
||||
}
|
||||
|
||||
err = db.Raw(sql, dbName, "public").Scan(&entities).Error
|
||||
@@ -49,60 +46,87 @@ func (a *autoCodePgsql) GetTables(businessDB string, dbName string) (data []resp
|
||||
func (a *autoCodePgsql) GetColumn(businessDB string, tableName string, dbName string) (data []response.Column, err error) {
|
||||
// todo 数据获取不全, 待完善sql
|
||||
sql := `
|
||||
SELECT psc.COLUMN_NAME AS COLUMN_NAME,
|
||||
psc.udt_name AS data_type,
|
||||
CASE
|
||||
psc.udt_name
|
||||
WHEN 'text' THEN
|
||||
concat_ws ( '', '', psc.CHARACTER_MAXIMUM_LENGTH )
|
||||
WHEN 'varchar' THEN
|
||||
concat_ws ( '', '', psc.CHARACTER_MAXIMUM_LENGTH )
|
||||
WHEN 'smallint' THEN
|
||||
concat_ws ( ',', psc.NUMERIC_PRECISION, psc.NUMERIC_SCALE )
|
||||
WHEN 'decimal' THEN
|
||||
concat_ws ( ',', psc.NUMERIC_PRECISION, psc.NUMERIC_SCALE )
|
||||
WHEN 'integer' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'int4' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'int8' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'bigint' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'timestamp' THEN
|
||||
concat_ws ( '', '', psc.datetime_precision )
|
||||
ELSE ''
|
||||
END AS data_type_long,
|
||||
(
|
||||
SELECT
|
||||
pd.description
|
||||
FROM
|
||||
pg_description pd
|
||||
WHERE
|
||||
(pd.objoid,pd.objsubid) in (
|
||||
SELECT pa.attrelid,pa.attnum
|
||||
FROM
|
||||
pg_attribute pa
|
||||
WHERE pa.attrelid = ( SELECT oid FROM pg_class pc WHERE
|
||||
pc.relname = psc.table_name
|
||||
SELECT
|
||||
psc.COLUMN_NAME AS COLUMN_NAME,
|
||||
psc.udt_name AS data_type,
|
||||
CASE
|
||||
psc.udt_name
|
||||
WHEN 'text' THEN
|
||||
concat_ws ( '', '', psc.CHARACTER_MAXIMUM_LENGTH )
|
||||
WHEN 'varchar' THEN
|
||||
concat_ws ( '', '', psc.CHARACTER_MAXIMUM_LENGTH )
|
||||
WHEN 'smallint' THEN
|
||||
concat_ws ( ',', psc.NUMERIC_PRECISION, psc.NUMERIC_SCALE )
|
||||
WHEN 'decimal' THEN
|
||||
concat_ws ( ',', psc.NUMERIC_PRECISION, psc.NUMERIC_SCALE )
|
||||
WHEN 'integer' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'int4' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'int8' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'bigint' THEN
|
||||
concat_ws ( '', '', psc.NUMERIC_PRECISION )
|
||||
WHEN 'timestamp' THEN
|
||||
concat_ws ( '', '', psc.datetime_precision )
|
||||
ELSE ''
|
||||
END AS data_type_long,
|
||||
(
|
||||
SELECT
|
||||
pd.description
|
||||
FROM
|
||||
pg_description pd
|
||||
WHERE
|
||||
(pd.objoid,pd.objsubid) in (
|
||||
SELECT pa.attrelid,pa.attnum
|
||||
FROM
|
||||
pg_attribute pa
|
||||
WHERE pa.attrelid = ( SELECT oid FROM pg_class pc WHERE
|
||||
pc.relname = psc.table_name
|
||||
)
|
||||
and attname = psc.column_name
|
||||
)
|
||||
and attname = psc.column_name
|
||||
)
|
||||
) AS column_comment
|
||||
) AS column_comment,
|
||||
(
|
||||
SELECT
|
||||
COUNT(*)
|
||||
FROM
|
||||
pg_constraint
|
||||
WHERE
|
||||
contype = 'p'
|
||||
AND conrelid = (
|
||||
SELECT
|
||||
oid
|
||||
FROM
|
||||
pg_class
|
||||
WHERE
|
||||
relname = psc.table_name
|
||||
)
|
||||
AND conkey::int[] @> ARRAY[(
|
||||
SELECT
|
||||
attnum
|
||||
FROM
|
||||
pg_attribute
|
||||
WHERE
|
||||
attrelid = conrelid
|
||||
AND attname = psc.column_name
|
||||
)]
|
||||
) > 0 AS primary_key
|
||||
FROM
|
||||
INFORMATION_SCHEMA.COLUMNS psc
|
||||
INFORMATION_SCHEMA.COLUMNS psc
|
||||
WHERE
|
||||
table_catalog = ?
|
||||
AND table_schema = 'public'
|
||||
AND TABLE_NAME = ?;
|
||||
`
|
||||
table_catalog = ?
|
||||
AND table_schema = 'public'
|
||||
AND TABLE_NAME = ?;
|
||||
`
|
||||
var entities []response.Column
|
||||
db, _err := gorm.Open(postgres.Open(global.GVA_CONFIG.Pgsql.LinkDsn(dbName)), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
|
||||
if _err != nil {
|
||||
return nil, errors.Wrapf(err, "[pgsql] 连接 数据库(%s)的表(%s)失败!", dbName, tableName)
|
||||
}
|
||||
//sql = strings.ReplaceAll(sql, "@table_catalog", dbName)
|
||||
//sql = strings.ReplaceAll(sql, "@table_name", tableName)
|
||||
db := global.GVA_DB
|
||||
if businessDB != "" {
|
||||
db = global.GVA_DBList[businessDB]
|
||||
}
|
||||
|
||||
err = db.Raw(sql, dbName, tableName).Scan(&entities).Error
|
||||
return entities, err
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user