+
+5.如果您需要服务器的话 2C4G8M 80GB 腾讯云 一年70 三年198 在这里购买:https://curl.qcloud.com/tJrn0bK0
+
## 1. 基本介绍
### 1.1 项目介绍
-> Gin-vue-admin是一个基于 [vue](https://vuejs.org) 和 [gin](https://gin-gonic.com) 开发的全栈前后端分离的后台管理系统,集成jwt鉴权,动态路由,动态菜单,casbin鉴权,表单生成器,代码生成器等功能,提供多种示例文件,让您把更多时间专注在业务开发上。
+> Gin-vue-admin是一个基于 [vue](https://vuejs.org) 和 [gin](https://gin-gonic.com) 开发的全栈前后端分离的开发基础平台,集成jwt鉴权,动态路由,动态菜单,casbin鉴权,表单生成器,代码生成器等功能,提供多种示例文件,让您把更多时间专注在业务开发上。
[在线预览](http://demo.gin-vue-admin.com): http://demo.gin-vue-admin.com
@@ -52,7 +58,7 @@
### 1.2 贡献指南
Hi! 首先感谢你使用 gin-vue-admin。
-Gin-vue-admin 是一套为后台管理平台准备的一整套前后端分离架构式的开源框架,旨在快速搭建后台管理系统。
+Gin-vue-admin 是一套为快速研发准备的一整套前后端分离架构式的开源框架,旨在快速搭建中小型项目。
Gin-vue-admin 的成长离不开大家的支持,如果你愿意为 gin-vue-admin 贡献代码或提供建议,请阅读以下内容。
diff --git a/deployment/server/gva-server-configmap.yaml b/deployment/server/gva-server-configmap.yaml
new file mode 100644
index 00000000..fb889fb7
--- /dev/null
+++ b/deployment/server/gva-server-configmap.yaml
@@ -0,0 +1,148 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: config.yaml
+ annotations:
+ flipped-aurora/gin-vue-admin: backend
+ github: "https://github.com/flipped-aurora/gin-vue-admin.git"
+ app.kubernetes.io/version: 0.0.1
+ labels:
+ app: gva-server
+ version: gva-vue3
+data:
+ config.yaml: |
+ # github.com/flipped-aurora/gin-vue-admin/server Global Configuration
+
+ # jwt configuration
+ jwt:
+ signing-key: 'qmPlus'
+ expires-time: 604800
+ buffer-time: 86400
+
+ # zap logger configuration
+ zap:
+ level: 'info'
+ format: 'console'
+ prefix: '[github.com/flipped-aurora/gin-vue-admin/server]'
+ director: 'log'
+ link-name: 'latest_log'
+ show-line: true
+ encode-level: 'LowercaseColorLevelEncoder'
+ stacktrace-key: 'stacktrace'
+ log-in-console: true
+
+ # redis configuration
+ redis:
+ db: 0
+ addr: '127.0.0.1:6379'
+ password: ''
+
+ # email configuration
+ email:
+ to: 'xxx@qq.com'
+ port: 465
+ from: 'xxx@163.com'
+ host: 'smtp.163.com'
+ is-ssl: true
+ secret: 'xxx'
+ nickname: 'test'
+
+ # casbin configuration
+ casbin:
+ model-path: './resource/rbac_model.conf'
+
+ # system configuration
+ system:
+ env: 'develop' # Change to "develop" to skip authentication for development mode
+ addr: 8888
+ db-type: 'mysql'
+ oss-type: 'local' # 控制oss选择走本期还是 七牛等其他仓 自行增加其他oss仓可以在 server/utils/upload/upload.go 中 NewOss函数配置
+ use-multipoint: false
+
+ # captcha configuration
+ captcha:
+ key-long: 6
+ img-width: 240
+ img-height: 80
+
+ # mysql connect configuration
+ # 未初始化之前请勿手动修改数据库信息!!!如果一定要手动初始化请看(https://www.github.com/flipped-aurora/gin-vue-admin/server.com/docs/first)
+ mysql:
+ path: ''
+ config: ''
+ db-name: ''
+ username: ''
+ password: ''
+ max-idle-conns: 10
+ max-open-conns: 100
+ log-mode: false
+ log-zap: ""
+
+ # local configuration
+ local:
+ path: 'uploads/file'
+
+ # autocode configuration
+ autocode:
+ transfer-restart: true
+ root: ""
+ server: /server
+ server-api: /api/v1/autocode
+ server-initialize: /initialize
+ server-model: /model/autocode
+ server-request: /model/autocode/request/
+ server-router: /router/autocode
+ server-service: /service/autocode
+ web: /web/src
+ web-api: /api
+ web-flow: /view
+ web-form: /view
+ web-table: /view
+
+ # qiniu configuration (请自行七牛申请对应的 公钥 私钥 bucket 和 域名地址)
+ qiniu:
+ zone: 'ZoneHuaDong'
+ bucket: ''
+ img-path: ''
+ use-https: false
+ access-key: ''
+ secret-key: ''
+ use-cdn-domains: false
+
+
+ # aliyun oss configuration
+ aliyun-oss:
+ endpoint: 'yourEndpoint'
+ access-key-id: 'yourAccessKeyId'
+ access-key-secret: 'yourAccessKeySecret'
+ bucket-name: 'yourBucketName'
+ bucket-url: 'yourBucketUrl'
+ base-path: 'yourBasePath'
+
+ # tencent cos configuration
+ tencent-cos:
+ bucket: 'xxxxx-10005608'
+ region: 'ap-shanghai'
+ secret-id: 'xxxxxxxx'
+ secret-key: 'xxxxxxxx'
+ base-url: 'https://gin.vue.admin'
+ path-prefix: 'github.com/flipped-aurora/gin-vue-admin/server'
+
+ # excel configuration
+ 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: 需要清理的表名
+ # compareField: 需要比较时间的字段
+ # interval: 时间间隔, 具体配置详看 time.ParseDuration() 中字符串表示 且不能为负数
+ # 2160h = 24 * 30 * 3 -> 三个月
+ { tableName: "sys_operation_records" , compareField: "created_at", interval: "2160h" },
+ { tableName: "jwt_blacklists" , compareField: "created_at", interval: "168h" }
+ #{ tableName: "log2" , compareField: "created_at", interval: "2160h" }
+ ]
diff --git a/deployment/server/gva-server-deployment.yaml b/deployment/server/gva-server-deployment.yaml
new file mode 100644
index 00000000..d89dcb63
--- /dev/null
+++ b/deployment/server/gva-server-deployment.yaml
@@ -0,0 +1,68 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: gva-server
+ annotations:
+ flipped-aurora/gin-vue-admin: backend
+ github: "https://github.com/flipped-aurora/gin-vue-admin.git"
+ app.kubernetes.io/version: 0.0.1
+ labels:
+ app: gva-server
+ version: gva-vue3
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: gva-server
+ version: gva-vue3
+ template:
+ metadata:
+ labels:
+ app: gva-server
+ version: gva-vue3
+ spec:
+ containers:
+ - name: gin-vue-admin-container
+ image: registry.cn-hangzhou.aliyuncs.com/gin-vue-admin/server:40fc3aa6
+ imagePullPolicy: IfNotPresent
+ ports:
+ - containerPort: 8888
+ name: http
+ volumeMounts:
+ - mountPath: /go/src/github.com/flipped-aurora/gin-vue-admin/server/config.yaml
+ name: config
+ subPath: config.yaml
+ - mountPath: /etc/localtime
+ name: localtime
+ resources:
+ limits:
+ cpu: 1000m
+ memory: 2000Mi
+ requests:
+ cpu: 100m
+ memory: 200Mi
+# readinessProbe:
+# httpGet:
+# path: /ready
+# port: http
+# initialDelaySeconds: 20
+# periodSeconds: 10
+# successThreshold: 1
+# failureThreshold: 3
+# livenessProbe:
+# httpGet:
+# path: /health
+# port: http
+# initialDelaySeconds: 20
+# periodSeconds: 10
+# successThreshold: 1
+# failureThreshold: 3
+ #imagePullSecrets:
+ # - name: docker-registry
+ volumes:
+ - name: localtime
+ hostPath:
+ path: /etc/localtime
+ - name: config
+ configMap:
+ name: config.yaml
\ No newline at end of file
diff --git a/deployment/server/gva-server-service.yaml b/deployment/server/gva-server-service.yaml
new file mode 100644
index 00000000..17aaef2c
--- /dev/null
+++ b/deployment/server/gva-server-service.yaml
@@ -0,0 +1,21 @@
+apiVersion: v1
+kind: Service
+metadata:
+ name: gva-server
+ annotations:
+ flipped-aurora/gin-vue-admin: backend
+ github: "https://github.com/flipped-aurora/gin-vue-admin.git"
+ app.kubernetes.io/version: 0.0.1
+ labels:
+ app: gva-server
+ version: gva-vue3
+spec:
+ selector:
+ app: gva-server
+ version: gva-vue3
+ ports:
+ - port: 8888
+ name: http
+ targetPort: 8888
+ type: ClusterIP
+# type: NodePort
diff --git a/deployment/web/gva-web-configmap.yaml b/deployment/web/gva-web-configmap.yaml
new file mode 100644
index 00000000..189b8617
--- /dev/null
+++ b/deployment/web/gva-web-configmap.yaml
@@ -0,0 +1,32 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: my.conf
+data:
+ my.conf: |
+ server {
+ listen 8080;
+ server_name localhost;
+
+ #charset koi8-r;
+ #access_log logs/host.access.log main;
+
+ location / {
+ root /usr/share/nginx/html;
+ add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
+ try_files $uri $uri/ /index.html;
+ }
+
+ location /api {
+ proxy_set_header Host $http_host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ rewrite ^/api/(.*)$ /$1 break; #重写
+ proxy_pass http://gva-server:8888; # 设置代理服务器的协议和地址
+ }
+
+ location /api/swagger/index.html {
+ proxy_pass http://gva-server:8888/swagger/index.html;
+ }
+ }
\ No newline at end of file
diff --git a/deployment/web/gva-web-deploymemt.yaml b/deployment/web/gva-web-deploymemt.yaml
new file mode 100644
index 00000000..bb442477
--- /dev/null
+++ b/deployment/web/gva-web-deploymemt.yaml
@@ -0,0 +1,51 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: gva-web
+ annotations:
+ flipped-aurora/gin-vue-admin: ui
+ github: "https://github.com/flipped-aurora/gin-vue-admin.git"
+ app.kubernetes.io/version: 0.0.1
+ labels:
+ app: gva-web
+ version: gva-vue3
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: gva-web
+ version: gva-vue3
+ template:
+ metadata:
+ labels:
+ app: gva-web
+ version: gva-vue3
+ spec:
+ containers:
+ - name: gin-vue-admin-nginx-container
+ image: registry.cn-hangzhou.aliyuncs.com/gin-vue-admin/web:40fc3aa6
+ imagePullPolicy: IfNotPresent
+ ports:
+ - containerPort: 8080
+ name: http
+ readinessProbe:
+ tcpSocket:
+ port: 8080
+ initialDelaySeconds: 10
+ periodSeconds: 10
+ successThreshold: 1
+ failureThreshold: 3
+ resources:
+ limits:
+ cpu: 500m
+ memory: 1000Mi
+ requests:
+ cpu: 100m
+ memory: 100Mi
+ volumeMounts:
+ - mountPath: /etc/nginx/conf.d/
+ name: nginx-config
+ volumes:
+ - name: nginx-config
+ configMap:
+ name: my.conf
diff --git a/deployment/web/gva-web-service.yaml b/deployment/web/gva-web-service.yaml
new file mode 100644
index 00000000..39bdeab3
--- /dev/null
+++ b/deployment/web/gva-web-service.yaml
@@ -0,0 +1,21 @@
+apiVersion: v1
+kind: Service
+metadata:
+ name: gva-web
+ annotations:
+ flipped-aurora/gin-vue-admin: ui
+ github: "https://github.com/flipped-aurora/gin-vue-admin.git"
+ app.kubernetes.io/version: 0.0.1
+ labels:
+ app: gva-web
+ version: gva-vue3
+spec:
+ type: NodePort
+# type: ClusterIP
+ ports:
+ - name: http
+ port: 8080
+ targetPort: 8080
+ selector:
+ app: gva-web
+ version: gva-vue3
diff --git a/server/Dockerfile b/server/Dockerfile
index 0e03cd50..5c3b8861 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -1,4 +1,4 @@
-FROM golang:alpine
+FROM golang:alpine as builder
WORKDIR /go/src/github.com/flipped-aurora/gin-vue-admin/server
COPY . .
diff --git a/server/api/v1/autocode/autocodeExample.go b/server/api/v1/autocode/auto_code_example.go
similarity index 93%
rename from server/api/v1/autocode/autocodeExample.go
rename to server/api/v1/autocode/auto_code_example.go
index ff83240c..ae1457d0 100644
--- a/server/api/v1/autocode/autocodeExample.go
+++ b/server/api/v1/autocode/auto_code_example.go
@@ -28,7 +28,7 @@ func (autoCodeExampleApi *AutoCodeExampleApi) CreateAutoCodeExample(c *gin.Conte
var autoCodeExample autocode.AutoCodeExample
_ = c.ShouldBindJSON(&autoCodeExample)
if err := autoCodeExampleService.CreateAutoCodeExample(autoCodeExample); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -47,7 +47,7 @@ func (autoCodeExampleApi *AutoCodeExampleApi) DeleteAutoCodeExample(c *gin.Conte
var autoCodeExample autocode.AutoCodeExample
_ = c.ShouldBindJSON(&autoCodeExample)
if err := autoCodeExampleService.DeleteAutoCodeExample(autoCodeExample); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -66,7 +66,7 @@ func (autoCodeExampleApi *AutoCodeExampleApi) UpdateAutoCodeExample(c *gin.Conte
var autoCodeExample autocode.AutoCodeExample
_ = c.ShouldBindJSON(&autoCodeExample)
if err := autoCodeExampleService.UpdateAutoCodeExample(&autoCodeExample); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
@@ -89,7 +89,7 @@ func (autoCodeExampleApi *AutoCodeExampleApi) FindAutoCodeExample(c *gin.Context
return
}
if err, reAutoCodeExample := autoCodeExampleService.GetAutoCodeExample(autoCodeExample.ID); err != nil {
- global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"reAutoCodeExample": reAutoCodeExample}, "查询成功", c)
@@ -108,7 +108,7 @@ func (autoCodeExampleApi *AutoCodeExampleApi) GetAutoCodeExampleList(c *gin.Cont
var pageInfo autocodeReq.AutoCodeExampleSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := autoCodeExampleService.GetAutoCodeExampleInfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/enter.go b/server/api/v1/enter.go
index 4f92934e..919f6881 100644
--- a/server/api/v1/enter.go
+++ b/server/api/v1/enter.go
@@ -7,8 +7,8 @@ import (
)
type ApiGroup struct {
- ExampleApiGroup example.ApiGroup
SystemApiGroup system.ApiGroup
+ ExampleApiGroup example.ApiGroup
AutoCodeApiGroup autocode.ApiGroup
}
diff --git a/server/api/v1/example/enter.go b/server/api/v1/example/enter.go
index 9149e02e..efc344e1 100644
--- a/server/api/v1/example/enter.go
+++ b/server/api/v1/example/enter.go
@@ -3,11 +3,11 @@ package example
import "github.com/flipped-aurora/gin-vue-admin/server/service"
type ApiGroup struct {
- CustomerApi
ExcelApi
+ CustomerApi
FileUploadAndDownloadApi
}
-var fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService
-var customerService = service.ServiceGroupApp.ExampleServiceGroup.CustomerService
var excelService = service.ServiceGroupApp.ExampleServiceGroup.ExcelService
+var customerService = service.ServiceGroupApp.ExampleServiceGroup.CustomerService
+var fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService
diff --git a/server/api/v1/example/exa_breakpoint_continue.go b/server/api/v1/example/exa_breakpoint_continue.go
index cf20d55c..e10db174 100644
--- a/server/api/v1/example/exa_breakpoint_continue.go
+++ b/server/api/v1/example/exa_breakpoint_continue.go
@@ -30,13 +30,13 @@ func (u *FileUploadAndDownloadApi) BreakpointContinue(c *gin.Context) {
chunkTotal, _ := strconv.Atoi(c.Request.FormValue("chunkTotal"))
_, FileHeader, err := c.Request.FormFile("file")
if err != nil {
- global.GVA_LOG.Error("接收文件失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
response.FailWithMessage("接收文件失败", c)
return
}
f, err := FileHeader.Open()
if err != nil {
- global.GVA_LOG.Error("文件读取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("文件读取失败!", zap.Error(err))
response.FailWithMessage("文件读取失败", c)
return
}
@@ -48,25 +48,25 @@ func (u *FileUploadAndDownloadApi) BreakpointContinue(c *gin.Context) {
}(f)
cen, _ := ioutil.ReadAll(f)
if !utils.CheckMd5(cen, chunkMd5) {
- global.GVA_LOG.Error("检查md5失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("检查md5失败!", zap.Error(err))
response.FailWithMessage("检查md5失败", c)
return
}
err, file := fileUploadAndDownloadService.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
- global.GVA_LOG.Error("查找或创建记录失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查找或创建记录失败!", zap.Error(err))
response.FailWithMessage("查找或创建记录失败", c)
return
}
err, pathc := utils.BreakPointContinue(cen, fileName, chunkNumber, chunkTotal, fileMd5)
if err != nil {
- global.GVA_LOG.Error("断点续传失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("断点续传失败!", zap.Error(err))
response.FailWithMessage("断点续传失败", c)
return
}
if err = fileUploadAndDownloadService.CreateFileChunk(file.ID, pathc, chunkNumber); err != nil {
- global.GVA_LOG.Error("创建文件记录失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建文件记录失败!", zap.Error(err))
response.FailWithMessage("创建文件记录失败", c)
return
}
@@ -87,7 +87,7 @@ func (u *FileUploadAndDownloadApi) FindFile(c *gin.Context) {
chunkTotal, _ := strconv.Atoi(c.Query("chunkTotal"))
err, file := fileUploadAndDownloadService.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
- global.GVA_LOG.Error("查找失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查找失败!", zap.Error(err))
response.FailWithMessage("查找失败", c)
} else {
response.OkWithDetailed(exampleRes.FileResponse{File: file}, "查找成功", c)
@@ -107,7 +107,7 @@ func (b *FileUploadAndDownloadApi) BreakpointContinueFinish(c *gin.Context) {
fileName := c.Query("fileName")
err, filePath := utils.MakeFile(fileName, fileMd5)
if err != nil {
- global.GVA_LOG.Error("文件创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("文件创建失败!", zap.Error(err))
response.FailWithDetailed(exampleRes.FilePathResponse{FilePath: filePath}, "文件创建失败", c)
} else {
response.OkWithDetailed(exampleRes.FilePathResponse{FilePath: filePath}, "文件创建成功", c)
@@ -132,7 +132,7 @@ func (u *FileUploadAndDownloadApi) RemoveChunk(c *gin.Context) {
}
err = fileUploadAndDownloadService.DeleteFileChunk(fileMd5, fileName, filePath)
if err != nil {
- global.GVA_LOG.Error("缓存切片删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("缓存切片删除失败!", zap.Error(err))
response.FailWithDetailed(exampleRes.FilePathResponse{FilePath: filePath}, "缓存切片删除失败", c)
} else {
response.OkWithDetailed(exampleRes.FilePathResponse{FilePath: filePath}, "缓存切片删除成功", c)
diff --git a/server/api/v1/example/exa_customer.go b/server/api/v1/example/exa_customer.go
index 3939ebfb..5e22d65a 100644
--- a/server/api/v1/example/exa_customer.go
+++ b/server/api/v1/example/exa_customer.go
@@ -32,7 +32,7 @@ func (e *CustomerApi) CreateExaCustomer(c *gin.Context) {
customer.SysUserID = utils.GetUserID(c)
customer.SysUserAuthorityID = utils.GetUserAuthorityId(c)
if err := customerService.CreateExaCustomer(customer); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -55,7 +55,7 @@ func (e *CustomerApi) DeleteExaCustomer(c *gin.Context) {
return
}
if err := customerService.DeleteExaCustomer(customer); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -82,7 +82,7 @@ func (e *CustomerApi) UpdateExaCustomer(c *gin.Context) {
return
}
if err := customerService.UpdateExaCustomer(&customer); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
@@ -106,7 +106,7 @@ func (e *CustomerApi) GetExaCustomer(c *gin.Context) {
}
err, data := customerService.GetExaCustomer(customer.ID)
if err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(exampleRes.ExaCustomerResponse{Customer: data}, "获取成功", c)
@@ -130,7 +130,7 @@ func (e *CustomerApi) GetExaCustomerList(c *gin.Context) {
}
err, customerList, total := customerService.GetCustomerInfoList(utils.GetUserAuthorityId(c), pageInfo)
if err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败"+err.Error(), c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/example/exa_excel.go b/server/api/v1/example/exa_excel.go
index 12dc2b9e..263dec3c 100644
--- a/server/api/v1/example/exa_excel.go
+++ b/server/api/v1/example/exa_excel.go
@@ -31,7 +31,7 @@ func (e *ExcelApi) ExportExcel(c *gin.Context) {
filePath := global.GVA_CONFIG.Excel.Dir + excelInfo.FileName
err := excelService.ParseInfoList2Excel(excelInfo.InfoList, filePath)
if err != nil {
- global.GVA_LOG.Error("转换Excel失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("转换Excel失败!", zap.Error(err))
response.FailWithMessage("转换Excel失败", c)
return
}
@@ -50,7 +50,7 @@ func (e *ExcelApi) ExportExcel(c *gin.Context) {
func (e *ExcelApi) ImportExcel(c *gin.Context) {
_, header, err := c.Request.FormFile("file")
if err != nil {
- global.GVA_LOG.Error("接收文件失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
response.FailWithMessage("接收文件失败", c)
return
}
@@ -67,7 +67,7 @@ func (e *ExcelApi) ImportExcel(c *gin.Context) {
func (e *ExcelApi) LoadExcel(c *gin.Context) {
menus, err := excelService.ParseExcel2InfoList()
if err != nil {
- global.GVA_LOG.Error("加载数据失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("加载数据失败!", zap.Error(err))
response.FailWithMessage("加载数据失败", c)
return
}
@@ -92,7 +92,7 @@ func (e *ExcelApi) DownloadTemplate(c *gin.Context) {
filePath := global.GVA_CONFIG.Excel.Dir + fileName
ok, err := utils.PathExists(filePath)
if !ok || err != nil {
- global.GVA_LOG.Error("文件不存在!", zap.Any("err", err))
+ global.GVA_LOG.Error("文件不存在!", zap.Error(err))
response.FailWithMessage("文件不存在", c)
return
}
diff --git a/server/api/v1/example/exa_file_upload_download.go b/server/api/v1/example/exa_file_upload_download.go
index 5fdf6dc5..658fd7eb 100644
--- a/server/api/v1/example/exa_file_upload_download.go
+++ b/server/api/v1/example/exa_file_upload_download.go
@@ -26,13 +26,13 @@ func (u *FileUploadAndDownloadApi) UploadFile(c *gin.Context) {
noSave := c.DefaultQuery("noSave", "0")
_, header, err := c.Request.FormFile("file")
if err != nil {
- global.GVA_LOG.Error("接收文件失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
response.FailWithMessage("接收文件失败", c)
return
}
err, file = fileUploadAndDownloadService.UploadFile(header, noSave) // 文件上传后拿到文件路径
if err != nil {
- global.GVA_LOG.Error("修改数据库链接失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("修改数据库链接失败!", zap.Error(err))
response.FailWithMessage("修改数据库链接失败", c)
return
}
@@ -50,7 +50,7 @@ func (u *FileUploadAndDownloadApi) DeleteFile(c *gin.Context) {
var file example.ExaFileUploadAndDownload
_ = c.ShouldBindJSON(&file)
if err := fileUploadAndDownloadService.DeleteFile(file); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
return
}
@@ -70,7 +70,7 @@ func (u *FileUploadAndDownloadApi) GetFileList(c *gin.Context) {
_ = c.ShouldBindJSON(&pageInfo)
err, list, total := fileUploadAndDownloadService.GetFileRecordInfoList(pageInfo)
if err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/system/enter.go b/server/api/v1/system/enter.go
index 995522c3..8796ac06 100644
--- a/server/api/v1/system/enter.go
+++ b/server/api/v1/system/enter.go
@@ -3,31 +3,32 @@ package system
import "github.com/flipped-aurora/gin-vue-admin/server/service"
type ApiGroup struct {
- SystemApiApi
- AuthorityApi
- AutoCodeApi
- BaseApi
- CasbinApi
- DictionaryApi
- DictionaryDetailApi
- SystemApi
DBApi
JwtApi
- OperationRecordApi
+ BaseApi
+ SystemApi
+ CasbinApi
+ AutoCodeApi
+ SystemApiApi
+ AuthorityApi
+ DictionaryApi
AuthorityMenuApi
+ OperationRecordApi
+ AutoCodeHistoryApi
+ DictionaryDetailApi
}
-var authorityService = service.ServiceGroupApp.SystemServiceGroup.AuthorityService
var apiService = service.ServiceGroupApp.SystemServiceGroup.ApiService
+var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
var menuService = service.ServiceGroupApp.SystemServiceGroup.MenuService
+var userService = service.ServiceGroupApp.SystemServiceGroup.UserService
+var initDBService = service.ServiceGroupApp.SystemServiceGroup.InitDBService
var casbinService = service.ServiceGroupApp.SystemServiceGroup.CasbinService
var autoCodeService = service.ServiceGroupApp.SystemServiceGroup.AutoCodeService
-var autoCodeHistoryService = service.ServiceGroupApp.SystemServiceGroup.AutoCodeHistoryService
-var dictionaryService = service.ServiceGroupApp.SystemServiceGroup.DictionaryService
-var dictionaryDetailService = service.ServiceGroupApp.SystemServiceGroup.DictionaryDetailService
-var initDBService = service.ServiceGroupApp.SystemServiceGroup.InitDBService
-var jwtService = service.ServiceGroupApp.SystemServiceGroup.JwtService
var baseMenuService = service.ServiceGroupApp.SystemServiceGroup.BaseMenuService
-var operationRecordService = service.ServiceGroupApp.SystemServiceGroup.OperationRecordService
-var userService = service.ServiceGroupApp.SystemServiceGroup.UserService
+var authorityService = service.ServiceGroupApp.SystemServiceGroup.AuthorityService
+var dictionaryService = service.ServiceGroupApp.SystemServiceGroup.DictionaryService
var systemConfigService = service.ServiceGroupApp.SystemServiceGroup.SystemConfigService
+var operationRecordService = service.ServiceGroupApp.SystemServiceGroup.OperationRecordService
+var autoCodeHistoryService = service.ServiceGroupApp.SystemServiceGroup.AutoCodeHistoryService
+var dictionaryDetailService = service.ServiceGroupApp.SystemServiceGroup.DictionaryDetailService
diff --git a/server/api/v1/system/sys_api.go b/server/api/v1/system/sys_api.go
index ba7fb8a3..8f2e4dbe 100644
--- a/server/api/v1/system/sys_api.go
+++ b/server/api/v1/system/sys_api.go
@@ -32,7 +32,7 @@ func (s *SystemApiApi) CreateApi(c *gin.Context) {
return
}
if err := apiService.CreateApi(api); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -55,7 +55,7 @@ func (s *SystemApiApi) DeleteApi(c *gin.Context) {
return
}
if err := apiService.DeleteApi(api); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -78,7 +78,7 @@ func (s *SystemApiApi) GetApiList(c *gin.Context) {
return
}
if err, list, total := apiService.GetAPIInfoList(pageInfo.SysApi, pageInfo.PageInfo, pageInfo.OrderKey, pageInfo.Desc); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
@@ -107,7 +107,7 @@ func (s *SystemApiApi) GetApiById(c *gin.Context) {
}
err, api := apiService.GetApiById(idInfo.ID)
if err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithData(systemRes.SysAPIResponse{Api: api}, c)
@@ -130,7 +130,7 @@ func (s *SystemApiApi) UpdateApi(c *gin.Context) {
return
}
if err := apiService.UpdateApi(api); err != nil {
- global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage("修改失败", c)
} else {
response.OkWithMessage("修改成功", c)
@@ -146,7 +146,7 @@ func (s *SystemApiApi) UpdateApi(c *gin.Context) {
// @Router /api/getAllApis [post]
func (s *SystemApiApi) GetAllApis(c *gin.Context) {
if err, apis := apiService.GetAllApis(); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(systemRes.SysAPIListResponse{Apis: apis}, "获取成功", c)
@@ -165,7 +165,7 @@ func (s *SystemApiApi) DeleteApisByIds(c *gin.Context) {
var ids request.IdsReq
_ = c.ShouldBindJSON(&ids)
if err := apiService.DeleteApisByIds(ids); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
diff --git a/server/api/v1/system/sys_authority.go b/server/api/v1/system/sys_authority.go
index 5cb6d96a..a1a25d8e 100644
--- a/server/api/v1/system/sys_authority.go
+++ b/server/api/v1/system/sys_authority.go
@@ -32,7 +32,7 @@ func (a *AuthorityApi) CreateAuthority(c *gin.Context) {
return
}
if err, authBack := authorityService.CreateAuthority(authority); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败"+err.Error(), c)
} else {
_ = menuService.AddMenuAuthority(systemReq.DefaultMenu(), authority.AuthorityId)
@@ -61,7 +61,7 @@ func (a *AuthorityApi) CopyAuthority(c *gin.Context) {
return
}
if err, authBack := authorityService.CopyAuthority(copyInfo); err != nil {
- global.GVA_LOG.Error("拷贝失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("拷贝失败!", zap.Error(err))
response.FailWithMessage("拷贝失败"+err.Error(), c)
} else {
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authBack}, "拷贝成功", c)
@@ -84,7 +84,7 @@ func (a *AuthorityApi) DeleteAuthority(c *gin.Context) {
return
}
if err := authorityService.DeleteAuthority(&authority); err != nil { // 删除角色之前需要判断是否有用户正在使用此角色
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败"+err.Error(), c)
} else {
response.OkWithMessage("删除成功", c)
@@ -107,7 +107,7 @@ func (a *AuthorityApi) UpdateAuthority(c *gin.Context) {
return
}
if err, authority := authorityService.UpdateAuthority(auth); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败"+err.Error(), c)
} else {
response.OkWithDetailed(systemRes.SysAuthorityResponse{Authority: authority}, "更新成功", c)
@@ -130,7 +130,7 @@ func (a *AuthorityApi) GetAuthorityList(c *gin.Context) {
return
}
if err, list, total := authorityService.GetAuthorityInfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败"+err.Error(), c)
} else {
response.OkWithDetailed(response.PageResult{
@@ -158,7 +158,7 @@ func (a *AuthorityApi) SetDataAuthority(c *gin.Context) {
return
}
if err := authorityService.SetDataAuthority(auth); err != nil {
- global.GVA_LOG.Error("设置失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败"+err.Error(), c)
} else {
response.OkWithMessage("设置成功", c)
diff --git a/server/api/v1/system/sys_auto_code.go b/server/api/v1/system/sys_auto_code.go
index e8b7b049..7b24e926 100644
--- a/server/api/v1/system/sys_auto_code.go
+++ b/server/api/v1/system/sys_auto_code.go
@@ -9,99 +9,15 @@ 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"
- systemReq "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"
)
-type AutoCodeApi struct {
-}
-
-// @Tags AutoCode
-// @Summary 删除回滚记录
-// @Security ApiKeyAuth
-// @accept application/json
-// @Produce application/json
-// @Param data body systemReq.AutoHistoryByID true "删除回滚记录"
-// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
-// @Router /autoCode/delSysHistory [post]
-func (autoApi *AutoCodeApi) DelSysHistory(c *gin.Context) {
- var id systemReq.AutoHistoryByID
- _ = c.ShouldBindJSON(&id)
- err := autoCodeHistoryService.DeletePage(id.ID)
- if err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
- response.FailWithMessage("获取失败", c)
- }
- response.OkWithMessage("删除成功", c)
-
-}
-
-// @Tags AutoCode
-// @Summary 查询回滚记录
-// @Security ApiKeyAuth
-// @accept application/json
-// @Produce application/json
-// @Param data body systemReq.SysAutoHistory true "查询回滚记录"
-// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
-// @Router /autoCode/getSysHistory [post]
-func (autoApi *AutoCodeApi) GetSysHistory(c *gin.Context) {
- var search systemReq.SysAutoHistory
- _ = c.ShouldBindJSON(&search)
- err, list, total := autoCodeHistoryService.GetSysHistoryPage(search.PageInfo)
- if err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
- response.FailWithMessage("获取失败", c)
- } else {
- response.OkWithDetailed(response.PageResult{
- List: list,
- Total: total,
- Page: search.Page,
- PageSize: search.PageSize,
- }, "获取成功", c)
- }
-}
-
-// @Tags AutoCode
-// @Summary 回滚
-// @Security ApiKeyAuth
-// @accept application/json
-// @Produce application/json
-// @Param data body systemReq.AutoHistoryByID true "回滚自动生成代码"
-// @Success 200 {string} string "{"success":true,"data":{},"msg":"回滚成功"}"
-// @Router /autoCode/rollback [post]
-func (autoApi *AutoCodeApi) RollBack(c *gin.Context) {
- var id systemReq.AutoHistoryByID
- _ = c.ShouldBindJSON(&id)
- if err := autoCodeHistoryService.RollBack(id.ID); err != nil {
- response.FailWithMessage(err.Error(), c)
- return
- }
- response.OkWithMessage("回滚成功", c)
-}
-
-// @Tags AutoCode
-// @Summary 回滚
-// @Security ApiKeyAuth
-// @accept application/json
-// @Produce application/json
-// @Param data body systemReq.AutoHistoryByID true "获取meta信息"
-// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
-// @Router /autoCode/getMeta [post]
-func (autoApi *AutoCodeApi) GetMeta(c *gin.Context) {
- var id systemReq.AutoHistoryByID
- _ = c.ShouldBindJSON(&id)
- if v, err := autoCodeHistoryService.GetMeta(id.ID); err != nil {
- response.FailWithMessage(err.Error(), c)
- return
- } else {
- response.OkWithDetailed(gin.H{"meta": v}, "获取成功", c)
- }
-
-}
+type AutoCodeApi struct{}
+// PreviewTemp
// @Tags AutoCode
// @Summary 预览创建后的代码
// @Security ApiKeyAuth
@@ -119,13 +35,14 @@ func (autoApi *AutoCodeApi) PreviewTemp(c *gin.Context) {
}
autoCode, err := autoCodeService.PreviewTemp(a)
if err != nil {
- global.GVA_LOG.Error("预览失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("预览失败!", zap.Error(err))
response.FailWithMessage("预览失败", c)
} else {
response.OkWithDetailed(gin.H{"autoCode": autoCode}, "预览成功", c)
}
}
+// CreateTemp
// @Tags AutoCode
// @Summary 自动代码模板
// @Security ApiKeyAuth
@@ -144,7 +61,7 @@ func (autoApi *AutoCodeApi) CreateTemp(c *gin.Context) {
var apiIds []uint
if a.AutoCreateApiToSql {
if ids, err := autoCodeService.AutoCreateApi(&a); err != nil {
- global.GVA_LOG.Error("自动化创建失败!请自行清空垃圾数据!", zap.Any("err", err))
+ global.GVA_LOG.Error("自动化创建失败!请自行清空垃圾数据!", zap.Error(err))
c.Writer.Header().Add("success", "false")
c.Writer.Header().Add("msg", url.QueryEscape("自动化创建失败!请自行清空垃圾数据!"))
return
@@ -171,6 +88,24 @@ func (autoApi *AutoCodeApi) CreateTemp(c *gin.Context) {
}
}
+// GetDB
+// @Tags AutoCode
+// @Summary 获取当前所有数据库
+// @Security ApiKeyAuth
+// @accept application/json
+// @Produce application/json
+// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
+// @Router /autoCode/getDatabase [get]
+func (autoApi *AutoCodeApi) GetDB(c *gin.Context) {
+ dbs, err := autoCodeService.Database().GetDB()
+ if err != nil {
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
+ response.FailWithMessage("获取失败", c)
+ }
+ response.OkWithDetailed(gin.H{"dbs": dbs}, "获取成功", c)
+}
+
+// GetTables
// @Tags AutoCode
// @Summary 获取当前数据库所有表
// @Security ApiKeyAuth
@@ -180,31 +115,16 @@ func (autoApi *AutoCodeApi) CreateTemp(c *gin.Context) {
// @Router /autoCode/getTables [get]
func (autoApi *AutoCodeApi) GetTables(c *gin.Context) {
dbName := c.DefaultQuery("dbName", global.GVA_CONFIG.Mysql.Dbname)
- err, tables := autoCodeService.GetTables(dbName)
+ tables, err := autoCodeService.Database().GetTables(dbName)
if err != nil {
- global.GVA_LOG.Error("查询table失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查询table失败!", zap.Error(err))
response.FailWithMessage("查询table失败", c)
} else {
response.OkWithDetailed(gin.H{"tables": tables}, "获取成功", c)
}
}
-// @Tags AutoCode
-// @Summary 获取当前所有数据库
-// @Security ApiKeyAuth
-// @accept application/json
-// @Produce application/json
-// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
-// @Router /autoCode/getDatabase [get]
-func (autoApi *AutoCodeApi) GetDB(c *gin.Context) {
- if err, dbs := autoCodeService.GetDB(); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
- response.FailWithMessage("获取失败", c)
- } else {
- response.OkWithDetailed(gin.H{"dbs": dbs}, "获取成功", c)
- }
-}
-
+// GetColumn
// @Tags AutoCode
// @Summary 获取当前表所有字段
// @Security ApiKeyAuth
@@ -215,10 +135,10 @@ func (autoApi *AutoCodeApi) GetDB(c *gin.Context) {
func (autoApi *AutoCodeApi) GetColumn(c *gin.Context) {
dbName := c.DefaultQuery("dbName", global.GVA_CONFIG.Mysql.Dbname)
tableName := c.Query("tableName")
- if err, columns := autoCodeService.GetColumn(tableName, dbName); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ columns, err := autoCodeService.Database().GetColumn(tableName, dbName)
+ if err != nil {
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
- } else {
- response.OkWithDetailed(gin.H{"columns": columns}, "获取成功", c)
}
+ response.OkWithDetailed(gin.H{"columns": columns}, "获取成功", c)
}
diff --git a/server/api/v1/system/sys_auto_code_history.go b/server/api/v1/system/sys_auto_code_history.go
new file mode 100644
index 00000000..7254b96b
--- /dev/null
+++ b/server/api/v1/system/sys_auto_code_history.go
@@ -0,0 +1,98 @@
+package system
+
+import (
+ "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"
+ systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
+ "github.com/gin-gonic/gin"
+ "go.uber.org/zap"
+)
+
+type AutoCodeHistoryApi struct{}
+
+// First
+// @Tags AutoCode
+// @Summary 获取meta信息
+// @Security ApiKeyAuth
+// @accept application/json
+// @Produce application/json
+// @Param data body request.GetById true "请求参数"
+// @Success 200 {object} response.Response{} "获取成功!"
+// @Router /autoCode/getMeta [post]
+func (a *AutoCodeHistoryApi) First(c *gin.Context) {
+ var info request.GetById
+ _ = c.ShouldBindJSON(&info)
+ data, err := autoCodeHistoryService.First(&info)
+ if err != nil {
+ response.FailWithMessage(err.Error(), c)
+ return
+ }
+ response.OkWithDetailed(gin.H{"meta": data}, "获取成功", c)
+}
+
+// Delete
+// @Tags AutoCode
+// @Summary 删除回滚记录
+// @Security ApiKeyAuth
+// @accept application/json
+// @Produce application/json
+// @Param data body request.GetById true "请求参数"
+// @Success 200 {object} response.Response{} "删除成功!"
+// @Router /autoCode/delSysHistory [post]
+func (a *AutoCodeHistoryApi) Delete(c *gin.Context) {
+ var info request.GetById
+ _ = c.ShouldBindJSON(&info)
+ err := autoCodeHistoryService.Delete(&info)
+ if err != nil {
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
+ response.FailWithMessage("删除失败", c)
+ return
+ }
+ response.OkWithMessage("删除成功", c)
+}
+
+// RollBack
+// @Tags AutoCode
+// @Summary 回滚自动生成代码
+// @Security ApiKeyAuth
+// @accept application/json
+// @Produce application/json
+// @Param data body request.GetById true "请求参数"
+// @Success 200 {object} response.Response{} "回滚成功!"
+// @Router /autoCode/rollback [post]
+func (a *AutoCodeHistoryApi) RollBack(c *gin.Context) {
+ var info request.GetById
+ _ = c.ShouldBindJSON(&info)
+ if err := autoCodeHistoryService.RollBack(&info); err != nil {
+ response.FailWithMessage(err.Error(), c)
+ return
+ }
+ response.OkWithMessage("回滚成功", c)
+}
+
+// GetList
+// @Tags AutoCode
+// @Summary 查询回滚记录
+// @Security ApiKeyAuth
+// @accept application/json
+// @Produce application/json
+// @Param data body systemReq.SysAutoHistory true "请求参数"
+// @Success 200 {object} response.Response{} "获取成功!"
+// @Router /autoCode/getSysHistory [post]
+func (a *AutoCodeHistoryApi) GetList(c *gin.Context) {
+ var search systemReq.SysAutoHistory
+ _ = c.ShouldBindJSON(&search)
+ list, total, err := autoCodeHistoryService.GetList(search.PageInfo)
+ if err != nil {
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
+ response.FailWithMessage("获取失败", c)
+ return
+ }
+ response.OkWithDetailed(response.PageResult{
+ List: list,
+ Total: total,
+ Page: search.Page,
+ PageSize: search.PageSize,
+ }, "获取成功", c)
+}
diff --git a/server/api/v1/system/sys_captcha.go b/server/api/v1/system/sys_captcha.go
index f07587d5..8a69ac51 100644
--- a/server/api/v1/system/sys_captcha.go
+++ b/server/api/v1/system/sys_captcha.go
@@ -30,12 +30,13 @@ func (b *BaseApi) Captcha(c *gin.Context) {
//cp := base64Captcha.NewCaptcha(driver, store.UseWithCtx(c)) // v8下使用redis
cp := base64Captcha.NewCaptcha(driver, store)
if id, b64s, err := cp.Generate(); err != nil {
- global.GVA_LOG.Error("验证码获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("验证码获取失败!", zap.Error(err))
response.FailWithMessage("验证码获取失败", c)
} else {
response.OkWithDetailed(systemRes.SysCaptchaResponse{
- CaptchaId: id,
- PicPath: b64s,
+ CaptchaId: id,
+ PicPath: b64s,
+ CaptchaLength: global.GVA_CONFIG.Captcha.KeyLong,
}, "验证码获取成功", c)
}
}
diff --git a/server/api/v1/system/sys_casbin.go b/server/api/v1/system/sys_casbin.go
index ce2f1bcb..fab202d5 100644
--- a/server/api/v1/system/sys_casbin.go
+++ b/server/api/v1/system/sys_casbin.go
@@ -29,7 +29,7 @@ func (cas *CasbinApi) UpdateCasbin(c *gin.Context) {
return
}
if err := casbinService.UpdateCasbin(cmr.AuthorityId, cmr.CasbinInfos); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
diff --git a/server/api/v1/system/sys_dictionary.go b/server/api/v1/system/sys_dictionary.go
index 4b7b3944..e71d711e 100644
--- a/server/api/v1/system/sys_dictionary.go
+++ b/server/api/v1/system/sys_dictionary.go
@@ -25,7 +25,7 @@ func (s *DictionaryApi) CreateSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
_ = c.ShouldBindJSON(&dictionary)
if err := dictionaryService.CreateSysDictionary(dictionary); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -44,7 +44,7 @@ func (s *DictionaryApi) DeleteSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
_ = c.ShouldBindJSON(&dictionary)
if err := dictionaryService.DeleteSysDictionary(dictionary); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -63,7 +63,7 @@ func (s *DictionaryApi) UpdateSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
_ = c.ShouldBindJSON(&dictionary)
if err := dictionaryService.UpdateSysDictionary(&dictionary); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
@@ -82,7 +82,7 @@ func (s *DictionaryApi) FindSysDictionary(c *gin.Context) {
var dictionary system.SysDictionary
_ = c.ShouldBindQuery(&dictionary)
if err, sysDictionary := dictionaryService.GetSysDictionary(dictionary.Type, dictionary.ID); err != nil {
- global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"resysDictionary": sysDictionary}, "查询成功", c)
@@ -105,7 +105,7 @@ func (s *DictionaryApi) GetSysDictionaryList(c *gin.Context) {
return
}
if err, list, total := dictionaryService.GetSysDictionaryInfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/system/sys_dictionary_detail.go b/server/api/v1/system/sys_dictionary_detail.go
index 49844624..8b5c6ede 100644
--- a/server/api/v1/system/sys_dictionary_detail.go
+++ b/server/api/v1/system/sys_dictionary_detail.go
@@ -25,7 +25,7 @@ func (s *DictionaryDetailApi) CreateSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
_ = c.ShouldBindJSON(&detail)
if err := dictionaryDetailService.CreateSysDictionaryDetail(detail); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -44,7 +44,7 @@ func (s *DictionaryDetailApi) DeleteSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
_ = c.ShouldBindJSON(&detail)
if err := dictionaryDetailService.DeleteSysDictionaryDetail(detail); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -63,7 +63,7 @@ func (s *DictionaryDetailApi) UpdateSysDictionaryDetail(c *gin.Context) {
var detail system.SysDictionaryDetail
_ = c.ShouldBindJSON(&detail)
if err := dictionaryDetailService.UpdateSysDictionaryDetail(&detail); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
@@ -86,7 +86,7 @@ func (s *DictionaryDetailApi) FindSysDictionaryDetail(c *gin.Context) {
return
}
if err, resysDictionaryDetail := dictionaryDetailService.GetSysDictionaryDetail(detail.ID); err != nil {
- global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"resysDictionaryDetail": resysDictionaryDetail}, "查询成功", c)
@@ -105,7 +105,7 @@ func (s *DictionaryDetailApi) GetSysDictionaryDetailList(c *gin.Context) {
var pageInfo request.SysDictionaryDetailSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := dictionaryDetailService.GetSysDictionaryDetailInfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/system/sys_initdb.go b/server/api/v1/system/sys_initdb.go
index 0d062a99..70645aa1 100644
--- a/server/api/v1/system/sys_initdb.go
+++ b/server/api/v1/system/sys_initdb.go
@@ -9,9 +9,9 @@ import (
"github.com/gin-gonic/gin"
)
-type DBApi struct {
-}
+type DBApi struct{}
+// InitDB
// @Tags InitDB
// @Summary 初始化用户数据库
// @Produce application/json
@@ -26,18 +26,19 @@ func (i *DBApi) InitDB(c *gin.Context) {
}
var dbInfo request.InitDB
if err := c.ShouldBindJSON(&dbInfo); err != nil {
- global.GVA_LOG.Error("参数校验不通过!", zap.Any("err", err))
+ global.GVA_LOG.Error("参数校验不通过!", zap.Error(err))
response.FailWithMessage("参数校验不通过", c)
return
}
if err := initDBService.InitDB(dbInfo); err != nil {
- global.GVA_LOG.Error("自动创建数据库失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("自动创建数据库失败!", zap.Error(err))
response.FailWithMessage("自动创建数据库失败,请查看后台日志,检查后在进行初始化", c)
return
}
response.OkWithData("自动创建数据库成功", c)
}
+// CheckDB
// @Tags CheckDB
// @Summary 初始化用户数据库
// @Produce application/json
diff --git a/server/api/v1/system/sys_jwt_blacklist.go b/server/api/v1/system/sys_jwt_blacklist.go
index a3ecb2dc..981167c7 100644
--- a/server/api/v1/system/sys_jwt_blacklist.go
+++ b/server/api/v1/system/sys_jwt_blacklist.go
@@ -22,7 +22,7 @@ func (j *JwtApi) JsonInBlacklist(c *gin.Context) {
token := c.Request.Header.Get("x-token")
jwt := system.JwtBlacklist{Jwt: token}
if err := jwtService.JsonInBlacklist(jwt); err != nil {
- global.GVA_LOG.Error("jwt作废失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("jwt作废失败!", zap.Error(err))
response.FailWithMessage("jwt作废失败", c)
} else {
response.OkWithMessage("jwt作废成功", c)
diff --git a/server/api/v1/system/sys_menu.go b/server/api/v1/system/sys_menu.go
index d0139366..a7477763 100644
--- a/server/api/v1/system/sys_menu.go
+++ b/server/api/v1/system/sys_menu.go
@@ -25,7 +25,7 @@ type AuthorityMenuApi struct {
// @Router /menu/getMenu [post]
func (a *AuthorityMenuApi) GetMenu(c *gin.Context) {
if err, menus := menuService.GetMenuTree(utils.GetUserAuthorityId(c)); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
if menus == nil {
@@ -44,7 +44,7 @@ func (a *AuthorityMenuApi) GetMenu(c *gin.Context) {
// @Router /menu/getBaseMenuTree [post]
func (a *AuthorityMenuApi) GetBaseMenuTree(c *gin.Context) {
if err, menus := menuService.GetBaseMenuTree(); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(systemRes.SysBaseMenusResponse{Menus: menus}, "获取成功", c)
@@ -67,7 +67,7 @@ func (a *AuthorityMenuApi) AddMenuAuthority(c *gin.Context) {
return
}
if err := menuService.AddMenuAuthority(authorityMenu.Menus, authorityMenu.AuthorityId); err != nil {
- global.GVA_LOG.Error("添加失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("添加失败!", zap.Error(err))
response.FailWithMessage("添加失败", c)
} else {
response.OkWithMessage("添加成功", c)
@@ -90,7 +90,7 @@ func (a *AuthorityMenuApi) GetMenuAuthority(c *gin.Context) {
return
}
if err, menus := menuService.GetMenuAuthority(¶m); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithDetailed(systemRes.SysMenusResponse{Menus: menus}, "获取失败", c)
} else {
response.OkWithDetailed(gin.H{"menus": menus}, "获取成功", c)
@@ -117,7 +117,7 @@ func (a *AuthorityMenuApi) AddBaseMenu(c *gin.Context) {
return
}
if err := menuService.AddBaseMenu(menu); err != nil {
- global.GVA_LOG.Error("添加失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("添加失败!", zap.Error(err))
response.FailWithMessage("添加失败", c)
} else {
@@ -141,7 +141,7 @@ func (a *AuthorityMenuApi) DeleteBaseMenu(c *gin.Context) {
return
}
if err := baseMenuService.DeleteBaseMenu(menu.ID); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -168,7 +168,7 @@ func (a *AuthorityMenuApi) UpdateBaseMenu(c *gin.Context) {
return
}
if err := baseMenuService.UpdateBaseMenu(menu); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
@@ -191,7 +191,7 @@ func (a *AuthorityMenuApi) GetBaseMenuById(c *gin.Context) {
return
}
if err, menu := baseMenuService.GetBaseMenuById(idInfo.ID); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(systemRes.SysBaseMenuResponse{Menu: menu}, "获取成功", c)
@@ -214,7 +214,7 @@ func (a *AuthorityMenuApi) GetMenuList(c *gin.Context) {
return
}
if err, menuList, total := menuService.GetInfoList(); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/system/sys_operation_record.go b/server/api/v1/system/sys_operation_record.go
index 8bf165a6..33d193c4 100644
--- a/server/api/v1/system/sys_operation_record.go
+++ b/server/api/v1/system/sys_operation_record.go
@@ -26,7 +26,7 @@ func (s *OperationRecordApi) CreateSysOperationRecord(c *gin.Context) {
var sysOperationRecord system.SysOperationRecord
_ = c.ShouldBindJSON(&sysOperationRecord)
if err := operationRecordService.CreateSysOperationRecord(sysOperationRecord); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -45,7 +45,7 @@ func (s *OperationRecordApi) DeleteSysOperationRecord(c *gin.Context) {
var sysOperationRecord system.SysOperationRecord
_ = c.ShouldBindJSON(&sysOperationRecord)
if err := operationRecordService.DeleteSysOperationRecord(sysOperationRecord); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -64,7 +64,7 @@ func (s *OperationRecordApi) DeleteSysOperationRecordByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := operationRecordService.DeleteSysOperationRecordByIds(IDS); err != nil {
- global.GVA_LOG.Error("批量删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
@@ -87,7 +87,7 @@ func (s *OperationRecordApi) FindSysOperationRecord(c *gin.Context) {
return
}
if err, resysOperationRecord := operationRecordService.GetSysOperationRecord(sysOperationRecord.ID); err != nil {
- global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"resysOperationRecord": resysOperationRecord}, "查询成功", c)
@@ -106,7 +106,7 @@ func (s *OperationRecordApi) GetSysOperationRecordList(c *gin.Context) {
var pageInfo systemReq.SysOperationRecordSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := operationRecordService.GetSysOperationRecordInfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/api/v1/system/sys_system.go b/server/api/v1/system/sys_system.go
index c344bac5..bdc10119 100644
--- a/server/api/v1/system/sys_system.go
+++ b/server/api/v1/system/sys_system.go
@@ -22,7 +22,7 @@ type SystemApi struct {
// @Router /system/getSystemConfig [post]
func (s *SystemApi) GetSystemConfig(c *gin.Context) {
if err, config := systemConfigService.GetSystemConfig(); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(systemRes.SysConfigResponse{Config: config}, "获取成功", c)
@@ -40,7 +40,7 @@ func (s *SystemApi) SetSystemConfig(c *gin.Context) {
var sys system.System
_ = c.ShouldBindJSON(&sys)
if err := systemConfigService.SetSystemConfig(sys); err != nil {
- global.GVA_LOG.Error("设置失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败", c)
} else {
response.OkWithData("设置成功", c)
@@ -56,7 +56,7 @@ func (s *SystemApi) SetSystemConfig(c *gin.Context) {
func (s *SystemApi) ReloadSystem(c *gin.Context) {
err := utils.Reload()
if err != nil {
- global.GVA_LOG.Error("重启系统失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("重启系统失败!", zap.Error(err))
response.FailWithMessage("重启系统失败", c)
} else {
response.OkWithMessage("重启系统成功", c)
@@ -71,7 +71,7 @@ func (s *SystemApi) ReloadSystem(c *gin.Context) {
// @Router /system/getServerInfo [post]
func (s *SystemApi) GetServerInfo(c *gin.Context) {
if server, err := systemConfigService.GetServerInfo(); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"server": server}, "获取成功", c)
diff --git a/server/api/v1/system/sys_user.go b/server/api/v1/system/sys_user.go
index 8a59407a..6a3bde67 100644
--- a/server/api/v1/system/sys_user.go
+++ b/server/api/v1/system/sys_user.go
@@ -1,9 +1,6 @@
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"
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
@@ -11,8 +8,8 @@ import (
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"
+ "strconv"
- "github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"go.uber.org/zap"
@@ -34,7 +31,7 @@ func (b *BaseApi) Login(c *gin.Context) {
if store.Verify(l.CaptchaId, l.Captcha, true) {
u := &system.SysUser{Username: l.Username, Password: l.Password}
if err, user := userService.Login(u); err != nil {
- global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Any("err", err))
+ global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
response.FailWithMessage("用户名不存在或者密码错误", c)
} else {
b.tokenNext(c, *user)
@@ -47,22 +44,16 @@ func (b *BaseApi) Login(c *gin.Context) {
// 登录以后签发jwt
func (b *BaseApi) tokenNext(c *gin.Context, user system.SysUser) {
j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
- claims := systemReq.CustomClaims{
+ claims := j.CreateClaims(systemReq.BaseClaims{
UUID: user.UUID,
ID: user.ID,
NickName: user.NickName,
Username: user.Username,
AuthorityId: user.AuthorityId,
- BufferTime: global.GVA_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
- StandardClaims: jwt.StandardClaims{
- NotBefore: time.Now().Unix() - 1000, // 签名生效时间
- ExpiresAt: time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime, // 过期时间 7天 配置文件
- Issuer: "qmPlus", // 签名的发行者
- },
- }
+ })
token, err := j.CreateToken(claims)
if err != nil {
- global.GVA_LOG.Error("获取token失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取token失败!", zap.Error(err))
response.FailWithMessage("获取token失败", c)
return
}
@@ -77,7 +68,7 @@ func (b *BaseApi) tokenNext(c *gin.Context, user system.SysUser) {
if err, jwtStr := jwtService.GetRedisJWT(user.Username); err == redis.Nil {
if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
- global.GVA_LOG.Error("设置登录状态失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
response.FailWithMessage("设置登录状态失败", c)
return
}
@@ -87,7 +78,7 @@ func (b *BaseApi) tokenNext(c *gin.Context, user system.SysUser) {
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
}, "登录成功", c)
} else if err != nil {
- global.GVA_LOG.Error("设置登录状态失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
response.FailWithMessage("设置登录状态失败", c)
} else {
var blackJWT system.JwtBlacklist
@@ -130,7 +121,7 @@ func (b *BaseApi) Register(c *gin.Context) {
user := &system.SysUser{Username: r.Username, NickName: r.NickName, Password: r.Password, HeaderImg: r.HeaderImg, AuthorityId: r.AuthorityId, Authorities: authorities}
err, userReturn := userService.Register(*user)
if err != nil {
- global.GVA_LOG.Error("注册失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("注册失败!", zap.Error(err))
response.FailWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册失败", c)
} else {
response.OkWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册成功", c)
@@ -153,7 +144,7 @@ func (b *BaseApi) ChangePassword(c *gin.Context) {
}
u := &system.SysUser{Username: user.Username, Password: user.Password}
if err, _ := userService.ChangePassword(u, user.NewPassword); err != nil {
- global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage("修改失败,原密码与当前账户不符", c)
} else {
response.OkWithMessage("修改成功", c)
@@ -176,7 +167,7 @@ func (b *BaseApi) GetUserList(c *gin.Context) {
return
}
if err, list, total := userService.GetUserInfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
@@ -206,14 +197,14 @@ func (b *BaseApi) SetUserAuthority(c *gin.Context) {
userID := utils.GetUserID(c)
uuid := utils.GetUserUuid(c)
if err := userService.SetUserAuthority(userID, uuid, sua.AuthorityId); err != nil {
- global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage(err.Error(), c)
} else {
claims := utils.GetUserInfo(c)
j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
claims.AuthorityId = sua.AuthorityId
if token, err := j.CreateToken(*claims); err != nil {
- global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage(err.Error(), c)
} else {
c.Header("new-token", token)
@@ -236,7 +227,7 @@ func (b *BaseApi) SetUserAuthorities(c *gin.Context) {
var sua systemReq.SetUserAuthorities
_ = c.ShouldBindJSON(&sua)
if err := userService.SetUserAuthorities(sua.ID, sua.AuthorityIds); err != nil {
- global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("修改失败!", zap.Error(err))
response.FailWithMessage("修改失败", c)
} else {
response.OkWithMessage("修改成功", c)
@@ -264,7 +255,7 @@ func (b *BaseApi) DeleteUser(c *gin.Context) {
return
}
if err := userService.DeleteUser(reqId.ID); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -287,7 +278,7 @@ func (b *BaseApi) SetUserInfo(c *gin.Context) {
return
}
if err, ReqUser := userService.SetUserInfo(user); err != nil {
- global.GVA_LOG.Error("设置失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("设置失败!", zap.Error(err))
response.FailWithMessage("设置失败", c)
} else {
response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "设置成功", c)
@@ -304,9 +295,27 @@ func (b *BaseApi) SetUserInfo(c *gin.Context) {
func (b *BaseApi) GetUserInfo(c *gin.Context) {
uuid := utils.GetUserUuid(c)
if err, ReqUser := userService.GetUserInfo(uuid); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "获取成功", c)
}
}
+
+// @Tags SysUser
+// @Summary 用户修改密码
+// @Security ApiKeyAuth
+// @Produce application/json
+// @Param data body system.SysUser true "ID"
+// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
+// @Router /user/resetPassword [post]
+func (b *BaseApi) ResetPassword(c *gin.Context) {
+ var user system.SysUser
+ _ = c.ShouldBindJSON(&user)
+ if err := userService.ResetPassword(user.ID); err != nil {
+ global.GVA_LOG.Error("重置失败!", zap.Error(err))
+ response.FailWithMessage("重置失败"+err.Error(), c)
+ } else {
+ response.OkWithMessage("重置成功", c)
+ }
+}
diff --git a/server/config.docker.yaml b/server/config.docker.yaml
index 886c1b45..4ae96ec2 100644
--- a/server/config.docker.yaml
+++ b/server/config.docker.yaml
@@ -81,7 +81,6 @@ autocode:
server-service: /service
web: /web/src
web-api: /api
- web-flow: /view
web-form: /view
web-table: /view
diff --git a/server/config.yaml b/server/config.yaml
index 8130f1ed..fa93b4bf 100644
--- a/server/config.yaml
+++ b/server/config.yaml
@@ -5,14 +5,13 @@ jwt:
signing-key: 'qmPlus'
expires-time: 604800
buffer-time: 86400
-
+ issuer: 'qmPlus'
# zap logger configuration
zap:
level: 'info'
format: 'console'
prefix: '[github.com/flipped-aurora/gin-vue-admin/server]'
director: 'log'
- link-name: 'latest_log'
show-line: true
encode-level: 'LowercaseColorLevelEncoder'
stacktrace-key: 'stacktrace'
@@ -45,6 +44,10 @@ system:
db-type: 'mysql'
oss-type: 'local' # 控制oss选择走本期还是 七牛等其他仓 自行增加其他oss仓可以在 server/utils/upload/upload.go 中 NewOss函数配置
use-multipoint: false
+ # IP限制次数 一个小时15000次
+ iplimit-count: 15000
+ # IP限制一个小时
+ iplimit-time: 3600
# captcha configuration
captcha:
@@ -56,14 +59,29 @@ captcha:
# 未初始化之前请勿手动修改数据库信息!!!如果一定要手动初始化请看(https://www.github.com/flipped-aurora/gin-vue-admin/server.com/docs/first)
mysql:
path: ''
+ port: ''
config: ''
db-name: ''
username: ''
password: ''
max-idle-conns: 10
max-open-conns: 100
- log-mode: false
- log-zap: ""
+ log-mode: ""
+ log-zap: false
+
+# pgsql connect configuration
+# 未初始化之前请勿手动修改数据库信息!!!如果一定要手动初始化请看(https://www.github.com/flipped-aurora/gin-vue-admin/server.com/docs/first)
+pgsql:
+ path: ''
+ port: ''
+ config: ''
+ db-name: ''
+ username: ''
+ password: ''
+ max-idle-conns: 10
+ max-open-conns: 100
+ log-mode: ""
+ log-zap: false
# local configuration
local:
@@ -72,6 +90,8 @@ local:
# autocode configuration
autocode:
transfer-restart: true
+ # root 自动适配项目根目录
+ # 请不要手动配置,他会在项目加载的时候识别出根路径
root: ""
server: /server
server-api: /api/v1/autocode
@@ -82,7 +102,6 @@ autocode:
server-service: /service/autocode
web: /web/src
web-api: /api
- web-flow: /view
web-form: /view
web-table: /view
@@ -134,3 +153,4 @@ Timer:
#{ tableName: "log2" , compareField: "created_at", interval: "2160h" }
]
+
diff --git a/server/config/auto_code.go b/server/config/auto_code.go
index f941e398..4182625c 100644
--- a/server/config/auto_code.go
+++ b/server/config/auto_code.go
@@ -14,5 +14,4 @@ type Autocode struct {
WApi string `mapstructure:"web-api" json:"webApi" yaml:"web-api"`
WForm string `mapstructure:"web-form" json:"webForm" yaml:"web-form"`
WTable string `mapstructure:"web-table" json:"webTable" yaml:"web-table"`
- WFlow string `mapstructure:"web-flow" json:"webFlow" yaml:"web-flow"`
}
diff --git a/server/config/config.go b/server/config/config.go
index 83d256f4..b3267cce 100644
--- a/server/config/config.go
+++ b/server/config/config.go
@@ -12,6 +12,7 @@ type Server struct {
AutoCode Autocode `mapstructure:"autoCode" json:"autoCode" yaml:"autoCode"`
// gorm
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
+ Pgsql Pgsql `mapstructure:"pgsql" json:"pgsql" yaml:"pgsql"`
// oss
Local Local `mapstructure:"local" json:"local" yaml:"local"`
Qiniu Qiniu `mapstructure:"qiniu" json:"qiniu" yaml:"qiniu"`
diff --git a/server/config/gorm.go b/server/config/gorm_mysql.go
similarity index 80%
rename from server/config/gorm.go
rename to server/config/gorm_mysql.go
index ae6c7384..b596c29b 100644
--- a/server/config/gorm.go
+++ b/server/config/gorm_mysql.go
@@ -1,7 +1,8 @@
package config
type Mysql struct {
- Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址:端口
+ 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:"dbname" yaml:"db-name"` // 数据库名
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
@@ -13,5 +14,5 @@ type Mysql struct {
}
func (m *Mysql) Dsn() string {
- return m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
+ return m.Username + ":" + m.Password + "@tcp(" + m.Path + ":" + m.Port + ")/" + m.Dbname + "?" + m.Config
}
diff --git a/server/config/gorm_pgsql.go b/server/config/gorm_pgsql.go
new file mode 100644
index 00000000..554da8b4
--- /dev/null
+++ b/server/config/gorm_pgsql.go
@@ -0,0 +1,26 @@
+package config
+
+type Pgsql 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:"dbname" yaml:"db-name"` // 数据库名
+ Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
+ Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
+ MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数
+ MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
+ LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志
+ LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件
+}
+
+// Dsn 基于配置文件获取 dsn
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (p *Pgsql) Dsn() string {
+ return "host=" + p.Path + " user=" + p.Username + " password=" + p.Password + " dbname=" + p.Dbname + " port=" + p.Port + " " + p.Config
+}
+
+// LinkDsn 根据 dbname 生成 dsn
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (p *Pgsql) LinkDsn(dbname string) string {
+ return "host=" + p.Path + " user=" + p.Username + " password=" + p.Password + " dbname=" + dbname + " port=" + p.Port + " " + p.Config
+}
diff --git a/server/config/jwt.go b/server/config/jwt.go
index 0ac7168f..4f419853 100644
--- a/server/config/jwt.go
+++ b/server/config/jwt.go
@@ -4,4 +4,5 @@ type JWT struct {
SigningKey string `mapstructure:"signing-key" json:"signingKey" yaml:"signing-key"` // jwt签名
ExpiresTime int64 `mapstructure:"expires-time" json:"expiresTime" yaml:"expires-time"` // 过期时间
BufferTime int64 `mapstructure:"buffer-time" json:"bufferTime" yaml:"buffer-time"` // 缓冲时间
+ Issuer string `mapstructure:"issuer" json:"issuer" yaml:"issuer"` // 签发者
}
diff --git a/server/config/system.go b/server/config/system.go
index 768788ab..8cf92b06 100644
--- a/server/config/system.go
+++ b/server/config/system.go
@@ -6,4 +6,6 @@ type System struct {
DbType string `mapstructure:"db-type" json:"dbType" yaml:"db-type"` // 数据库类型:mysql(默认)|sqlite|sqlserver|postgresql
OssType string `mapstructure:"oss-type" json:"ossType" yaml:"oss-type"` // Oss类型
UseMultipoint bool `mapstructure:"use-multipoint" json:"useMultipoint" yaml:"use-multipoint"` // 多点登录拦截
+ LimitCountIP int `mapstructure:"iplimit-count" json:"iplimitCount" yaml:"iplimit-count"`
+ LimitTimeIP int `mapstructure:"iplimit-time" json:"iplimitTime" yaml:"iplimit-time"`
}
diff --git a/server/config/zap.go b/server/config/zap.go
index f681ca83..e5a00916 100644
--- a/server/config/zap.go
+++ b/server/config/zap.go
@@ -5,7 +5,6 @@ type Zap struct {
Format string `mapstructure:"format" json:"format" yaml:"format"` // 输出
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 日志前缀
Director string `mapstructure:"director" json:"director" yaml:"director"` // 日志文件夹
- LinkName string `mapstructure:"link-name" json:"linkName" yaml:"link-name"` // 软链接名称
ShowLine bool `mapstructure:"show-line" json:"showLine" yaml:"showLine"` // 显示行
EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level"` // 编码级
StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key"` // 栈名
diff --git a/server/core/server.go b/server/core/server.go
index e11b3419..57dbfb15 100644
--- a/server/core/server.go
+++ b/server/core/server.go
@@ -38,7 +38,7 @@ func RunWindowsServer() {
fmt.Printf(`
欢迎使用 github.com/flipped-aurora/gin-vue-admin/server
- 当前版本:V2.4.5 beta
+ 当前版本:V2.4.6 Beta
加群方式:微信号:shouzi_1994 QQ群:622360840
默认自动化文档地址:http://127.0.0.1%s/swagger/index.html
默认前端文件运行地址:http://127.0.0.1:8080
diff --git a/server/core/server_other.go b/server/core/server_other.go
index ce159fe3..b95e9011 100644
--- a/server/core/server_other.go
+++ b/server/core/server_other.go
@@ -4,15 +4,16 @@
package core
import (
+ "time"
+
"github.com/fvbock/endless"
"github.com/gin-gonic/gin"
- "time"
)
func initServer(address string, router *gin.Engine) server {
s := endless.NewServer(address, router)
- s.ReadHeaderTimeout = 10 * time.Millisecond
- s.WriteTimeout = 10 * time.Second
+ s.ReadHeaderTimeout = 20 * time.Second
+ s.WriteTimeout = 20 * time.Second
s.MaxHeaderBytes = 1 << 20
return s
}
diff --git a/server/core/server_win.go b/server/core/server_win.go
index 60fb2681..e1c874ec 100644
--- a/server/core/server_win.go
+++ b/server/core/server_win.go
@@ -13,8 +13,8 @@ func initServer(address string, router *gin.Engine) server {
return &http.Server{
Addr: address,
Handler: router,
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 10 * time.Second,
+ ReadTimeout: 20 * time.Second,
+ WriteTimeout: 20 * time.Second,
MaxHeaderBytes: 1 << 20,
}
}
diff --git a/server/core/viper.go b/server/core/viper.go
index ddfdd217..bf0a11a9 100644
--- a/server/core/viper.go
+++ b/server/core/viper.go
@@ -56,9 +56,11 @@ func Viper(path ...string) *viper.Viper {
if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
+ // root 适配性
+ // 根据root位置去找到对应迁移位置,保证root路径有效
global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
global.BlackCache = local_cache.NewCache(
local_cache.SetDefaultExpire(time.Second * time.Duration(global.GVA_CONFIG.JWT.ExpiresTime)),
- )
+ )
return v
}
diff --git a/server/core/zap.go b/server/core/zap.go
index a0f40fe7..1abec961 100644
--- a/server/core/zap.go
+++ b/server/core/zap.go
@@ -11,38 +11,36 @@ import (
"go.uber.org/zap/zapcore"
)
-var level zapcore.Level
-
func Zap() (logger *zap.Logger) {
if ok, _ := utils.PathExists(global.GVA_CONFIG.Zap.Director); !ok { // 判断是否有Director文件夹
fmt.Printf("create %v directory\n", global.GVA_CONFIG.Zap.Director)
_ = os.Mkdir(global.GVA_CONFIG.Zap.Director, os.ModePerm)
}
+ // 调试级别
+ debugPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
+ return lev == zap.DebugLevel
+ })
+ // 日志级别
+ infoPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
+ return lev == zap.InfoLevel
+ })
+ // 警告级别
+ warnPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
+ return lev == zap.WarnLevel
+ })
+ // 错误级别
+ errorPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
+ return lev >= zap.ErrorLevel
+ })
- switch global.GVA_CONFIG.Zap.Level { // 初始化配置文件的Level
- case "debug":
- level = zap.DebugLevel
- case "info":
- level = zap.InfoLevel
- case "warn":
- level = zap.WarnLevel
- case "error":
- level = zap.ErrorLevel
- case "dpanic":
- level = zap.DPanicLevel
- case "panic":
- level = zap.PanicLevel
- case "fatal":
- level = zap.FatalLevel
- default:
- level = zap.InfoLevel
+ cores := [...]zapcore.Core{
+ getEncoderCore(fmt.Sprintf("./%s/server_debug.log", global.GVA_CONFIG.Zap.Director), debugPriority),
+ getEncoderCore(fmt.Sprintf("./%s/server_info.log", global.GVA_CONFIG.Zap.Director), infoPriority),
+ getEncoderCore(fmt.Sprintf("./%s/server_warn.log", global.GVA_CONFIG.Zap.Director), warnPriority),
+ getEncoderCore(fmt.Sprintf("./%s/server_error.log", global.GVA_CONFIG.Zap.Director), errorPriority),
}
+ logger = zap.New(zapcore.NewTee(cores[:]...), zap.AddCaller())
- if level == zap.DebugLevel || level == zap.ErrorLevel {
- logger = zap.New(getEncoderCore(), zap.AddStacktrace(level))
- } else {
- logger = zap.New(getEncoderCore())
- }
if global.GVA_CONFIG.Zap.ShowLine {
logger = logger.WithOptions(zap.AddCaller())
}
@@ -88,12 +86,8 @@ func getEncoder() zapcore.Encoder {
}
// getEncoderCore 获取Encoder的zapcore.Core
-func getEncoderCore() (core zapcore.Core) {
- writer, err := utils.GetWriteSyncer() // 使用file-rotatelogs进行日志分割
- if err != nil {
- fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
- return
- }
+func getEncoderCore(fileName string, level zapcore.LevelEnabler) (core zapcore.Core) {
+ writer := utils.GetWriteSyncer(fileName) // 使用file-rotatelogs进行日志分割
return zapcore.NewCore(getEncoder(), writer, level)
}
diff --git a/server/docs/docs.go b/server/docs/docs.go
index a0abd332..62955b57 100644
--- a/server/docs/docs.go
+++ b/server/docs/docs.go
@@ -3576,9 +3576,6 @@ var doc = `{
"webApi": {
"type": "string"
},
- "webFlow": {
- "type": "string"
- },
"webForm": {
"type": "string"
},
diff --git a/server/docs/swagger.json b/server/docs/swagger.json
index 60db1a59..4a5f9741 100644
--- a/server/docs/swagger.json
+++ b/server/docs/swagger.json
@@ -3560,9 +3560,6 @@
"webApi": {
"type": "string"
},
- "webFlow": {
- "type": "string"
- },
"webForm": {
"type": "string"
},
diff --git a/server/docs/swagger.yaml b/server/docs/swagger.yaml
index fae34820..39944813 100644
--- a/server/docs/swagger.yaml
+++ b/server/docs/swagger.yaml
@@ -54,8 +54,6 @@ definitions:
type: string
webApi:
type: string
- webFlow:
- type: string
webForm:
type: string
webTable:
diff --git a/server/go.mod b/server/go.mod
index 0cfd9d05..5a52a65e 100644
--- a/server/go.mod
+++ b/server/go.mod
@@ -17,23 +17,27 @@ require (
github.com/go-sql-driver/mysql v1.5.0
github.com/gookit/color v1.3.1
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84
- github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible
github.com/mojocn/base64Captcha v1.3.1
+ github.com/natefinch/lumberjack v2.0.0+incompatible
+ github.com/pkg/errors v0.9.1
github.com/qiniu/api.v7/v7 v7.4.1
github.com/robfig/cron/v3 v3.0.1
github.com/satori/go.uuid v1.2.0
- github.com/shirou/gopsutil v3.21.1+incompatible
+ github.com/shirou/gopsutil v3.21.9+incompatible
github.com/songzhibin97/gkit v1.1.1
github.com/spf13/viper v1.7.0
- github.com/stretchr/testify v1.7.0 // indirect
+ github.com/stretchr/testify v1.7.0
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/tklauser/go-sysconf v0.3.9 // indirect
github.com/unrolled/secure v1.0.7
github.com/xuri/excelize/v2 v2.4.1
go.uber.org/zap v1.16.0
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
+ gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gorm.io/driver/mysql v1.0.1
- gorm.io/gorm v1.20.7
+ gorm.io/driver/postgres v0.2.6
+ gorm.io/gorm v1.20.11
nhooyr.io/websocket v1.8.6
)
diff --git a/server/go.sum b/server/go.sum
index 4cdf6692..7e9a9f43 100644
--- a/server/go.sum
+++ b/server/go.sum
@@ -83,7 +83,6 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
-github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJdVkTrXpu9KtoVCSo1hg7mtI7G9KU=
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/flipped-aurora/gin-vue-admin/server v0.0.0-20210823151324-f5410430faf0/go.mod h1:ksHCxOjTTQDk1Y1MrptfG6e9+s3rDJzQXkIZBHl8sws=
@@ -285,13 +284,11 @@ github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0f
github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
-github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 h1:IPJ3dvxmJ4uczJe5YQdrYB16oTJlGSC/OyZDqUk9xX4=
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869/go.mod h1:cJ6Cj7dQo+O6GJNiMx+Pa94qKj+TG8ONdKHgMNIyyag=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
-github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84 h1:pS0A6cr4aHYZnYwC7Uw+rwgb39+nzkm2QhwZ+S6Gn5I=
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
@@ -322,11 +319,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
-github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8=
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is=
-github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible h1:4mNlp+/SvALIPFpbXV3kxNJJno9iKFWGxSDE13Kl66Q=
github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA=
-github.com/lestrrat-go/strftime v1.0.3 h1:qqOPU7y+TM8Y803I8fG9c/DyKG3xH/xkng6keC1015Q=
github.com/lestrrat-go/strftime v1.0.3/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
@@ -377,6 +371,8 @@ github.com/mojocn/base64Captcha v1.3.1/go.mod h1:wAQCKEc5bDujxKRmbT6/vTnTt5CjStQ
github.com/mozillazg/go-httpheader v0.2.1 h1:geV7TrjbL8KXSyvghnFm+NyTux/hxwueTSrwhe88TQQ=
github.com/mozillazg/go-httpheader v0.2.1/go.mod h1:jJ8xECTlalr6ValeXYdOF8fFUISeBAdw6E61aqQma60=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
+github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
+github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
@@ -430,8 +426,9 @@ github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/shirou/gopsutil v3.20.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
-github.com/shirou/gopsutil v3.21.1+incompatible h1:2LwXWdbjXwyDgq26Yy/OT4xozlpmssQfy/rtfhWb0bY=
github.com/shirou/gopsutil v3.21.1+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
+github.com/shirou/gopsutil v3.21.9+incompatible h1:LTLpUnfX81MkHeCtSrwNKZwuW5Id6kCa7/P43NdcNn4=
+github.com/shirou/gopsutil v3.21.9+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc h1:jUIKcSPO9MoMJBbEoyE/RJoE8vz7Mb8AjvifMMwSyvY=
github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
@@ -463,7 +460,6 @@ github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM=
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
@@ -480,10 +476,13 @@ github.com/swaggo/gin-swagger v1.3.0/go.mod h1:oy1BRA6WvgtCp848lhxce7BnWH4C8Bxa0
github.com/swaggo/swag v1.5.1/go.mod h1:1Bl9F/ZBpVWh22nY0zmYyASPO1lI/zIwRDrpZU+tv8Y=
github.com/swaggo/swag v1.7.0 h1:5bCA/MTLQoIqDXXyHfOpMeDvL9j68OY/udlK4pQoo4E=
github.com/swaggo/swag v1.7.0/go.mod h1:BdPIL73gvS9NBsdi7M1JOxLvlbfvNRaBP8m6WT6Aajo=
-github.com/tebeka/strftime v0.1.3 h1:5HQXOqWKYRFfNyBMNVc9z5+QzuBtIXy03psIhtdJYto=
github.com/tebeka/strftime v0.1.3/go.mod h1:7wJm3dZlpr4l/oVK0t1HYIc4rMzQ2XJlOMIUJUJH6XQ=
github.com/tencentyun/cos-go-sdk-v5 v0.7.19 h1:janAfTO4MglOrUFuKGTQJBuMc66+F7TgtEIt1wPsJ+k=
github.com/tencentyun/cos-go-sdk-v5 v0.7.19/go.mod h1:wQBO5HdAkLjj2q6XQiIfDSP8DXDNrppDRw2Kp/1BODA=
+github.com/tklauser/go-sysconf v0.3.9 h1:JeUVdAOWhhxVcU6Eqr/ATFHgXk/mmiItdKeJPev3vTo=
+github.com/tklauser/go-sysconf v0.3.9/go.mod h1:11DU/5sG7UexIrp/O6g35hrWzu0JxlwQ3LSFUzyeuhs=
+github.com/tklauser/numcpus v0.3.0 h1:ILuRUQBtssgnxw0XXIjKUC56fgnOrFoQQ/4+DeU2biQ=
+github.com/tklauser/numcpus v0.3.0/go.mod h1:yFGUr7TUHQRAhyqBcEg0Ge34zDBAsIvJJcyE6boqnA8=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
@@ -640,8 +639,9 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71 h1:ikCpsnYR+Ew0vu99XlDp55lGgDJdIMx3f4a18jfse/s=
+golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -744,6 +744,8 @@ gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:a
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.55.0 h1:E8yzL5unfpW3M6fz/eB7Cb5MQAYSZ7GKo4Qth+N2sgQ=
gopkg.in/ini.v1 v1.55.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
+gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
+gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
@@ -769,8 +771,9 @@ gorm.io/driver/sqlserver v0.2.4/go.mod h1:TcPfkdce5b8qlCMgyUeUdm7HQa1ZzWUuxzI+od
gorm.io/gorm v0.2.19/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v0.2.23/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.9.19/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
-gorm.io/gorm v1.20.7 h1:rMS4CL3pNmYq1V5/X+nHHjh1Dx6dnf27+Cai5zabo+M=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
+gorm.io/gorm v1.20.11 h1:jYHQ0LLUViV85V8dM1TP9VBBkfzKTnuTXDjYObkI6yc=
+gorm.io/gorm v1.20.11/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
diff --git a/server/initialize/gorm.go b/server/initialize/gorm.go
index fbbab797..d22c3181 100644
--- a/server/initialize/gorm.go
+++ b/server/initialize/gorm.go
@@ -1,118 +1,60 @@
package initialize
import (
- "os"
-
"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/model/autocode"
"github.com/flipped-aurora/gin-vue-admin/server/model/example"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
+ "os"
"go.uber.org/zap"
- "gorm.io/driver/mysql"
"gorm.io/gorm"
- "gorm.io/gorm/logger"
)
-//@author: SliverHorn
-//@function: Gorm
-//@description: 初始化数据库并产生数据库全局变量
-//@return: *gorm.DB
-
+// Gorm 初始化数据库并产生数据库全局变量
+// Author SliverHorn
func Gorm() *gorm.DB {
switch global.GVA_CONFIG.System.DbType {
case "mysql":
return GormMysql()
+ case "pgsql":
+ return GormPgSql()
default:
return GormMysql()
}
}
-// MysqlTables
-//@author: SliverHorn
-//@function: MysqlTables
-//@description: 注册数据库表专用
-//@param: db *gorm.DB
-
-func MysqlTables(db *gorm.DB) {
+// RegisterTables 注册数据库表专用
+// Author SliverHorn
+func RegisterTables(db *gorm.DB) {
err := db.AutoMigrate(
- system.SysUser{},
- system.SysAuthority{},
+ // 系统模块表
system.SysApi{},
+ system.SysUser{},
system.SysBaseMenu{},
- system.SysBaseMenuParameter{},
system.JwtBlacklist{},
+ system.SysAuthority{},
system.SysDictionary{},
- system.SysDictionaryDetail{},
- example.ExaFileUploadAndDownload{},
- example.ExaFile{},
- example.ExaFileChunk{},
- example.ExaCustomer{},
system.SysOperationRecord{},
system.SysAutoCodeHistory{},
+ system.SysDictionaryDetail{},
+ system.SysBaseMenuParameter{},
+
+ // 示例模块表
+ example.ExaFile{},
+ example.ExaCustomer{},
+ example.ExaFileChunk{},
+ example.ExaFileUploadAndDownload{},
+
+ // 自动化模块表
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
autocode.AutoCodeExample{},
// 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.Any("err", err))
+ global.GVA_LOG.Error("register table failed", zap.Error(err))
os.Exit(0)
}
global.GVA_LOG.Info("register table success")
}
-
-//@author: SliverHorn
-//@function: GormMysql
-//@description: 初始化Mysql数据库
-//@return: *gorm.DB
-
-func GormMysql() *gorm.DB {
- m := global.GVA_CONFIG.Mysql
- if m.Dbname == "" {
- return nil
- }
- dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
- mysqlConfig := mysql.Config{
- DSN: dsn, // DSN data source name
- DefaultStringSize: 191, // string 类型字段的默认长度
- DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
- DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
- DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
- SkipInitializeWithVersion: false, // 根据版本自动配置
- }
- if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig()); err != nil {
- //global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
- //os.Exit(0)
- //return nil
- return nil
- } else {
- sqlDB, _ := db.DB()
- sqlDB.SetMaxIdleConns(m.MaxIdleConns)
- sqlDB.SetMaxOpenConns(m.MaxOpenConns)
- return db
- }
-}
-
-//@author: SliverHorn
-//@function: gormConfig
-//@description: 根据配置决定是否开启日志
-//@param: mod bool
-//@return: *gorm.Config
-
-func gormConfig() *gorm.Config {
- config := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}
- switch global.GVA_CONFIG.Mysql.LogMode {
- case "silent", "Silent":
- config.Logger = internal.Default.LogMode(logger.Silent)
- case "error", "Error":
- config.Logger = internal.Default.LogMode(logger.Error)
- case "warn", "Warn":
- config.Logger = internal.Default.LogMode(logger.Warn)
- case "info", "Info":
- config.Logger = internal.Default.LogMode(logger.Info)
- default:
- config.Logger = internal.Default.LogMode(logger.Info)
- }
- return config
-}
diff --git a/server/initialize/gorm_mysql.go b/server/initialize/gorm_mysql.go
new file mode 100644
index 00000000..851fa8de
--- /dev/null
+++ b/server/initialize/gorm_mysql.go
@@ -0,0 +1,31 @@
+package initialize
+
+import (
+ "github.com/flipped-aurora/gin-vue-admin/server/global"
+ "github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
+ "gorm.io/driver/mysql"
+ "gorm.io/gorm"
+)
+
+// GormMysql 初始化Mysql数据库
+// Author [piexlmax](https://github.com/piexlmax)
+// Author [SliverHorn](https://github.com/SliverHorn)
+func GormMysql() *gorm.DB {
+ m := global.GVA_CONFIG.Mysql
+ if m.Dbname == "" {
+ return nil
+ }
+ mysqlConfig := mysql.Config{
+ DSN: m.Dsn(), // DSN data source name
+ DefaultStringSize: 191, // string 类型字段的默认长度
+ SkipInitializeWithVersion: false, // 根据版本自动配置
+ }
+ if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config()); err != nil {
+ return nil
+ } else {
+ sqlDB, _ := db.DB()
+ sqlDB.SetMaxIdleConns(m.MaxIdleConns)
+ sqlDB.SetMaxOpenConns(m.MaxOpenConns)
+ return db
+ }
+}
diff --git a/server/initialize/gorm_pgsql.go b/server/initialize/gorm_pgsql.go
new file mode 100644
index 00000000..e178a277
--- /dev/null
+++ b/server/initialize/gorm_pgsql.go
@@ -0,0 +1,30 @@
+package initialize
+
+import (
+ "github.com/flipped-aurora/gin-vue-admin/server/global"
+ "github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+)
+
+// GormPgSql 初始化 Postgresql 数据库
+// Author [piexlmax](https://github.com/piexlmax)
+// Author [SliverHorn](https://github.com/SliverHorn)
+func GormPgSql() *gorm.DB {
+ p := global.GVA_CONFIG.Pgsql
+ if p.Dbname == "" {
+ return nil
+ }
+ pgsqlConfig := postgres.Config{
+ DSN: p.Dsn(), // DSN data source name
+ PreferSimpleProtocol: false,
+ }
+ if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config()); err != nil {
+ return nil
+ } else {
+ sqlDB, _ := db.DB()
+ sqlDB.SetMaxIdleConns(p.MaxIdleConns)
+ sqlDB.SetMaxOpenConns(p.MaxOpenConns)
+ return db
+ }
+}
diff --git a/server/initialize/internal/gorm.go b/server/initialize/internal/gorm.go
new file mode 100644
index 00000000..0502857a
--- /dev/null
+++ b/server/initialize/internal/gorm.go
@@ -0,0 +1,38 @@
+package internal
+
+import (
+ "github.com/flipped-aurora/gin-vue-admin/server/global"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+ "log"
+ "os"
+ "time"
+)
+
+var Gorm = new(_gorm)
+
+type _gorm struct{}
+
+// Config gorm 自定义配置
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (g *_gorm) Config() *gorm.Config {
+ config := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}
+ _default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{
+ SlowThreshold: 200 * time.Millisecond,
+ LogLevel: logger.Warn,
+ Colorful: true,
+ })
+ switch global.GVA_CONFIG.Mysql.LogMode {
+ case "silent", "Silent":
+ config.Logger = _default.LogMode(logger.Silent)
+ case "error", "Error":
+ config.Logger = _default.LogMode(logger.Error)
+ case "warn", "Warn":
+ config.Logger = _default.LogMode(logger.Warn)
+ case "info", "Info":
+ config.Logger = _default.LogMode(logger.Info)
+ default:
+ config.Logger = _default.LogMode(logger.Info)
+ }
+ return config
+}
diff --git a/server/initialize/internal/logger.go b/server/initialize/internal/logger.go
index 25b7b8ca..89bd14a3 100644
--- a/server/initialize/internal/logger.go
+++ b/server/initialize/internal/logger.go
@@ -1,153 +1,34 @@
package internal
import (
- "context"
"fmt"
- "io/ioutil"
- "log"
- "os"
- "time"
-
"github.com/flipped-aurora/gin-vue-admin/server/global"
"gorm.io/gorm/logger"
- "gorm.io/gorm/utils"
)
-type config struct {
- SlowThreshold time.Duration
- Colorful bool
- LogLevel logger.LogLevel
-}
-
-var (
- Discard = New(log.New(ioutil.Discard, "", log.LstdFlags), config{})
- Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), config{
- SlowThreshold: 200 * time.Millisecond,
- LogLevel: logger.Warn,
- Colorful: true,
- })
- Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()}
-)
-
-func New(writer logger.Writer, config config) logger.Interface {
- var (
- infoStr = "%s\n[info] "
- warnStr = "%s\n[warn] "
- errStr = "%s\n[error] "
- traceStr = "%s\n[%.3fms] [rows:%v] %s\n"
- traceWarnStr = "%s %s\n[%.3fms] [rows:%v] %s\n"
- traceErrStr = "%s %s\n[%.3fms] [rows:%v] %s\n"
- )
-
- if config.Colorful {
- infoStr = logger.Green + "%s\n" + logger.Reset + logger.Green + "[info] " + logger.Reset
- warnStr = logger.BlueBold + "%s\n" + logger.Reset + logger.Magenta + "[warn] " + logger.Reset
- errStr = logger.Magenta + "%s\n" + logger.Reset + logger.Red + "[error] " + logger.Reset
- traceStr = logger.Green + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s\n"
- traceWarnStr = logger.Green + "%s " + logger.Yellow + "%s\n" + logger.Reset + logger.RedBold + "[%.3fms] " + logger.Yellow + "[rows:%v]" + logger.Magenta + " %s\n" + logger.Reset
- traceErrStr = logger.RedBold + "%s " + logger.MagentaBold + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s\n"
- }
-
- return &_logger{
- Writer: writer,
- config: config,
- infoStr: infoStr,
- warnStr: warnStr,
- errStr: errStr,
- traceStr: traceStr,
- traceWarnStr: traceWarnStr,
- traceErrStr: traceErrStr,
- }
-}
-
-type _logger struct {
- config
+type writer struct {
logger.Writer
- infoStr, warnStr, errStr string
- traceStr, traceErrStr, traceWarnStr string
}
-// LogMode log mode
-func (c *_logger) LogMode(level logger.LogLevel) logger.Interface {
- newLogger := *c
- newLogger.LogLevel = level
- return &newLogger
+// NewWriter writer 构造函数
+// Author [SliverHorn](https://github.com/SliverHorn)
+func NewWriter(w logger.Writer) *writer {
+ return &writer{Writer: w}
}
-// Info print info
-func (c *_logger) Info(ctx context.Context, message string, data ...interface{}) {
- if c.LogLevel >= logger.Info {
- c.Printf(c.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
+// Printf 格式化打印日志
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (w *writer) Printf(message string, data ...interface{}) {
+ var logZap bool
+ switch global.GVA_CONFIG.System.DbType {
+ case "mysql":
+ logZap = global.GVA_CONFIG.Mysql.LogZap
+ case "pgsql":
+ logZap = global.GVA_CONFIG.Pgsql.LogZap
}
-}
-
-// Warn print warn messages
-func (c *_logger) Warn(ctx context.Context, message string, data ...interface{}) {
- if c.LogLevel >= logger.Warn {
- c.Printf(c.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
- }
-}
-
-// Error print error messages
-func (c *_logger) Error(ctx context.Context, message string, data ...interface{}) {
- if c.LogLevel >= logger.Error {
- c.Printf(c.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
- }
-}
-
-// Trace print sql message
-func (c *_logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
- if c.LogLevel > 0 {
- elapsed := time.Since(begin)
- switch {
- case err != nil && c.LogLevel >= logger.Error:
- sql, rows := fc()
- if rows == -1 {
- c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
- } else {
- c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
- }
- case elapsed > c.SlowThreshold && c.SlowThreshold != 0 && c.LogLevel >= logger.Warn:
- sql, rows := fc()
- slowLog := fmt.Sprintf("SLOW SQL >= %v", c.SlowThreshold)
- if rows == -1 {
- c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
- } else {
- c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
- }
- case c.LogLevel >= logger.Info:
- sql, rows := fc()
- if rows == -1 {
- c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
- } else {
- c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
- }
- }
- }
-}
-
-func (c *_logger) Printf(message string, data ...interface{}) {
- if global.GVA_CONFIG.Mysql.LogZap {
- global.GVA_LOG.Info(fmt.Sprintf(message, data...))
+ if logZap {
+ global.GVA_LOG.Info(fmt.Sprintf(message+"\n", data...))
} else {
- c.Writer.Printf(message, data...)
+ w.Writer.Printf(message, data...)
}
}
-
-type traceRecorder struct {
- logger.Interface
- BeginAt time.Time
- SQL string
- RowsAffected int64
- Err error
-}
-
-func (t traceRecorder) New() *traceRecorder {
- return &traceRecorder{Interface: t.Interface, BeginAt: time.Now()}
-}
-
-func (t *traceRecorder) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
- t.BeginAt = begin
- t.SQL, t.RowsAffected = fc()
- t.Err = err
-}
diff --git a/server/initialize/redis.go b/server/initialize/redis.go
index afc2868e..f52829b3 100644
--- a/server/initialize/redis.go
+++ b/server/initialize/redis.go
@@ -18,7 +18,7 @@ func Redis() {
})
pong, err := client.Ping(context.Background()).Result()
if err != nil {
- global.GVA_LOG.Error("redis connect ping failed, err:", zap.Any("err", err))
+ global.GVA_LOG.Error("redis connect ping failed, err:", zap.Error(err))
} else {
global.GVA_LOG.Info("redis connect ping response:", zap.String("pong", pong))
global.GVA_REDIS = client
diff --git a/server/initialize/router.go b/server/initialize/router.go
index 000f33a2..79cb2c2d 100644
--- a/server/initialize/router.go
+++ b/server/initialize/router.go
@@ -23,7 +23,7 @@ func Routers() *gin.Engine {
// 然后执行打包命令 npm run build。在打开下面4行注释
//Router.LoadHTMLGlob("./dist/*.html") // npm打包成dist的路径
//Router.Static("/favicon.ico", "./dist/favicon.ico")
- //Router.Static("/static", "./dist/static") // dist里面的静态资源
+ //Router.Static("/static", "./dist/assets") // dist里面的静态资源
//Router.StaticFile("/", "./dist/index.html") // 前端网页入口页面
Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.Path)) // 为用户头像和文件提供静态地址
@@ -41,6 +41,12 @@ func Routers() *gin.Engine {
exampleRouter := router.RouterGroupApp.Example
autocodeRouter := router.RouterGroupApp.Autocode
PublicGroup := Router.Group("")
+ {
+ // 健康监测
+ PublicGroup.GET("/health", func(c *gin.Context) {
+ c.JSON(200, "ok")
+ })
+ }
{
systemRouter.InitBaseRouter(PublicGroup) // 注册基础功能路由 不做鉴权
systemRouter.InitInitRouter(PublicGroup) // 自动初始化相关
@@ -48,20 +54,22 @@ func Routers() *gin.Engine {
PrivateGroup := Router.Group("")
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.InitSysOperationRecordRouter(PrivateGroup) // 操作记录
- systemRouter.InitSysDictionaryDetailRouter(PrivateGroup) // 字典详情管理
- exampleRouter.InitFileUploadAndDownloadRouter(PrivateGroup) // 文件上传下载功能路由
+ 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) // 字典详情管理
+
exampleRouter.InitExcelRouter(PrivateGroup) // 表格导入导出
exampleRouter.InitCustomerRouter(PrivateGroup) // 客户路由
+ exampleRouter.InitFileUploadAndDownloadRouter(PrivateGroup) // 文件上传下载功能路由
// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
autocodeRouter.InitSysAutoCodeExampleRouter(PrivateGroup)
diff --git a/server/main.go b/server/main.go
index 0a74adb3..e607749a 100644
--- a/server/main.go
+++ b/server/main.go
@@ -24,11 +24,10 @@ func main() {
global.GVA_DB = initialize.Gorm() // gorm连接数据库
initialize.Timer()
if global.GVA_DB != nil {
- initialize.MysqlTables(global.GVA_DB) // 初始化表
+ initialize.RegisterTables(global.GVA_DB) // 初始化表
// 程序结束前关闭数据库链接
db, _ := global.GVA_DB.DB()
defer db.Close()
}
core.RunWindowsServer()
-
}
diff --git a/server/middleware/casbin_rbac.go b/server/middleware/casbin_rbac.go
index 05bba88c..b21345ec 100644
--- a/server/middleware/casbin_rbac.go
+++ b/server/middleware/casbin_rbac.go
@@ -3,8 +3,8 @@ 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/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"
)
@@ -13,8 +13,7 @@ var casbinService = service.ServiceGroupApp.SystemServiceGroup.CasbinService
// 拦截器
func CasbinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
- claims, _ := c.Get("claims")
- waitUse := claims.(*request.CustomClaims)
+ waitUse, _ := utils.GetClaims(c)
// 获取请求的URI
obj := c.Request.URL.RequestURI()
// 获取请求方法
diff --git a/server/middleware/email.go b/server/middleware/email.go
index 9942599e..17ff9138 100644
--- a/server/middleware/email.go
+++ b/server/middleware/email.go
@@ -2,13 +2,13 @@ package middleware
import (
"github.com/flipped-aurora/gin-vue-admin/server/plugin/email/utils"
+ utils2 "github.com/flipped-aurora/gin-vue-admin/server/utils"
"io/ioutil"
"strconv"
"time"
"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/model/system/request"
"github.com/flipped-aurora/gin-vue-admin/server/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -19,9 +19,9 @@ var userService = service.ServiceGroupApp.SystemServiceGroup.UserService
func ErrorToEmail() gin.HandlerFunc {
return func(c *gin.Context) {
var username string
- if claims, ok := c.Get("claims"); ok {
- waitUse := claims.(*request.CustomClaims)
- username = waitUse.Username
+ claims, _ := utils2.GetClaims(c)
+ if claims.Username != "" {
+ username = claims.Username
} else {
id, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
err, user := userService.FindUserById(id)
@@ -49,7 +49,7 @@ func ErrorToEmail() gin.HandlerFunc {
if status != 200 {
subject := username + "" + record.Ip + "调用了" + record.Path + "报错了"
if err := utils.ErrorToEmail(subject, str); err != nil {
- global.GVA_LOG.Error("ErrorToEmail Failed, err:", zap.Any("err", err))
+ global.GVA_LOG.Error("ErrorToEmail Failed, err:", zap.Error(err))
}
}
}
diff --git a/server/middleware/jwt.go b/server/middleware/jwt.go
index 576a3da4..749723c4 100644
--- a/server/middleware/jwt.go
+++ b/server/middleware/jwt.go
@@ -58,7 +58,7 @@ func JWTAuth() gin.HandlerFunc {
if global.GVA_CONFIG.System.UseMultipoint {
err, RedisJwtToken := jwtService.GetRedisJWT(newClaims.Username)
if err != nil {
- global.GVA_LOG.Error("get redis jwt failed", zap.Any("err", err))
+ global.GVA_LOG.Error("get redis jwt failed", zap.Error(err))
} else { // 当之前的取成功时才进行拉黑操作
_ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: RedisJwtToken})
}
diff --git a/server/middleware/limit_ip.go b/server/middleware/limit_ip.go
new file mode 100644
index 00000000..9e951415
--- /dev/null
+++ b/server/middleware/limit_ip.go
@@ -0,0 +1,94 @@
+package middleware
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "time"
+
+ "go.uber.org/zap"
+
+ "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"
+)
+
+type LimitConfig struct {
+ // GenerationKey 根据业务生成key 下面CheckOrMark查询生成
+ GenerationKey func(c *gin.Context) string
+ // 检查函数,用户可修改具体逻辑,更加灵活
+ CheckOrMark func(key string, expire int, limit int) error
+ // Expire key 过期时间
+ Expire int
+ // Limit 周期时间
+ Limit int
+}
+
+func (l LimitConfig) LimitWithTime() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ if err := l.CheckOrMark(l.GenerationKey(c), l.Expire, l.Limit); err != nil {
+ c.JSON(http.StatusOK, gin.H{"code": response.ERROR, "msg": err})
+ c.Abort()
+ return
+ } else {
+ c.Next()
+ }
+ }
+}
+
+// DefaultGenerationKey 默认生成key
+func DefaultGenerationKey(c *gin.Context) string {
+ return "GVA_Limit" + c.ClientIP()
+}
+
+func DefaultCheckOrMark(key string, expire int, limit int) (err error) {
+ // 判断是否开启redis
+ if global.GVA_REDIS == nil {
+ return err
+ }
+ if err = SetLimitWithTime(key, limit, time.Duration(expire)*time.Second); err != nil {
+ global.GVA_LOG.Error("limit", zap.Error(err))
+
+ }
+ return err
+
+}
+
+func DefaultLimit() gin.HandlerFunc {
+ return LimitConfig{
+ GenerationKey: DefaultGenerationKey,
+ CheckOrMark: DefaultCheckOrMark,
+ Expire: global.GVA_CONFIG.System.LimitTimeIP,
+ Limit: global.GVA_CONFIG.System.LimitCountIP,
+ }.LimitWithTime()
+}
+
+// SetLimitWithTime 设置访问次数
+func SetLimitWithTime(key string, limit int, expiration time.Duration) error {
+ count, err := global.GVA_REDIS.Exists(context.Background(), key).Result()
+ if err != nil {
+ return err
+ }
+ if count == 0 {
+ pipe := global.GVA_REDIS.TxPipeline()
+ pipe.Incr(context.Background(), key)
+ pipe.Expire(context.Background(), key, expiration)
+ _, err = pipe.Exec(context.Background())
+ return err
+ } else {
+ //次数
+ if times, err := global.GVA_REDIS.Get(context.Background(), key).Int(); err != nil {
+ return err
+ } else {
+ if times >= limit {
+ if t, err := global.GVA_REDIS.PTTL(context.Background(), key).Result(); err != nil {
+ return errors.New("请求太过频繁,请稍后再试")
+ } else {
+ return errors.New("请求太过频繁, 请 " + t.String() + " 秒后尝试")
+ }
+ } else {
+ return global.GVA_REDIS.Incr(context.Background(), key).Err()
+ }
+ }
+ }
+}
diff --git a/server/middleware/logger.go b/server/middleware/logger.go
new file mode 100644
index 00000000..5bfda9a5
--- /dev/null
+++ b/server/middleware/logger.go
@@ -0,0 +1,87 @@
+package middleware
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+)
+
+// LogLayout 日志layout
+type LogLayout struct {
+ Time time.Time
+ Metadata map[string]interface{} // 存储自定义原数据
+ Path string // 访问路径
+ Query string // 携带query
+ Body string // 携带body数据
+ IP string // ip地址
+ UserAgent string // 代理
+ Error string // 错误
+ Cost time.Duration // 花费时间
+ Source string // 来源
+}
+
+type Logger struct {
+ // Filter 用户自定义过滤
+ Filter func(c *gin.Context) bool
+ // FilterKeyword 关键字过滤(key)
+ FilterKeyword func(layout *LogLayout) bool
+ // AuthProcess 鉴权处理
+ AuthProcess func(c *gin.Context, layout *LogLayout)
+ // 日志处理
+ Print func(LogLayout)
+ // Source 服务唯一标识
+ Source string
+}
+
+func (l Logger) SetLoggerMiddleware() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ start := time.Now()
+ path := c.Request.URL.Path
+ query := c.Request.URL.RawQuery
+ var body []byte
+ if l.Filter != nil && !l.Filter(c) {
+ body, _ = c.GetRawData()
+ // 将原body塞回去
+ c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
+ }
+ c.Next()
+ cost := time.Since(start)
+ layout := LogLayout{
+ Time: time.Now(),
+ Path: path,
+ Query: query,
+ IP: c.ClientIP(),
+ UserAgent: c.Request.UserAgent(),
+ Error: strings.TrimRight(c.Errors.ByType(gin.ErrorTypePrivate).String(), "\n"),
+ Cost: cost,
+ Source: l.Source,
+ }
+ if l.Filter != nil && !l.Filter(c) {
+ layout.Body = string(body)
+ }
+ // 处理鉴权需要的信息
+ l.AuthProcess(c, &layout)
+ if l.FilterKeyword != nil {
+ // 自行判断key/value 脱敏等
+ l.FilterKeyword(&layout)
+ }
+ // 自行处理日志
+ l.Print(layout)
+ }
+}
+
+func DefaultLogger() gin.HandlerFunc {
+ return Logger{
+ Print: func(layout LogLayout) {
+ // 标准输出,k8s做收集
+ v, _ := json.Marshal(layout)
+ fmt.Println(string(v))
+ },
+ Source: "GVA",
+ }.SetLoggerMiddleware()
+}
diff --git a/server/middleware/operation.go b/server/middleware/operation.go
index 8e4539b2..05c85e34 100644
--- a/server/middleware/operation.go
+++ b/server/middleware/operation.go
@@ -2,6 +2,7 @@ package middleware
import (
"bytes"
+ "github.com/flipped-aurora/gin-vue-admin/server/utils"
"io/ioutil"
"net/http"
"strconv"
@@ -9,7 +10,6 @@ import (
"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/model/system/request"
"github.com/flipped-aurora/gin-vue-admin/server/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -25,14 +25,14 @@ func OperationRecord() gin.HandlerFunc {
var err error
body, err = ioutil.ReadAll(c.Request.Body)
if err != nil {
- global.GVA_LOG.Error("read body from request error:", zap.Any("err", err))
+ global.GVA_LOG.Error("read body from request error:", zap.Error(err))
} else {
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
}
}
- if claims, ok := c.Get("claims"); ok {
- waitUse := claims.(*request.CustomClaims)
- userId = int(waitUse.ID)
+ claims, _ := utils.GetClaims(c)
+ if claims.ID != 0 {
+ userId = int(claims.ID)
} else {
id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
if err != nil {
@@ -69,7 +69,7 @@ func OperationRecord() gin.HandlerFunc {
record.Resp = writer.body.String()
if err := operationRecordService.CreateSysOperationRecord(record); err != nil {
- global.GVA_LOG.Error("create operation record error:", zap.Any("err", err))
+ global.GVA_LOG.Error("create operation record error:", zap.Error(err))
}
}
}
diff --git a/server/model/common/request/common.go b/server/model/common/request/common.go
index 129c6d7e..db8bba45 100644
--- a/server/model/common/request/common.go
+++ b/server/model/common/request/common.go
@@ -1,21 +1,25 @@
package request
-// Paging common input parameter structure
+// PageInfo Paging common input parameter structure
type PageInfo struct {
Page int `json:"page" form:"page"` // 页码
PageSize int `json:"pageSize" form:"pageSize"` // 每页大小
}
-// Find by id structure
+// GetById Find by id structure
type GetById struct {
ID float64 `json:"id" form:"id"` // 主键ID
}
+func (r *GetById) Uint() uint {
+ return uint(r.ID)
+}
+
type IdsReq struct {
Ids []int `json:"ids" form:"ids"`
}
-// Get role by id structure
+// GetAuthorityId Get role by id structure
type GetAuthorityId struct {
AuthorityId string `json:"authorityId" form:"authorityId"` // 角色ID
}
diff --git a/server/model/system/request/jwt.go b/server/model/system/request/jwt.go
index 7aa16429..bb673f66 100644
--- a/server/model/system/request/jwt.go
+++ b/server/model/system/request/jwt.go
@@ -7,11 +7,15 @@ import (
// Custom claims structure
type CustomClaims struct {
+ BaseClaims
+ BufferTime int64
+ jwt.StandardClaims
+}
+
+type BaseClaims struct {
UUID uuid.UUID
ID uint
Username string
NickName string
AuthorityId string
- BufferTime int64
- jwt.StandardClaims
}
diff --git a/server/model/system/request/sys_auto_history.go b/server/model/system/request/sys_auto_history.go
new file mode 100644
index 00000000..3ab8aea3
--- /dev/null
+++ b/server/model/system/request/sys_auto_history.go
@@ -0,0 +1,7 @@
+package request
+
+import "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
+
+type SysAutoHistory struct {
+ request.PageInfo
+}
diff --git a/server/model/system/request/sys_init.go b/server/model/system/request/sys_init.go
index 3f994cf3..d93602e6 100644
--- a/server/model/system/request/sys_init.go
+++ b/server/model/system/request/sys_init.go
@@ -1,9 +1,65 @@
package request
+import (
+ "fmt"
+ "github.com/flipped-aurora/gin-vue-admin/server/config"
+)
+
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"` // 数据库名
}
+
+// MysqlEmptyDsn msyql 空数据库 建库链接
+// Author SliverHorn
+func (i *InitDB) MysqlEmptyDsn() string {
+ if i.Host == "" {
+ i.Host = "127.0.0.1"
+ }
+ if i.Port == "" {
+ i.Port = "3306"
+ }
+ return fmt.Sprintf("%s:%s@tcp(%s:%s)/", i.UserName, i.Password, i.Host, i.Port)
+}
+
+// PgsqlEmptyDsn pgsql 空数据库 建库链接
+// Author SliverHorn
+func (i *InitDB) PgsqlEmptyDsn() string {
+ if i.Host == "" {
+ i.Host = "127.0.0.1"
+ }
+ if i.Port == "" {
+ i.Port = "3306"
+ }
+ return "host=" + i.Host + " user=" + i.UserName + " password=" + i.Password + " port=" + i.Port + " " + "sslmode=disable TimeZone=Asia/Shanghai"
+}
+
+// ToMysqlConfig 转换 config.Mysql
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (i *InitDB) ToMysqlConfig() config.Mysql {
+ return config.Mysql{
+ Path: i.Host,
+ Port: i.Port,
+ Dbname: i.DBName,
+ Username: i.UserName,
+ Password: i.Password,
+ Config: "charset=utf8mb4&parseTime=True&loc=Local",
+ }
+}
+
+// ToPgsqlConfig 转换 config.Pgsql
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (i *InitDB) ToPgsqlConfig() config.Pgsql {
+ return config.Pgsql{
+ Path: i.Host,
+ Port: i.Port,
+ Dbname: i.DBName,
+ Username: i.UserName,
+ Password: i.Password,
+ Config: "sslmode=disable TimeZone=Asia/Shanghai",
+ }
+}
diff --git a/server/model/system/request/sys_autocode.go b/server/model/system/response/sys_auto_code.go
similarity index 53%
rename from server/model/system/request/sys_autocode.go
rename to server/model/system/response/sys_auto_code.go
index 7216d91f..1e440053 100644
--- a/server/model/system/request/sys_autocode.go
+++ b/server/model/system/response/sys_auto_code.go
@@ -1,26 +1,16 @@
-package request
+package response
-import "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
-
-type SysAutoHistory struct {
- request.PageInfo
-}
-
-type AutoHistoryByID struct {
- ID uint `json:"id"`
-}
-
-type DBReq struct {
+type Db struct {
Database string `json:"database" gorm:"column:database"`
}
-type TableReq struct {
- TableName string `json:"tableName"`
+type Table struct {
+ TableName string `json:"tableName" gorm:"column:table_name"`
}
-type ColumnReq struct {
- ColumnName string `json:"columnName" gorm:"column:column_name"`
+type Column struct {
DataType string `json:"dataType" gorm:"column:data_type"`
+ 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"`
}
diff --git a/server/model/system/response/sys_auto_code_history.go b/server/model/system/response/sys_auto_code_history.go
new file mode 100644
index 00000000..a503a84d
--- /dev/null
+++ b/server/model/system/response/sys_auto_code_history.go
@@ -0,0 +1,13 @@
+package response
+
+import "time"
+
+type AutoCodeHistory struct {
+ ID uint `json:"ID" gorm:"column:id"`
+ CreatedAt time.Time `json:"CreatedAt" gorm:"column:created_at"`
+ UpdatedAt time.Time `json:"UpdatedAt" gorm:"column:updated_at"`
+ TableName string `json:"tableName" gorm:"column:table_name"`
+ StructName string `json:"structName" gorm:"column:struct_name"`
+ StructCNName string `json:"structCNName" gorm:"column:struct_cn_name"`
+ Flag int `json:"flag" gorm:"column:flag"`
+}
diff --git a/server/model/system/response/sys_captcha.go b/server/model/system/response/sys_captcha.go
index 9e78035a..4d482f9c 100644
--- a/server/model/system/response/sys_captcha.go
+++ b/server/model/system/response/sys_captcha.go
@@ -1,6 +1,7 @@
package response
type SysCaptchaResponse struct {
- CaptchaId string `json:"captchaId"`
- PicPath string `json:"picPath"`
+ CaptchaId string `json:"captchaId"`
+ PicPath string `json:"picPath"`
+ CaptchaLength int `json:"captchaLength""`
}
diff --git a/server/model/system/sys_auto_code.go b/server/model/system/sys_auto_code.go
index 7047b810..f3128898 100644
--- a/server/model/system/sys_auto_code.go
+++ b/server/model/system/sys_auto_code.go
@@ -2,7 +2,7 @@ package system
import "errors"
-// 初始版本自动化代码工具
+// AutoCodeStruct 初始版本自动化代码工具
type AutoCodeStruct struct {
StructName string `json:"structName"` // Struct名称
TableName string `json:"tableName"` // 表名
@@ -13,6 +13,7 @@ type AutoCodeStruct struct {
AutoCreateApiToSql bool `json:"autoCreateApiToSql"` // 是否自动创建api
AutoMoveFile bool `json:"autoMoveFile"` // 是否自动移动文件
Fields []*Field `json:"fields"`
+ DictTypes []string `json:"-"`
}
type Field struct {
diff --git a/server/model/system/sys_autocode_history.go b/server/model/system/sys_autocode_history.go
index 2250cb30..136be709 100644
--- a/server/model/system/sys_autocode_history.go
+++ b/server/model/system/sys_autocode_history.go
@@ -1,9 +1,13 @@
package system
-import "github.com/flipped-aurora/gin-vue-admin/server/global"
-
-// 自动迁移代码记录,用于回滚,重放使用
+import (
+ "github.com/flipped-aurora/gin-vue-admin/server/global"
+ "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
+ "strconv"
+ "strings"
+)
+// SysAutoCodeHistory 自动迁移代码记录,用于回滚,重放使用
type SysAutoCodeHistory struct {
global.GVA_MODEL
TableName string `json:"tableName"`
@@ -14,5 +18,20 @@ type SysAutoCodeHistory struct {
StructCNName string `json:"structCNName"`
ApiIDs string `json:"apiIDs,omitempty"` // api表注册内容
Flag int `json:"flag"` // 表示对应状态 0 代表创建, 1 代表回滚 ...
-
+}
+
+// ToRequestIds ApiIDs 转换 request.IdsReq
+// Author [SliverHorn](https://github.com/SliverHorn)
+func (m *SysAutoCodeHistory) ToRequestIds() request.IdsReq {
+ if m.ApiIDs == "" {
+ return request.IdsReq{}
+ }
+ slice := strings.Split(m.ApiIDs, ";")
+ ids := make([]int, 0, len(slice))
+ length := len(slice)
+ for i := 0; i < length; i++ {
+ id, _ := strconv.ParseInt(slice[i], 10, 32)
+ ids = append(ids, int(id))
+ }
+ return request.IdsReq{Ids: ids}
}
diff --git a/server/model/system/sys_initdb.go b/server/model/system/sys_initdb.go
index ae05a748..07ea0d3d 100644
--- a/server/model/system/sys_initdb.go
+++ b/server/model/system/sys_initdb.go
@@ -1,5 +1,79 @@
package system
+import "github.com/gookit/color"
+
type InitDBFunc interface {
Init() (err error)
}
+
+const (
+ Mysql = "mysql"
+ Pgsql = "pgsql"
+ InitSuccess = "\n[%v] --> 初始数据成功!\n"
+ AuthorityMenu = "\n[%v] --> %v 视图已存在!\n"
+ InitDataExist = "\n[%v] --> %v 表的初始数据已存在!\n"
+ InitDataFailed = "\n[%v] --> %v 表初始数据失败! \nerr: %+v\n"
+ InitDataSuccess = "\n[%v] --> %v 表初始数据成功!\n"
+)
+
+type InitData interface {
+ TableName() string
+ Initialize() error
+ CheckDataExist() bool
+}
+
+// MysqlDataInitialize Mysql 初始化接口使用封装
+// Author [SliverHorn](https://github.com/SliverHorn)
+func MysqlDataInitialize(inits ...InitData) error {
+ var entity SysMenu
+ for i := 0; i < len(inits); i++ {
+ if inits[i].TableName() == entity.TableName() {
+ if k := inits[i].CheckDataExist(); k {
+ color.Info.Printf(AuthorityMenu, Mysql, inits[i].TableName())
+ continue
+ }
+ } else {
+ if inits[i].CheckDataExist() {
+ color.Info.Printf(InitDataExist, Mysql, inits[i].TableName())
+ continue
+ }
+ }
+
+ if err := inits[i].Initialize(); err != nil {
+ color.Info.Printf(InitDataFailed, Mysql, err)
+ return err
+ } else {
+ color.Info.Printf(InitDataSuccess, Mysql, inits[i].TableName())
+ }
+ }
+ color.Info.Printf(InitSuccess, Mysql)
+ return nil
+}
+
+// PgsqlDataInitialize Pgsql 初始化接口使用封装
+// Author [SliverHorn](https://github.com/SliverHorn)
+func PgsqlDataInitialize(inits ...InitData) error {
+ var entity SysMenu
+ for i := 0; i < len(inits); i++ {
+ if inits[i].TableName() == entity.TableName() {
+ if k := inits[i].CheckDataExist(); k {
+ color.Info.Printf(AuthorityMenu, Pgsql, inits[i].TableName())
+ continue
+ }
+ } else {
+ if inits[i].CheckDataExist() {
+ color.Info.Printf(InitDataExist, Pgsql, inits[i].TableName())
+ continue
+ }
+ }
+
+ if err := inits[i].Initialize(); err != nil {
+ color.Info.Printf(InitDataFailed, Pgsql, err)
+ continue
+ } else {
+ color.Info.Printf(InitDataSuccess, Pgsql, inits[i].TableName())
+ }
+ }
+ color.Info.Printf(InitSuccess, Pgsql)
+ return nil
+}
diff --git a/server/model/system/sys_operation_record.go b/server/model/system/sys_operation_record.go
index 43bf7569..bd316bb4 100644
--- a/server/model/system/sys_operation_record.go
+++ b/server/model/system/sys_operation_record.go
@@ -17,8 +17,8 @@ type SysOperationRecord struct {
Latency time.Duration `json:"latency" form:"latency" gorm:"column:latency;comment:延迟" swaggertype:"string"` // 延迟
Agent string `json:"agent" form:"agent" gorm:"column:agent;comment:代理"` // 代理
ErrorMessage string `json:"error_message" form:"error_message" gorm:"column:error_message;comment:错误信息"` // 错误信息
- Body string `json:"body" form:"body" gorm:"type:longtext;column:body;comment:请求Body"` // 请求Body
- Resp string `json:"resp" form:"resp" gorm:"type:longtext;column:resp;comment:响应Body"` // 响应Body
+ Body string `json:"body" form:"body" gorm:"type:text;column:body;comment:请求Body"` // 请求Body
+ Resp string `json:"resp" form:"resp" gorm:"type:text;column:resp;comment:响应Body"` // 响应Body
UserID int `json:"user_id" form:"user_id" gorm:"column:user_id;comment:用户id"` // 用户id
User SysUser `json:"user"`
}
diff --git a/server/plugin/email/api/sys_email.go b/server/plugin/email/api/sys_email.go
index 03e13afa..2e8560d6 100644
--- a/server/plugin/email/api/sys_email.go
+++ b/server/plugin/email/api/sys_email.go
@@ -20,7 +20,7 @@ type EmailApi struct {
// @Router /email/emailTest [post]
func (s *EmailApi) EmailTest(c *gin.Context) {
if err := service.ServiceGroupApp.EmailTest(); err != nil {
- global.GVA_LOG.Error("发送失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("发送失败!", zap.Error(err))
response.FailWithMessage("发送失败", c)
} else {
response.OkWithData("发送成功", c)
@@ -38,7 +38,7 @@ func (s *EmailApi) SendEmail(c *gin.Context) {
var email email_response.Email
_ = c.ShouldBindJSON(&email)
if err := service.ServiceGroupApp.SendEmail(email.To, email.Subject, email.Body); err != nil {
- global.GVA_LOG.Error("发送失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("发送失败!", zap.Error(err))
response.FailWithMessage("发送失败", c)
} else {
response.OkWithData("发送成功", c)
diff --git a/server/plugin/ws/utils/utils.go b/server/plugin/ws/utils/utils.go
deleted file mode 100644
index 85f91fe0..00000000
--- a/server/plugin/ws/utils/utils.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package utils
-
-import (
- "github.com/flipped-aurora/gin-vue-admin/server/global"
- systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
- "github.com/gin-gonic/gin"
- uuid "github.com/satori/go.uuid"
-)
-
-// 从Gin的Context中获取从jwt解析出来的用户ID
-func GetUserID(c *gin.Context) uint {
- if claims, exists := c.Get("claims"); !exists {
- global.GVA_LOG.Error("从Gin的Context中获取从jwt解析出来的用户ID失败, 请检查路由是否使用jwt中间件!")
- return 0
- } else {
- waitUse := claims.(*systemReq.CustomClaims)
- return waitUse.ID
- }
-}
-
-// 从Gin的Context中获取从jwt解析出来的用户UUID
-func GetUserUuid(c *gin.Context) uuid.UUID {
- if claims, exists := c.Get("claims"); !exists {
- global.GVA_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
- return uuid.UUID{}
- } else {
- waitUse := claims.(*systemReq.CustomClaims)
- return waitUse.UUID
- }
-}
-
-// 从Gin的Context中获取从jwt解析出来的用户角色id
-func GetUserAuthorityId(c *gin.Context) string {
- if claims, exists := c.Get("claims"); !exists {
- global.GVA_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
- return ""
- } else {
- waitUse := claims.(*systemReq.CustomClaims)
- return waitUse.AuthorityId
- }
-}
-
-// 从Gin的Context中获取从jwt解析出来的用户角色id
-func GetUserInfo(c *gin.Context) *systemReq.CustomClaims {
- if claims, exists := c.Get("claims"); !exists {
- global.GVA_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
- return nil
- } else {
- waitUse := claims.(*systemReq.CustomClaims)
- return waitUse
- }
-}
diff --git a/server/resource/template/server/api.go.tpl b/server/resource/template/server/api.go.tpl
index 42dcad6f..2fb0689c 100644
--- a/server/resource/template/server/api.go.tpl
+++ b/server/resource/template/server/api.go.tpl
@@ -30,7 +30,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Create{{.StructName}}(c *gin.Con
var {{.Abbreviation}} autocode.{{.StructName}}
_ = c.ShouldBindJSON(&{{.Abbreviation}})
if err := {{.Abbreviation}}Service.Create{{.StructName}}({{.Abbreviation}}); err != nil {
- global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("创建失败!", zap.Error(err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
@@ -50,7 +50,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Delete{{.StructName}}(c *gin.Con
var {{.Abbreviation}} autocode.{{.StructName}}
_ = c.ShouldBindJSON(&{{.Abbreviation}})
if err := {{.Abbreviation}}Service.Delete{{.StructName}}({{.Abbreviation}}); err != nil {
- global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("删除失败!", zap.Error(err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
@@ -70,7 +70,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Delete{{.StructName}}ByIds(c *gi
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := {{.Abbreviation}}Service.Delete{{.StructName}}ByIds(IDS); err != nil {
- global.GVA_LOG.Error("批量删除失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
@@ -90,7 +90,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Update{{.StructName}}(c *gin.Con
var {{.Abbreviation}} autocode.{{.StructName}}
_ = c.ShouldBindJSON(&{{.Abbreviation}})
if err := {{.Abbreviation}}Service.Update{{.StructName}}({{.Abbreviation}}); err != nil {
- global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("更新失败!", zap.Error(err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
@@ -110,7 +110,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Find{{.StructName}}(c *gin.Conte
var {{.Abbreviation}} autocode.{{.StructName}}
_ = c.ShouldBindQuery(&{{.Abbreviation}})
if err, re{{.Abbreviation}} := {{.Abbreviation}}Service.Get{{.StructName}}({{.Abbreviation}}.ID); err != nil {
- global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("查询失败!", zap.Error(err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithData(gin.H{"re{{.Abbreviation}}": re{{.Abbreviation}}}, c)
@@ -130,7 +130,7 @@ func ({{.Abbreviation}}Api *{{.StructName}}Api) Get{{.StructName}}List(c *gin.Co
var pageInfo autocodeReq.{{.StructName}}Search
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := {{.Abbreviation}}Service.Get{{.StructName}}InfoList(pageInfo); err != nil {
- global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
+ global.GVA_LOG.Error("获取失败!", zap.Error(err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
diff --git a/server/resource/template/server/router.go.tpl b/server/resource/template/server/router.go.tpl
index a4db665a..85f0f2bc 100644
--- a/server/resource/template/server/router.go.tpl
+++ b/server/resource/template/server/router.go.tpl
@@ -12,13 +12,16 @@ type {{.StructName}}Router struct {
// Init{{.StructName}}Router 初始化 {{.StructName}} 路由信息
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.AutoCodeApiGroup.{{.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.GET("find{{.StructName}}", {{.Abbreviation}}Api.Find{{.StructName}}) // 根据ID获取{{.StructName}}
- {{.Abbreviation}}Router.GET("get{{.StructName}}List", {{.Abbreviation}}Api.Get{{.StructName}}List) // 获取{{.StructName}}列表
+ }
+ {
+ {{.Abbreviation}}RouterWithoutRecord.GET("find{{.StructName}}", {{.Abbreviation}}Api.Find{{.StructName}}) // 根据ID获取{{.StructName}}
+ {{.Abbreviation}}RouterWithoutRecord.GET("get{{.StructName}}List", {{.Abbreviation}}Api.Get{{.StructName}}List) // 获取{{.StructName}}列表
}
}
diff --git a/server/resource/template/server/service.go.tpl b/server/resource/template/server/service.go.tpl
index 2fc99f19..f944e6e8 100644
--- a/server/resource/template/server/service.go.tpl
+++ b/server/resource/template/server/service.go.tpl
@@ -58,23 +58,23 @@ func ({{.Abbreviation}}Service *{{.StructName}}Service)Get{{.StructName}}InfoLis
{{- if .FieldSearchType}}
{{- if eq .FieldType "string" }}
if info.{{.FieldName}} != "" {
- db = db.Where("`{{.ColumnName}}` {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+ {{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
+ db = db.Where("{{.ColumnName}} {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+ {{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
}
{{- else if eq .FieldType "bool" }}
if info.{{.FieldName}} != nil {
- db = db.Where("`{{.ColumnName}}` {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
+ db = db.Where("{{.ColumnName}} {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
}
{{- else if eq .FieldType "int" }}
if info.{{.FieldName}} != nil {
- db = db.Where("`{{.ColumnName}}` {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
+ db = db.Where("{{.ColumnName}} {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
}
{{- else if eq .FieldType "float64" }}
if info.{{.FieldName}} != nil {
- db = db.Where("`{{.ColumnName}}` {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
+ db = db.Where("{{.ColumnName}} {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
}
{{- else if eq .FieldType "time.Time" }}
if info.{{.FieldName}} != nil {
- db = db.Where("`{{.ColumnName}}` {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
+ db = db.Where("{{.ColumnName}} {{.FieldSearchType}} ?",{{if eq .FieldSearchType "LIKE"}}"%"+{{ end }}info.{{.FieldName}}{{if eq .FieldSearchType "LIKE"}}+"%"{{ end }})
}
{{- end }}
{{- end }}
diff --git a/server/resource/template/web/form.vue.tpl b/server/resource/template/web/form.vue.tpl
index cd19c74f..17e31158 100644
--- a/server/resource/template/web/form.vue.tpl
+++ b/server/resource/template/web/form.vue.tpl
@@ -1,36 +1,38 @@
确定要删除吗?
-确定要删除吗?
+
+ {{ card.label }}
+
- {{ card.label }}
-初始化须知
-1.您需有用一定的VUE和golang基础
+1.您需有用一定的VUE和GOLANG基础
2.请您确认是否已经阅读过官方文档
3.请您确认是否了解后续的配置流程
注:开发组不为文档中书写过的内容提供无偿服务
@@ -22,8 +22,9 @@欢迎使用GIN-VUE-ADMIN
-您需要初始化您的数据库并且填充初始数据
-确定要删除吗?
-