Compare commits

..
39 Commits
Author SHA1 Message Date
lwnmengjing 8557e1e160 Merge pull request #384 from go-admin-team/dev
admin中的公共中间件,提到common 495a9c5
2021-03-30 22:56:52 +08:00
linwenxiang dd16744676 refactor 🎨: admin中的公共中间件,提到common 2021-03-29 09:05:05 +08:00
linwenxiang 495a9c54aa refactor 🎨: admin中的公共中间件,提到common 2021-03-28 23:27:01 +08:00
wenjianzhang afab1ef7c9 docs📝 :修正readme 2021-03-26 15:08:15 +08:00
wenjianzhang 5e99363e9a docs📝 :修正readme 2021-03-26 15:06:12 +08:00
wenjianzhang 86c7c64a32 fix🐛 :修复角色数据权限更新失(#380) 2021-03-26 14:36:18 +08:00
wenjianzhang 44b9666302 fix🐛 :修复内容模块问题(#357)
fix🐛 :修复内容模块问题(#357)
2021-03-26 13:53:44 +08:00
wenjianzhang 91c9a2c7f9 fix🐛 :修复内容模块问题(#357) 2021-03-26 13:42:12 +08:00
wenjianzhang a65930b35b fix🐛 :修复已知bug (#377) 2021-03-26 09:03:21 +08:00
linwenxiang 9023b620fb Merge branch 'master' into dev 2021-03-25 22:28:24 +08:00
linwenxiang f188b34253 feat ✨: 使用runtime cache中的mq功能优化日志存储
perf 👌: 启用mq将日志存储从中间件中移除到消费者
2021-03-25 22:26:33 +08:00
wenjianzhang 8faf6c9aba docs📝 :更新readme 2021-03-25 19:14:42 +08:00
wenjianzhang 547a5eb8e4 fix🐛 :修复初始化Duplicate column name 'is_frontend' (#376) 2021-03-25 18:35:09 +08:00
linwenxiang 2459c877e0 Merge branch 'dev' 2021-03-25 14:47:12 +08:00
linwenxiang 93625a6d9f format 🥚:模版生成优化 2021-03-25 14:45:39 +08:00
linwenxiang 58b439f553 修复个人中心修改密码不生效问题 2021-03-25 11:34:30 +08:00
linwenxiang 78c67185fd 升级core依赖 2021-03-24 23:00:09 +08:00
lwnmengjing 265cc9350d Merge pull request #374 from go-admin-team/dev
优化生成的swagger
2021-03-24 22:49:33 +08:00
linwenxiang 4182bac3a2 修改模版,优化生成的swagger 2021-03-24 22:20:23 +08:00
linwenxiang 12893fc09d 修复swagger无法生成文档 2021-03-24 18:52:59 +08:00
linwenxiang 6fb7da87a3 优化logger设置获取流程 2021-03-24 16:49:04 +08:00
wenjianzhang 0ecf56cd8c docs📝 :更新 2021-03-17 19:21:28 +08:00
wenjianzhang 0c802ad366 feat✨ :菜单配置迁移脚本功能 2021-03-17 19:15:49 +08:00
wenjianzhang 0be7735855 publish🚀 v1.3.0 2021-03-17 16:42:47 +08:00
wenjianzhang 9c73558382 feat✨ :更新 2021-03-17 16:29:45 +08:00
wenjianzhang 4e370665dd feat✨ :去除系统配置表数据的sql 2021-03-17 16:26:28 +08:00
wenjianzhang 0194561056 Merge branch 'dev' of https://github.com/go-admin-team/go-admin into dev 2021-03-17 14:30:20 +08:00
wenjianzhang 5b69883a9f fix🐛 :系统配置初始化sql 2021-03-17 14:30:16 +08:00
linwenxiang b1789e5785 优化api返回方法 2021-03-17 12:43:52 +08:00
wenjianzhang 5756286641 fix🐛 :去掉迁移脚本中的数据库名称 2021-03-17 11:23:17 +08:00
wenjianzhang 6746dbd9cf feat✨ :参数配置中添加是否前台控制 2021-03-17 11:16:53 +08:00
wenjianzhang 2134d9fa58 fix🐛 :修复日志状态显示问题 2021-03-17 11:16:02 +08:00
wenjianzhang a8c00c5be1 fix🐛 :修复请求日志数据获取为空问题 2021-03-17 11:15:35 +08:00
wenjianzhang 51bc4423f7 feat✨ :系统配置统一使用参数设置功能
注意:系统配置表将设置为过时功能
2021-03-17 10:18:47 +08:00
linwenxiang 55a85babf8 升级go-admin-core依赖 2021-03-16 17:21:17 +08:00
linwenxiang c9f705e4f5 Merge remote-tracking branch 'origin/dev' into dev 2021-03-12 16:03:12 +08:00
linwenxiang 9bf9330410 api层写法统一 2021-03-12 16:02:29 +08:00
wenjianzhang f53ee3008a Update index.go 2021-03-12 12:14:54 +08:00
wenjianzhang 31ec3880da fix🐛 :修改接口默认页面地址 2021-03-12 12:14:15 +08:00
90 changed files with 3608 additions and 3299 deletions
+1
View File
@@ -21,3 +21,4 @@ cmd/migrate/migration/version-local/*
# go sum
go.sum
config/settings.deva.yml
+117 -90
View File
@@ -23,6 +23,10 @@
- GORM-based database storage that can expand many types of databases
- Simple model mapping of configuration files to quickly get the desired configuration
- Form builder
- Multi command mode
- TODO: unit test
@@ -39,102 +43,90 @@
8. Operation log: system normal operation log record and query; system exception information log record and query.
9. Login log: The system login log record query contains login exceptions.
10. System interface: Automatically generate related api interface documents according to business code.
11. Multi command mode code generation: according to the data table structure to generate the corresponding business, all visual programming, basic business can be 0 code.
12. Form construction: Customize page style, drag and drop to achieve page layout.
13. Service monitoring: view the basic information of some servers.
## Configuration details
## 🗞 System architecture
1. Configuration file description
```yml
settings:
application:
# Project launch environment
env: dev
# When env: demo, prompts for request operations other than GET
envmsg: "谢谢您的参与,但为了大家更好的体验,所以本次提交就算了吧!"
# Host IP or domain name, default 0.0.0.0
host: 0.0.0.0
# Whether to initialize the database structure and basic data; true: required; false: not required
isinit: false
# JWT encrypted string
jwtsecret: 123abc
# log storage path
logpath: temp/logs/log.log
# application name
name: go-admin
# application port
port: 8000
readtimeout: 1
writertimeout: 2
database:
# database name
database: dbname
# database type
dbtype: mysql
# database host
host: 127.0.0.1
# database password
password: password
# database port
port: 3306
# database username
username: root
redis:
# redis addresss
addr: 0.0.0.0:6379
# db
db: 0
# password
password: password
# read timeout
readtimeout: 50
```
<p align="center">
<img src="https://gitee.com/mydearzwj/image/raw/d9f59ea603e3c8a3977491a1bfa8f122e1a80824/img/go-admin-system.png" width="936px" height="491px">
</p>
2. file path go-admin/config/settings.yml
## 📦 Local development
## 📦 evelopment
First start instructions
### Create development directory
```bash
# Get the code
git clone https://github.com/wenjianzhang/go-admin.git
mkdir goadmin
cd goadmin
```
# Enter working path
### Get code
> Key points: two projects must be placed in the same folder;
```bash
# Get backend code
git clone https://github.com/go-admin-team/go-admin.git
# Get front end code
git clone https://github.com/go-admin-team/go-admin-ui.git
```
### Start up instructions
#### Server startup instructions
```bash
# Enter the go-admin backend project
cd ./go-admin
# Build the project
# Compile project
go build
# Change setting
vi ./config/setting.yml (Note: Change isinit and database connection)
# Configuration
# file path go-admin/config/settings.yml
vi ./config/setting.yml
# 1. Database information in the configuration file
# Note: the corresponding configuration data under settings.database
# 2. Confirm database initialization parameters
# Note: If this is the first time settings.application.isinit is set, please set the current value to true, the system will automatically initialize the database structure and basic data information;
# 3. Confirm the log path
# 1. Modifying database information in configuration file
# settings.database Corresponding configuration data under
# 2. Confirm log path
```
#### Initialize the database and start the service
```
# The first configuration needs to initialize the database resource information
./go-admin migrate -c config/settings.yml
# Start the project or debug with the IDE
./go-admin
# Start the project, you can also debug with IDE
./go-admin server -c config/settings.yml
```
#### Using docker to compile and start
```shell
# Compile image
docker build -t go-admin .
# Start the container. The first go admin is the container name and the second go admin is the image name
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin
# See also instructions in WIKI
```
Document generation
#### Document generation
```bash
swag init
go generate
```
If there is no `swag` command go get installed
```bash
go get -u github.com/swaggo/swag/cmd/swag
```
Cross compilation
#### Cross compiling
```bash
env GOOS=windows GOARCH=amd64 go build main.go
@@ -143,11 +135,56 @@ env GOOS=windows GOARCH=amd64 go build main.go
env GOOS=linux GOARCH=amd64 go build main.go
```
### UI interactive terminal startup description
## 🔗 Online Demo
```bash
# Installation dependency
npm install
# It is recommended that you do not use cnpm to install dependencies directly. There will be all kinds of weird bugs. The problem of slow download speed of NPM can be solved by the following operations
npm install --registry=https://registry.npm.taobao.org
# Start the service
npm run dev
```
## 🎬 Online Demo
> admin / 123456
Demo address:[http://www.zhangwj.com](http://www.zhangwj.com/#/login)
Demo:[http://www.go-admin.dev](http://www.go-admin.dev/#/login)
## 📨 Interaction
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq.png" width="200px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
</tr>
<tr>
<td>WeChat</td>
<td>This QQ group is full</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
</tr>
</table>
## 💎 Member
<a href="https://github.com/wenjianzhang"> <img src="https://avatars.githubusercontent.com/u/3890175?s=460&u=20eac63daef81588fbac611da676b99859319251&v=4" width="80px"></a>
<a href="https://github.com/lwnmengjing"> <img src="https://avatars.githubusercontent.com/u/12806223?s=400&u=a89272dce50100b77b4c0d5c81c718bf78ebb580&v=4" width="80px"></a>
<a href="https://github.com/chengxiao"> <img src="https://avatars.githubusercontent.com/u/1379545?s=460&u=557da5503d0ac4a8628df6b4075b17853d5edcd9&v=4" width="80px"></a>
<a href="https://github.com/bing127"> <img src="https://avatars.githubusercontent.com/u/31166183?s=460&u=c085bff88df10bb7676c8c0351ba9dcd031d1fb3&v=4" width="80px"></a>
## JetBrains Open source certificate support
The go admin project has always been developed in the GoLand integrated development environment of JetBrains company, based on the * * free JetBrains open source license (s) * * genuine free license. I would like to express my thanks.
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
## 🤝 Open source projects used
@@ -169,20 +206,10 @@ Demo address:[http://www.zhangwj.com](http://www.zhangwj.com/#/login)
## Version
#### 2020-03-15 New Features and Optimization
1. Add user avatar upload
2. Add user password modification
3. Operation log page adjustment
4. Optimize captcha background color
I saw a lot of friends who experience the wrong verification code, so I adjusted the contrast for everyone to experience!
## 🤝 Thanks
[chengxiao](https://github.com/chengxiao)
2. [chengxiao](https://github.com/chengxiao)
## License
@@ -191,4 +218,4 @@ I saw a lot of friends who experience the wrong verification code, so I adjusted
Copyright (c) 2020 wenjianzhang
[中文]qq technical exchange group: 74520518
[中文]qq technical exchange group: 74520518
+4 -6
View File
@@ -163,7 +163,7 @@ vi ./config/setting.yml
# 启动项目,也可以用IDE进行调试
./go-admin server -c config/settings.yml -p 8000
./go-admin server -c config/settings.yml
```
@@ -174,7 +174,8 @@ vi ./config/setting.yml
docker build -t go-admin .
# 启动容器,第一个go-admin是容器名字,第二个go-admin是镜像名称
docker run --name go-admin -p 8000:8000 -d go-admin
# -v 映射配置文件 本地路径:容器路径
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
```
@@ -182,10 +183,7 @@ docker run --name go-admin -p 8000:8000 -d go-admin
#### 文档生成
```bash
swag init
# 如果没有swag命令 go get安装一下即可
go get -u github.com/swaggo/swag/cmd/swag
go generate
```
#### 交叉编译
+10 -4
View File
@@ -5,10 +5,12 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"go-admin/common/apis"
)
const (
@@ -18,12 +20,16 @@ const (
GB = 1024 * MB
)
type Monitor struct {
apis.Api
}
// @Summary 系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/settings/serverInfo [get]
func ServerInfo(c *gin.Context) {
func (e *Monitor) ServerInfo(c *gin.Context) {
osDic := make(map[string]interface{}, 0)
osDic["goOs"] = runtime.GOOS
@@ -59,7 +65,7 @@ func ServerInfo(c *gin.Context) {
cpuDic["Percent"] = pkg.Round(percent[0], 2)
cpuDic["cpuNum"], _ = cpu.Counts(false)
app.Custum(c, gin.H{
e.Custom(c, gin.H{
"code": 200,
"os": osDic,
"mem": memDic,
+23 -18
View File
@@ -9,10 +9,10 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"github.com/go-admin-team/go-admin-core/sdk/pkg/utils"
"github.com/google/uuid"
"go-admin/common/apis"
"go-admin/common/file_store"
)
@@ -24,6 +24,10 @@ type FileResponse struct {
Type string `json:"type"`
}
type File struct {
apis.Api
}
// @Summary 上传图片
// @Description 获取JSON
// @Tags 公共接口
@@ -33,35 +37,36 @@ type FileResponse struct {
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/public/uploadFile [post]
func UploadFile(c *gin.Context) {
func (e *File) UploadFile(c *gin.Context) {
tag, _ := c.GetPostForm("type")
urlPerfix := fmt.Sprintf("http://%s/", c.Request.Host)
var fileResponse FileResponse
if tag == "" {
app.Error(c, 200, errors.New(""), "缺少标识")
e.Error(c, 500, nil, "缺少标识")
//app.Error(c, 200, errors.New(""), "缺少标识")
return
} else {
switch tag {
case "1": // 单图
var done bool
fileResponse, done = singleFile(c, fileResponse, urlPerfix)
fileResponse, done = e.singleFile(c, fileResponse, urlPerfix)
if done {
return
}
app.OK(c, fileResponse, "上传成功")
e.OK(c, fileResponse, "上传成功")
return
case "2": // 多图
multipartFile := multipleFile(c, urlPerfix)
app.OK(c, multipartFile, "上传成功")
multipartFile := e.multipleFile(c, urlPerfix)
e.OK(c, multipartFile, "上传成功")
return
case "3": // base64
fileResponse = baseImg(c, fileResponse, urlPerfix)
app.OK(c, fileResponse, "上传成功")
fileResponse = e.baseImg(c, fileResponse, urlPerfix)
e.OK(c, fileResponse, "上传成功")
}
}
}
func baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileResponse {
func (e *File) baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileResponse {
files, _ := c.GetPostForm("file")
file2list := strings.Split(files, ",")
ddd, _ := base64.StdEncoding.DecodeString(file2list[1])
@@ -80,7 +85,7 @@ func baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileRe
source, _ := c.GetPostForm("source")
err := thirdUpload(source, fileName, base64File)
if err != nil {
app.Error(c, 200, errors.New(""), "上传第三方失败")
e.Error(c, 200, errors.New(""), "上传第三方失败")
return fileResponse
}
if source != "1" {
@@ -90,7 +95,7 @@ func baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileRe
return fileResponse
}
func multipleFile(c *gin.Context, urlPerfix string) []FileResponse {
func (e *File) multipleFile(c *gin.Context, urlPerfix string) []FileResponse {
files := c.Request.MultipartForm.File["file"]
source, _ := c.GetPostForm("source")
var multipartFile []FileResponse
@@ -98,12 +103,12 @@ func multipleFile(c *gin.Context, urlPerfix string) []FileResponse {
guid := uuid.New().String()
fileName := guid + utils.GetExt(f.Filename)
multipartFileName := "static/uploadfile/" + fileName
e := c.SaveUploadedFile(f, multipartFileName)
err1 := c.SaveUploadedFile(f, multipartFileName)
fileType, _ := utils.GetType(multipartFileName)
if e == nil {
if err1 == nil {
err := thirdUpload(source, fileName, multipartFileName)
if err != nil {
app.Error(c, 200, errors.New(""), "上传第三方失败")
e.Error(c, 500, errors.New(""), "上传第三方失败")
} else {
fileResponse := FileResponse{
Size: pkg.GetFileSize(multipartFileName),
@@ -123,11 +128,11 @@ func multipleFile(c *gin.Context, urlPerfix string) []FileResponse {
return multipartFile
}
func singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (FileResponse, bool) {
func (e *File) singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (FileResponse, bool) {
files, err := c.FormFile("file")
if err != nil {
app.Error(c, 200, errors.New(""), "图片不能为空")
e.Error(c, 200, errors.New(""), "图片不能为空")
return FileResponse{}, true
}
// 上传文件至指定目录
@@ -147,7 +152,7 @@ func singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (Fi
source, _ := c.GetPostForm("source")
err = thirdUpload(source, fileName, singleFile)
if err != nil {
app.Error(c, 200, errors.New(""), "上传第三方失败")
e.Error(c, 200, errors.New(""), "上传第三方失败")
return FileResponse{}, true
}
fileResponse.Path = "https://youshikeji.oss-cn-shanghai.aliyuncs.com/img/" + fileName
+2 -4
View File
@@ -5,8 +5,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/service"
"go-admin/common/apis"
"go-admin/common/dto"
@@ -41,7 +39,7 @@ func (e *SysJob) RemoveJobForService(c *gin.Context) {
e.Error(c, http.StatusInternalServerError, err, "")
return
}
app.OK(c, nil, s.Msg)
e.OK(c, nil, s.Msg)
}
// StartJobForService 启动job service实现
@@ -69,5 +67,5 @@ func (e *SysJob) StartJobForService(c *gin.Context) {
e.Error(c, http.StatusInternalServerError, err, "")
return
}
app.OK(c, nil, s.Msg)
e.OK(c, nil, s.Msg)
}
+8 -10
View File
@@ -5,6 +5,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"github.com/google/uuid"
"go-admin/app/admin/models"
@@ -68,7 +69,7 @@ func (e *SysUser) GetSysUserList(c *gin.Context) {
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser/{userId} [get]
// @Security Bearer
func (e *SysUser) GetSysUser(c *gin.Context) {
@@ -109,7 +110,7 @@ func (e *SysUser) GetSysUser(c *gin.Context) {
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body models.SysUser true "用户数据"
// @Param data body dto.SysUserControl true "用户数据"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/sysUser [post]
@@ -156,7 +157,7 @@ func (e *SysUser) InsertSysUser(c *gin.Context) {
// @Tags 用户
// @Accept application/json
// @Product application/json
// @Param data body models.SysUser true "body"
// @Param data body dto.SysUserControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/sysuser/{userId} [put]
@@ -303,7 +304,7 @@ func (e *SysUser) InsetSysUserAvatar(c *gin.Context) {
// @Accept application/json
// @Product application/json
// @Param data body dto.PassWord true "body"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/pwd [post]
// @Security Bearer
func (e *SysUser) SysUserUpdatePwd(c *gin.Context) {
@@ -325,16 +326,13 @@ func (e *SysUser) SysUserUpdatePwd(c *gin.Context) {
// 数据权限检查
p := actions.GetPermissionFromContext(c)
object := &system.SysUser{
UserId: p.UserId,
Password: pwd.Password,
}
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.UpdateSysUser(object, p)
err = serviceSysUser.UpdateSysUserPwd(user.GetUserId(c), pwd.OldPassword, pwd.NewPassword, p)
if err != nil {
log.Error(err)
e.Error(c, http.StatusForbidden, err, "密码修改失败")
return
}
e.OK(c, nil, "密码修改成功")
@@ -343,7 +341,7 @@ func (e *SysUser) SysUserUpdatePwd(c *gin.Context) {
// @Summary 获取个人中心用户
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/profile [get]
// @Security Bearer
func (e *SysUser) GetSysUserProfile(c *gin.Context) {
+13 -5
View File
@@ -2,15 +2,23 @@ package system
import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/captcha"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/common/apis"
)
func GenerateCaptchaHandler(c *gin.Context) {
type System struct {
apis.Api
}
func (e *System) GenerateCaptchaHandler(c *gin.Context) {
log := e.GetLogger(c)
id, b64s, err := captcha.DriverDigitFunc()
pkg.HasError(err, "验证码获取失败", 500)
app.Custum(c, gin.H{
if err != nil {
log.Errorf("DriverDigitFunc error, %s", err.Error())
e.Error(c, 500, err, "验证码获取失败")
return
}
e.Custom(c, gin.H{
"code": 200,
"data": b64s,
"id": id,
+5 -4
View File
@@ -5,6 +5,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
@@ -25,7 +26,7 @@ type SysDictData struct {
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data [get]
// @Security Bearer
func (e *SysDictData) GetSysDictDataList(c *gin.Context) {
@@ -65,7 +66,7 @@ func (e *SysDictData) GetSysDictDataList(c *gin.Context) {
// @Description 获取JSON
// @Tags 字典数据
// @Param dictCode path int true "字典编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data/{dictCode} [get]
// @Security Bearer
func (e *SysDictData) GetSysDictData(c *gin.Context) {
@@ -104,7 +105,7 @@ func (e *SysDictData) GetSysDictData(c *gin.Context) {
// @Tags 字典数据
// @Accept application/json
// @Product application/json
// @Param data body system.DictType true "data"
// @Param data body dto.SysDictDataControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/data [post]
@@ -147,7 +148,7 @@ func (e *SysDictData) InsertSysDictData(c *gin.Context) {
// @Tags 字典数据
// @Accept application/json
// @Product application/json
// @Param data body models.DictType true "body"
// @Param data body dto.SysDictDataControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/data/{dictCode} [put]
+6 -5
View File
@@ -5,6 +5,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
@@ -25,7 +26,7 @@ type SysDictType struct {
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type [get]
// @Security Bearer
func (e *SysDictType) GetSysDictTypeList(c *gin.Context) {
@@ -63,7 +64,7 @@ func (e *SysDictType) GetSysDictTypeList(c *gin.Context) {
// @Description 获取JSON
// @Tags 字典类型
// @Param dictId path int true "字典类型编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type/{dictId} [get]
// @Security Bearer
func (e *SysDictType) GetSysDictType(c *gin.Context) {
@@ -100,7 +101,7 @@ func (e *SysDictType) GetSysDictType(c *gin.Context) {
// @Tags 字典类型
// @Accept application/json
// @Product application/json
// @Param data body models.DictType true "data"
// @Param data body dto.SysDictTypeControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/type [post]
@@ -142,7 +143,7 @@ func (e *SysDictType) InsertSysDictType(c *gin.Context) {
// @Tags 字典类型
// @Accept application/json
// @Product application/json
// @Param data body models.DictType true "body"
// @Param data body dto.SysDictTypeControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/type/{dictId} [put]
@@ -226,7 +227,7 @@ func (e *SysDictType) DeleteSysDictType(c *gin.Context) {
// @Param dictName query string false "dictName"
// @Param dictId query string false "dictId"
// @Param dictType query string false "dictType"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type-option-select [get]
// @Security Bearer
func (e *SysDictType) GetSysDictTypeAll(c *gin.Context) {
+1 -1
View File
@@ -28,7 +28,7 @@ $(function(){
</script>
</head>
<body>
<iframe id="iframe" frameborder="0" src="http://doc.zhangwj.com/go-admin-site/" style="width:100%;"></iframe>
<iframe id="iframe" frameborder="0" src="https://doc.go-admin.dev" style="width:100%;"></iframe>
</body>
</html>
`
+4 -4
View File
@@ -16,7 +16,7 @@ import (
// var Rm models.RoleMenu
// err := c.ShouldBind(&Rm)
// result, err := Rm.Get()
// var res app.Response
// var res response.Response
// if err != nil {
// res.Msg = "抱歉未找到相关信息"
// c.JSON(http.StatusOK, res.ReturnError(200))
@@ -33,7 +33,7 @@ type RoleMenuPost struct {
//func InsertRoleMenu(c *gin.Context) {
//
// var res app.Response
// var res response.Response
// res.Msg = "添加成功"
// c.JSON(http.StatusOK, res.ReturnOK())
// return
@@ -55,12 +55,12 @@ type RoleMenuPost struct {
// fmt.Println(menuId)
// _, err := t.Delete(id, menuId)
// if err != nil {
// var res app.Response
// var res response.Response
// res.Msg = "删除失败"
// c.JSON(http.StatusOK, res.ReturnError(200))
// return
// }
// var res app.Response
// var res response.Response
// res.Msg = "删除成功"
// c.JSON(http.StatusOK, res.ReturnOK())
// return
+1 -1
View File
@@ -53,7 +53,7 @@ func (e *SysSetting) GetSetting(c *gin.Context) {
// @Summary 更新或提交系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Param data body models.SysUser true "body"
// @Param data body dto.SysSettingControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/system/setting [post]
+55 -17
View File
@@ -5,7 +5,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
@@ -30,7 +29,7 @@ func (e *SysConfig) GetSysConfigList(c *gin.Context) {
err = d.Bind(c)
if err != nil {
log.Errorf("参数验证失败, error:%s", err)
app.Error(c, 500, err, "参数验证失败")
e.Error(c, 500, err, "参数验证失败")
return
}
@@ -42,12 +41,51 @@ func (e *SysConfig) GetSysConfigList(c *gin.Context) {
err = s.GetSysConfigPage(d, &list, &count)
if err != nil {
log.Errorf("GetSysConfigPage 查询失败, error:%s", err)
app.Error(c, 500, err, "查询失败")
e.Error(c, 500, err, "查询失败")
return
}
e.PageOK(c, list, int(count), d.GetPageIndex(), d.GetPageSize(), "查询成功")
}
// GetSysConfigBySysApp 获取系统配置信息,主要注意这里不在验证数据权限
func (e *SysConfig) GetSysConfigBySysApp(c *gin.Context) {
log := e.GetLogger(c)
d := new(dto.SysConfigSearch)
db, err := e.GetOrm(c)
if err != nil {
log.Error(err)
return
}
err = d.Bind(c)
if err != nil {
log.Errorf("参数验证失败, error:%s", err)
e.Error(c, 500, err, "参数验证失败")
return
}
// 控制只读前台的数据
d.IsFrontend = 1
list := make([]system.SysConfig, 0)
s := service.SysConfig{}
s.Log = log
s.Orm = db
err = s.GetSysConfigByKey(d, &list)
if err != nil {
log.Errorf("GetSysConfigPage 查询失败, error:%s", err)
e.Error(c, 500, err, "查询失败")
return
}
mp := make(map[string]string)
for i := 0; i < len(list); i++ {
key := list[i].ConfigKey
if key != "" {
mp[key] = list[i].ConfigValue
}
}
e.OK(c, mp, "查询成功")
}
func (e *SysConfig) GetSysConfig(c *gin.Context) {
log := e.GetLogger(c)
control := new(dto.SysConfigById)
@@ -61,7 +99,7 @@ func (e *SysConfig) GetSysConfig(c *gin.Context) {
if err != nil {
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
var object system.SysConfig
@@ -73,7 +111,7 @@ func (e *SysConfig) GetSysConfig(c *gin.Context) {
if err != nil {
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
@@ -94,14 +132,14 @@ func (e *SysConfig) InsertSysConfig(c *gin.Context) {
if err != nil {
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
// 设置创建人
@@ -115,7 +153,7 @@ func (e *SysConfig) InsertSysConfig(c *gin.Context) {
log.Error(err)
e.Error(c, http.StatusInternalServerError, err, "创建失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
@@ -137,14 +175,14 @@ func (e *SysConfig) UpdateSysConfig(c *gin.Context) {
if err != nil {
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
object, err := control.Generate()
if err != nil {
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
@@ -156,7 +194,7 @@ func (e *SysConfig) UpdateSysConfig(c *gin.Context) {
if err != nil {
e.Error(c, http.StatusUnprocessableEntity, err, "更新失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
e.OK(c, object.GetId(), "更新成功")
@@ -177,14 +215,14 @@ func (e *SysConfig) DeleteSysConfig(c *gin.Context) {
log.Errorf("Bind error: %s", err)
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
object, err := control.GenerateM()
if err != nil {
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
@@ -198,7 +236,7 @@ func (e *SysConfig) DeleteSysConfig(c *gin.Context) {
if err != nil {
e.Error(c, http.StatusUnprocessableEntity, err, "删除失败")
log.Errorf("Orm获取失败, error:%s", err)
app.Error(c, 500, err, "Orm获取失败")
e.Error(c, 500, err, "Orm获取失败")
return
}
e.OK(c, object.GetId(), "删除成功")
@@ -216,7 +254,7 @@ func (e *SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
err = v.Bind(c)
if err != nil {
log.Errorf("参数验证错误, error:%s", err)
app.Error(c, 422, err, "参数验证失败")
e.Error(c, 422, err, "参数验证失败")
return
}
s := service.SysConfig{}
@@ -225,8 +263,8 @@ func (e *SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
err = s.GetSysConfigByKEY(&v)
if err != nil {
log.Errorf("通过Key获取配置失败, error:%s", err)
app.Error(c, 500, err, "")
e.Error(c, 500, err, "")
return
}
app.OK(c, v, s.Msg)
e.OK(c, v, s.Msg)
}
+37 -32
View File
@@ -1,10 +1,12 @@
package sys_dept
import (
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
@@ -22,7 +24,7 @@ type SysDept struct {
// @Param name query string false "name"
// @Param id query string false "id"
// @Param position query string false "position"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept [get]
// @Security Bearer
func (e *SysDept) GetSysDeptList(c *gin.Context) {
@@ -59,7 +61,7 @@ func (e *SysDept) GetSysDeptList(c *gin.Context) {
// @Tags 部门
// @Param deptId path string false "deptId"
// @Param position query string false "position"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept/{deptId} [get]
// @Security Bearer
func (e *SysDept) GetSysDept(c *gin.Context) {
@@ -96,7 +98,7 @@ func (e *SysDept) GetSysDept(c *gin.Context) {
// @Tags 部门
// @Accept application/json
// @Product application/json
// @Param data body models.SysDept true "data"
// @Param data body dto.SysDeptControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dept [post]
@@ -143,7 +145,7 @@ func (e *SysDept) InsertSysDept(c *gin.Context) {
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body models.SysDept true "body"
// @Param data body dto.SysDeptControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dept/{deptId} [put]
@@ -184,7 +186,7 @@ func (e *SysDept) UpdateSysDept(c *gin.Context) {
// @Summary 删除部门
// @Description 删除数据
// @Tags 部门
// @Param data body []int true "body"
// @Param data body dto.SysDeptById true "body"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/dept [delete]
@@ -253,30 +255,33 @@ func (e *SysDept) GetDeptTree(c *gin.Context) {
e.OK(c, list, "")
}
//func (e *SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
// log := e.GetLogger(c)
// db, err := tools.GetOrm(c)
// if err != nil {
// log.Error(err)
// return
// }
//
// s := service.SysDept{}
// s.Orm = db
// s.MsgID = msgID
// id, err := tools.StringToInt(c.Param("roleId"))
// result, err := s.SetDeptLabel()
// if err != nil {
// log.Errorf("SetDeptLabel error, %s", msgID, err.Error())
// e.Error(c, http.StatusInternalServerError, err, "")
// }
// menuIds := make([]int, 0)
// if id != 0 {
// menuIds, err = s.GetRoleDeptId(id)
// tools.HasError(err, "抱歉未找到相关信息", -1)
// }
// e.OK(c, gin.H{
// "depts": result,
// "checkedKeys": menuIds,
// }, "")
//}
func (e *SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Error(err)
return
}
s := service.SysDept{}
s.Orm = db
s.Log = log
id, err := pkg.StringToInt(c.Param("roleId"))
result, err := s.SetDeptLabel()
if err != nil {
log.Errorf("SetDeptLabel error, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "")
}
menuIds := make([]int, 0)
if id != 0 {
menuIds, err = s.GetRoleDeptId(id)
if err != nil {
log.Errorf("抱歉未找到相关信息, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "")
}
}
e.OK(c, gin.H{
"depts": result,
"checkedKeys": menuIds,
}, "")
}
+2 -2
View File
@@ -152,7 +152,7 @@ func (e *SysMenu) InsertSysMenu(c *gin.Context) {
// @Accept application/x-www-form-urlencoded
// @Product application/x-www-form-urlencoded
// @Param id path int true "id"
// @Param data body models.Menu true "body"
// @Param data body dto.SysMenuControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/menu/{id} [put]
@@ -195,7 +195,7 @@ func (e *SysMenu) UpdateSysMenu(c *gin.Context) {
// @Summary 删除菜单
// @Description 删除数据
// @Tags 菜单
// @Param data body []int true "body"
// @Param data body dto.SysMenuById true "body"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/menu/ [delete]
+5 -4
View File
@@ -5,6 +5,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
@@ -23,7 +24,7 @@ type SysPost struct {
// @Param postCode query string false "postCode"
// @Param postId query string false "postId"
// @Param status query string false "status"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post [get]
// @Security Bearer
func (e *SysPost) GetSysPostList(c *gin.Context) {
@@ -60,7 +61,7 @@ func (e *SysPost) GetSysPostList(c *gin.Context) {
// @Description 获取JSON
// @Tags 岗位
// @Param postId path int true "postId"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post/{postId} [get]
// @Security Bearer
func (e *SysPost) GetSysPost(c *gin.Context) {
@@ -97,7 +98,7 @@ func (e *SysPost) GetSysPost(c *gin.Context) {
// @Tags 岗位
// @Accept application/json
// @Product application/json
// @Param data body models.Post true "data"
// @Param data body dto.SysPostControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/post [post]
@@ -143,7 +144,7 @@ func (e *SysPost) InsertSysPost(c *gin.Context) {
// @Tags 岗位
// @Accept application/json
// @Product application/json
// @Param data body models.Post true "body"
// @Param data body dto.SysPostControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/post/ [put]
+4 -3
View File
@@ -5,6 +5,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
@@ -25,7 +26,7 @@ type SysRole struct {
// @Param roleKey query string false "roleKey"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/role [get]
// @Security Bearer
func (e *SysRole) GetSysRoleList(c *gin.Context) {
@@ -100,7 +101,7 @@ func (e *SysRole) GetSysRole(c *gin.Context) {
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body models.SysRole true "data"
// @Param data body dto.SysRoleControl true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/role [post]
@@ -153,7 +154,7 @@ func (e *SysRole) InsertSysRole(c *gin.Context) {
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body models.SysRole true "body"
// @Param data body dto.SysRoleControl true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/role/{id} [put]
+11 -18
View File
@@ -5,10 +5,9 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/tools"
"go-admin/common/apis"
)
// @Summary 分页列表数据 / page list data
@@ -17,10 +16,10 @@ import (
// @Param tableName query string false "tableName / 数据表名称"
// @Param pageSize query int false "pageSize / 页条数"
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/db/columns/page [get]
func GetDBColumnList(c *gin.Context) {
log := apis.GetRequestLogger(c)
func (e *Gen) GetDBColumnList(c *gin.Context) {
log := e.GetLogger(c)
var data tools.DBColumns
var err error
var pageSize = 10
@@ -37,23 +36,17 @@ func GetDBColumnList(c *gin.Context) {
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
data.TableName = c.Request.FormValue("tableName")
pkg.Assert(data.TableName == "", "table name cannot be empty!", 500)
result, count, err := data.GetPage(db, pageSize, pageIndex)
pkg.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
mp["count"] = count
mp["pageIndex"] = pageIndex
mp["pageSize"] = pageSize
var res app.Response
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
if err != nil {
log.Errorf("GetPage error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
e.PageOK(c, result, count, pageIndex, pageSize, "查询成功")
}
+17 -20
View File
@@ -1,15 +1,15 @@
package tools
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models/tools"
"go-admin/common/apis"
)
// @Summary 分页列表数据 / page list data
@@ -18,18 +18,20 @@ import (
// @Param tableName query string false "tableName / 数据表名称"
// @Param pageSize query int false "pageSize / 页条数"
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/db/tables/page [get]
func GetDBTableList(c *gin.Context) {
var res app.Response
func (e *Gen) GetDBTableList(c *gin.Context) {
//var res response.Response
var data tools.DBTables
var err error
var pageSize = 10
var pageIndex = 1
log := apis.GetRequestLogger(c)
log := e.GetLogger(c)
if config.DatabaseConfig.Driver == "sqlite3" || config.DatabaseConfig.Driver == "postgres" {
res.Msg = "对不起,sqlite3 或 postgres 不支持代码生成!"
c.JSON(http.StatusOK, res.ReturnError(500))
err = errors.New("对不起,sqlite3 或 postgres 不支持代码生成!")
log.Warn(err)
e.Error(c, 403, err, "")
//c.JSON(http.StatusOK, res.ReturnError(500))
return
}
@@ -44,21 +46,16 @@ func GetDBTableList(c *gin.Context) {
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
data.TableName = c.Request.FormValue("tableName")
result, count, err := data.GetPage(db, pageSize, pageIndex)
pkg.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
mp["count"] = count
mp["pageIndex"] = pageIndex
mp["pageSize"] = pageSize
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
if err != nil {
log.Errorf("GetPage error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
e.PageOK(c, result, count, pageIndex, pageSize, "查询成功")
}
+177 -42
View File
@@ -3,43 +3,81 @@ package tools
import (
"bytes"
"net/http"
"strconv"
"text/template"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models"
"go-admin/app/admin/models/tools"
"go-admin/common/apis"
)
func Preview(c *gin.Context) {
log := apis.GetRequestLogger(c)
type Gen struct {
apis.Api
}
func (e *Gen) Preview(c *gin.Context) {
log := e.GetLogger(c)
table := tools.SysTables{}
id, err := pkg.StringToInt(c.Param("tableId"))
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
table.TableId = id
t1, err := template.ParseFiles("template/v4/model.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t2, err := template.ParseFiles("template/v4/no_actions/apis.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t3, err := template.ParseFiles("template/v4/js.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t4, err := template.ParseFiles("template/v4/vue.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t5, err := template.ParseFiles("template/v4/no_actions/router_check_role.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t6, err := template.ParseFiles("template/v4/dto.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t7, err := template.ParseFiles("template/v4/no_actions/service.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
@@ -67,22 +105,23 @@ func Preview(c *gin.Context) {
mp["template/router.go.template"] = b5.String()
mp["template/dto.go.template"] = b6.String()
mp["template/service.go.template"] = b7.String()
var res app.Response
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
e.OK(c, mp, "")
}
func GenCodeV3(c *gin.Context) {
log := apis.GetRequestLogger(c)
func (e *Gen) GenCodeV3(c *gin.Context) {
log := e.GetLogger(c)
table := tools.SysTables{}
id, err := pkg.StringToInt(c.Param("tableId"))
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
@@ -90,15 +129,40 @@ func GenCodeV3(c *gin.Context) {
tab, _ := table.Get(db)
if tab.IsActions == 1 {
ActionsGenV3(tab)
e.ActionsGenV3(c, tab)
} else {
NOActionsGenV3(tab)
e.NOActionsGenV3(c, tab)
}
app.OK(c, "", "Code generated successfully!")
e.OK(c, "", "Code generated successfully!")
}
func NOActionsGenV3(tab tools.SysTables) {
func (e *Gen) GenApiToFile(c *gin.Context) {
log := e.GetLogger(c)
table := tools.SysTables{}
id, err := pkg.StringToInt(c.Param("tableId"))
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
table.TableId = id
tab, _ := table.Get(db)
e.genApiToFile(c, tab)
e.OK(c, "", "Code generated successfully!")
}
func (e *Gen) NOActionsGenV3(c *gin.Context, tab tools.SysTables) {
log := e.GetLogger(c)
basePath := "template/v4/"
routerFile := basePath + "no_actions/router_check_role.go.template"
@@ -108,19 +172,47 @@ func NOActionsGenV3(tab tools.SysTables) {
}
t1, err := template.ParseFiles(basePath + "model.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t3, err := template.ParseFiles(routerFile)
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t4, err := template.ParseFiles(basePath + "js.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t5, err := template.ParseFiles(basePath + "vue.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t6, err := template.ParseFiles(basePath + "dto.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t7, err := template.ParseFiles(basePath + "no_actions/service.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
_ = pkg.PathCreate("./app/" + tab.PackageName + "/apis/" + tab.ModuleName)
_ = pkg.PathCreate("./app/" + tab.PackageName + "/models/")
@@ -153,7 +245,30 @@ func NOActionsGenV3(tab tools.SysTables) {
}
func ActionsGenV3(tab tools.SysTables) {
func (e *Gen) genApiToFile(c *gin.Context, tab tools.SysTables) {
log := e.GetLogger(c)
basePath := "template/"
t1, err := template.ParseFiles(basePath + "api_migrate.template")
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
i := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
var b1 bytes.Buffer
err = t1.Execute(&b1, struct {
tools.SysTables
GenerateTime string
}{tab, i})
pkg.FileCreate(b1, "./cmd/migrate/migration/version/"+i+"_migrate.go")
}
func (e *Gen) ActionsGenV3(c *gin.Context, tab tools.SysTables) {
log := api.GetRequestLogger(c)
basePath := "template/v4/"
routerFile := basePath + "actions/router_check_role.go.template"
@@ -162,15 +277,35 @@ func ActionsGenV3(tab tools.SysTables) {
}
t1, err := template.ParseFiles(basePath + "model.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t3, err := template.ParseFiles(routerFile)
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t4, err := template.ParseFiles(basePath + "js.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t5, err := template.ParseFiles(basePath + "vue.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
t6, err := template.ParseFiles(basePath + "dto.go.template")
pkg.HasError(err, "", -1)
if err != nil {
log.Error(err)
e.Error(c, 500, err, "")
return
}
_ = pkg.PathCreate("./app/" + tab.PackageName + "/models/")
_ = pkg.PathCreate("./app/" + tab.PackageName + "/router/")
@@ -196,8 +331,8 @@ func ActionsGenV3(tab tools.SysTables) {
pkg.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go")
}
func GenMenuAndApi(c *gin.Context) {
log := apis.GetRequestLogger(c)
func (e *Gen) GenMenuAndApi(c *gin.Context) {
log := api.GetRequestLogger(c)
table := tools.SysTables{}
timeNow := pkg.GetCurrentTime()
@@ -207,7 +342,7 @@ func GenMenuAndApi(c *gin.Context) {
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
@@ -437,5 +572,5 @@ func GenMenuAndApi(c *gin.Context) {
ADelete.UpdatedAt = timeNow
ADelete.MenuId, err = ADelete.Create(db)
app.OK(c, "", "数据生成成功!")
}
e.OK(c, "", "数据生成成功!")
}
+87 -71
View File
@@ -7,23 +7,27 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"gorm.io/gorm"
"go-admin/app/admin/models/tools"
"go-admin/common/apis"
)
type SysTable struct {
apis.Api
}
// @Summary 分页列表数据
// @Description 生成表分页列表
// @Tags 工具 - 生成表
// @Param tableName query string false "tableName / 数据表名称"
// @Param pageSize query int false "pageSize / 页条数"
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys/tables/page [get]
func GetSysTableList(c *gin.Context) {
log := apis.GetRequestLogger(c)
func (e *SysTable) GetSysTableList(c *gin.Context) {
log := e.GetLogger(c)
var data tools.SysTables
var err error
var pageSize = 10
@@ -37,66 +41,61 @@ func GetSysTableList(c *gin.Context) {
pageIndex, err = pkg.StringToInt(index)
}
db, err := pkg.GetOrm(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
data.TBName = c.Request.FormValue("tableName")
data.TableComment = c.Request.FormValue("tableComment")
result, count, err := data.GetPage(db, pageSize, pageIndex)
pkg.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
mp["count"] = count
mp["pageIndex"] = pageIndex
mp["pageSize"] = pageSize
var res app.Response
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
if err != nil {
log.Errorf("GetPage error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
e.PageOK(c, result, count, pageIndex, pageSize, "查询成功")
}
// @Summary 获取配置
// @Description 获取JSON
// @Tags 工具 - 生成表
// @Param configKey path int true "configKey"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys/tables/info/{tableId} [get]
// @Security Bearer
func GetSysTables(c *gin.Context) {
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
func (e *SysTable) GetSysTables(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
var data tools.SysTables
data.TableId, _ = pkg.StringToInt(c.Param("tableId"))
result, err := data.Get(db)
pkg.HasError(err, "抱歉未找到相关信息", -1)
if err != nil {
log.Errorf("Get error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
var res app.Response
res.Data = result
mp := make(map[string]interface{})
mp["list"] = result.Columns
mp["info"] = result
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
e.OK(c, mp, "")
}
func GetSysTablesInfo(c *gin.Context) {
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
func (e *SysTable) GetSysTablesInfo(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
@@ -105,33 +104,38 @@ func GetSysTablesInfo(c *gin.Context) {
data.TBName = c.Request.FormValue("tableName")
}
result, err := data.Get(db)
pkg.HasError(err, "抱歉未找到相关信息", -1)
if err != nil {
log.Errorf("Get error, %s", err.Error())
e.Error(c, 500, err, "抱歉未找到相关信息")
return
}
var res app.Response
res.Data = result
mp := make(map[string]interface{})
mp["list"] = result.Columns
mp["info"] = result
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
e.OK(c, mp, "")
//res.Data = mp
//c.JSON(http.StatusOK, res.ReturnOK())
}
func GetSysTablesTree(c *gin.Context) {
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
func (e *SysTable) GetSysTablesTree(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
var data tools.SysTables
result, err := data.GetTree(db)
pkg.HasError(err, "抱歉未找到相关信息", -1)
if err != nil {
log.Errorf("GetTree error, %s", err.Error())
e.Error(c, 500, err, "抱歉未找到相关信息")
return
}
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
e.OK(c, result, "")
}
// @Summary 添加表结构
@@ -144,12 +148,12 @@ func GetSysTablesTree(c *gin.Context) {
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/sys/tables/info [post]
// @Security Bearer
func InsertSysTable(c *gin.Context) {
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
func (e *SysTable) InsertSysTable(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
@@ -157,13 +161,20 @@ func InsertSysTable(c *gin.Context) {
for i := 0; i < len(tablesList); i++ {
data, err := genTableInit(db, tablesList, i, c)
if err != nil {
log.Errorf("genTableInit error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
_, err = data.Create(db)
pkg.HasError(err, "", -1)
if err != nil {
log.Errorf("Create error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
}
var res app.Response
res.Msg = "添加成功!"
c.JSON(http.StatusOK, res.ReturnOK())
e.OK(c, nil, "添加成功")
}
@@ -176,6 +187,9 @@ func genTableInit(tx *gorm.DB, tablesList []string, i int, c *gin.Context) (tool
dbTable.TableName = data.TBName
dbtable, err := dbTable.Get(tx)
if err != nil {
return data, err
}
dbColumn.TableName = data.TBName
tablenamelist := strings.Split(dbColumn.TableName, "_")
@@ -277,27 +291,27 @@ func genTableInit(tx *gorm.DB, tablesList []string, i int, c *gin.Context) (tool
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/sys/tables/info [put]
// @Security Bearer
func UpdateSysTable(c *gin.Context) {
func (e *SysTable) UpdateSysTable(c *gin.Context) {
var data tools.SysTables
err := c.Bind(&data)
pkg.HasError(err, "数据解析失败", 500)
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
data.UpdateBy = user.GetUserIdStr(c)
result, err := data.Update(db)
pkg.HasError(err, "", -1)
var res app.Response
res.Data = result
res.Msg = "修改成功"
c.JSON(http.StatusOK, res.ReturnOK())
if err != nil {
log.Errorf("Update error, %s", err.Error())
e.Error(c, 500, err, "")
return
}
e.OK(c, result, "修改成功")
}
// @Summary 删除表结构
@@ -307,20 +321,22 @@ func UpdateSysTable(c *gin.Context) {
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/sys/tables/info/{tableId} [delete]
func DeleteSysTables(c *gin.Context) {
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
func (e *SysTable) DeleteSysTables(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
e.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
var data tools.SysTables
IDS := pkg.IdsStrToIdsIntGroup("tableId", c)
_, err = data.BatchDelete(db, IDS)
pkg.HasError(err, "删除失败", 500)
var res app.Response
res.Msg = "删除成功"
c.JSON(http.StatusOK, res.ReturnOK())
if err != nil {
log.Errorf("BatchDelete error, %s", err.Error())
e.Error(c, 500, err, "删除失败")
return
}
e.OK(c, nil, "删除成功")
}
+3 -3
View File
@@ -8,8 +8,8 @@ type SysCategory struct {
models.Model
Name string `json:"name" gorm:"type:varchar(255);comment:名称"` //
Img string `json:"img" gorm:"type:varchar(255);comment:图标"` //
Sort string `json:"sort" gorm:"type:int(4);comment:排序"` //
Status string `json:"status" gorm:"type:int(1);comment:状态"` //
Sort int `json:"sort" gorm:"type:int(4);comment:排序"` //
Status int `json:"status" gorm:"type:int(1);comment:状态"` //
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
models.ControlBy
models.ModelTime
@@ -26,4 +26,4 @@ func (e *SysCategory) Generate() models.ActiveRecord {
func (e *SysCategory) GetId() interface{} {
return e.Id
}
}
+3 -6
View File
@@ -2,18 +2,15 @@ package models
import (
"go-admin/common/models"
"time"
)
type SysChinaAreaData struct {
models.Model
models.ControlBy
PId string `json:"pId" gorm:"type:int(11);comment:上级编码"`
Name string `json:"name" gorm:"type:varchar(128);comment:名称"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp;comment:CreateTime"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp;comment:UpdateTime"`
DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp;comment:DeleteTime"`
models.ControlBy
models.ModelTime
}
func (SysChinaAreaData) TableName() string {
@@ -27,4 +24,4 @@ func (e *SysChinaAreaData) Generate() models.ActiveRecord {
func (e *SysChinaAreaData) GetId() interface{} {
return e.Id
}
}
+7 -111
View File
@@ -5,22 +5,24 @@ import (
)
type SysContent struct {
Id int `json:"id" gorm:"type:int(11);primaryKey;autoIncrement"` // id
CateId string `json:"cateId" gorm:"type:int(11);comment:分类id"`
models.Model
CateId int `json:"cateId" gorm:"type:int(11);comment:分类id"`
Name string `json:"name" gorm:"type:varchar(255);comment:名称"`
Status string `json:"status" gorm:"type:int(1);comment:状态"`
Status int `json:"status" gorm:"type:int(1);comment:状态"`
Img string `json:"img" gorm:"type:varchar(255);comment:图片"`
Content string `json:"content" gorm:"type:text;comment:内容"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Sort string `json:"sort" gorm:"type:int(4);comment:排序"`
Sort int `json:"sort" gorm:"type:int(4);comment:排序"`
models.ControlBy
models.ModelTime
}
// TableName
func (SysContent) TableName() string {
return "sys_content"
}
// Generate
func (e *SysContent) Generate() models.ActiveRecord {
o := *e
return &o
@@ -28,110 +30,4 @@ func (e *SysContent) Generate() models.ActiveRecord {
func (e *SysContent) GetId() interface{} {
return e.Id
}
//// 创建SysContent
//func (e *SysContent) Create() (SysContent, error) {
// var doc SysContent
// result := orm.Eloquent.Table(e.TableName()).Create(&e)
// if result.Error != nil {
// err := result.Error
// return doc, err
// }
// doc = *e
// return doc, nil
//}
//
//// 获取SysContent
//func (e *SysContent) Get() (SysContent, error) {
// var doc SysContent
// table := orm.Eloquent.Table(e.TableName())
//
// if e.Id != 0 {
// table = table.Where("id = ?", e.Id)
// }
//
// if e.CateId != "" {
// table = table.Where("cate_id = ?", e.CateId)
// }
//
// if e.Name != "" {
// table = table.Where("name like ?", "%"+e.Name+"%")
// }
//
// if e.Status != "" {
// table = table.Where("status = ?", e.Status)
// }
//
// if err := table.First(&doc).Error; err != nil {
// return doc, err
// }
// return doc, nil
//}
//
//// 获取SysContent带分页
//func (e *SysContent) GetPage(pageSize int, pageIndex int) ([]SysContent, int, error) {
// var doc []SysContent
//
// table := orm.Eloquent.Table(e.TableName())
//
// if e.CateId != "" {
// table = table.Where("cate_id = ?", e.CateId)
// }
//
// if e.Name != "" {
// table = table.Where("name like ?", "%"+e.Name+"%")
// }
//
// if e.Status != "" {
// table = table.Where("status = ?", e.Status)
// }
//
// // 数据权限控制(如果不需要数据权限请将此处去掉)
// dataPermission := new(system.DataPermission)
// dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
// table, err := dataPermission.GetDataScope(e.TableName(), table)
// if err != nil {
// return nil, 0, err
// }
// var count int64
//
// if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
// return nil, 0, err
// }
// //table.Where("`deleted_at` IS NULL").Count(&count)
// return doc, int(count), nil
//}
//
//// 更新SysContent
//func (e *SysContent) Update(id int) (update SysContent, err error) {
// if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
// return
// }
//
// //参数1:是要修改的数据
// //参数2:是修改的数据
// if err = orm.Eloquent.Table(e.TableName()).Model(&update).Where("id = ?", id).Updates(&e).Error; err != nil {
// return
// }
// return
//}
//
//// 删除SysContent
//func (e *SysContent) Delete(id int) (success bool, err error) {
// if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysContent{}).Error; err != nil {
// success = false
// return
// }
// success = true
// return
//}
//
////批量删除
//func (e *SysContent) BatchDelete(id []int) (Result bool, err error) {
// if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysContent{}).Error; err != nil {
// return
// }
// Result = true
// return
//}
}
+3 -2
View File
@@ -9,8 +9,9 @@ type SysConfig struct {
ConfigName string `json:"configName" gorm:"type:varchar(128);comment:ConfigName"` //
ConfigKey string `json:"configKey" gorm:"type:varchar(128);comment:ConfigKey"` //
ConfigValue string `json:"configValue" gorm:"type:varchar(255);comment:ConfigValue"` //
ConfigType string `json:"configType" gorm:"type:varchar(64);comment:ConfigType"` //
Remark string `json:"remark" gorm:"type:varchar(128);comment:Remark"` //
ConfigType string `json:"configType" gorm:"type:varchar(64);comment:ConfigType"`
IsFrontend int `json:"isFrontend" gorm:"type:varchar(64);comment:是否前台"` //
Remark string `json:"remark" gorm:"type:varchar(128);comment:Remark"` //
models.ControlBy
models.ModelTime
}
+37 -2
View File
@@ -1,9 +1,15 @@
package system
import (
"go-admin/common/models"
"encoding/json"
"errors"
"time"
"github.com/go-admin-team/go-admin-core/cache"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"go-admin/common/models"
)
type SysLoginLog struct {
@@ -35,3 +41,32 @@ func (e *SysLoginLog) Generate() models.ActiveRecord {
func (e *SysLoginLog) GetId() interface{} {
return e.Id
}
// SaveLoginLog 从队列中获取登录日志
func SaveLoginLog(message cache.Message) (err error) {
//准备db
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
return err
}
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
log.Errorf("json Marshal error, %s", err.Error())
return err
}
var l SysLoginLog
err = json.Unmarshal(rb, &l)
if err != nil {
log.Errorf("json Unmarshal error, %s", err.Error())
return err
}
err = db.Create(&l).Error
if err != nil {
log.Errorf("db create error, %s", err.Error())
return err
}
return nil
}
+42 -2
View File
@@ -1,9 +1,15 @@
package system
import (
"go-admin/common/models"
"encoding/json"
"errors"
"time"
"github.com/go-admin-team/go-admin-core/cache"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"go-admin/common/models"
)
type SysOperaLog struct {
@@ -43,3 +49,37 @@ func (e *SysOperaLog) Generate() models.ActiveRecord {
func (e *SysOperaLog) GetId() interface{} {
return e.Id
}
// SaveOperaLog 从队列中获取操作日志
func SaveOperaLog(message cache.Message) (err error) {
//准备db
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
return err
}
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
log.Errorf("json Marshal error, %s", err.Error())
return err
}
var l SysOperaLog
err = json.Unmarshal(rb, &l)
if err != nil {
log.Errorf("json Unmarshal error, %s", err.Error())
return err
}
if l.Title == "" {
m := &SysMenu{}
db.Model(m).Select("Title").Where("action = ?", l.Method).Where("path = ?", message.GetValues()["_fullPath"]).First(m)
l.Title = m.Title
}
err = db.Create(&l).Error
if err != nil {
log.Errorf("db create error, %s", err.Error())
return err
}
return nil
}
+10 -10
View File
@@ -1,18 +1,17 @@
package router
import (
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"os"
"github.com/gin-gonic/gin"
log "github.com/go-admin-team/go-admin-core/logger"
"go-admin/app/admin/middleware"
"go-admin/app/admin/middleware/handler"
common "go-admin/common/middleware"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
common "go-admin/common/middleware"
"go-admin/common/middleware/handler"
)
// InitRouter 路由初始化,不要怀疑,这里用到了
@@ -35,10 +34,11 @@ func InitRouter() {
}
r.Use(common.Sentinel()).
Use(common.RequestId(pkg.TrafficKey))
middleware.InitMiddleware(r)
Use(common.RequestId(pkg.TrafficKey)).
Use(api.SetRequestLogger)
common.InitMiddleware(r)
// the jwt middleware
authMiddleware, err := middleware.AuthInit()
authMiddleware, err := common.AuthInit()
if err != nil {
log.Fatalf("JWT Init Error, %s", err.Error())
}
+8 -2
View File
@@ -13,9 +13,10 @@ func init() {
// 需认证的路由代码
func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := &sys_config.SysConfig{}
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
{
api := &sys_config.SysConfig{}
r.GET("", api.GetSysConfigList)
r.GET("/:id", api.GetSysConfig)
r.POST("", api.InsertSysConfig)
@@ -25,7 +26,12 @@ func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMidd
r1 := v1.Group("/configKey").Use(authMiddleware.MiddlewareFunc())
{
api := &sys_config.SysConfig{}
r1.GET("/:configKey", api.GetSysConfigByKEYForService)
}
r2 := v1.Group("/app-config")
{
r2.GET("", api.GetSysConfigBySysApp)
}
}
+40 -27
View File
@@ -1,23 +1,24 @@
package router
import (
"go-admin/app/admin/apis/system/sys_menu"
middleware2 "go-admin/common/middleware"
"mime"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/go-admin-team/go-admin-core/sdk/pkg/ws"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"go-admin/app/admin/apis/monitor"
"go-admin/app/admin/apis/public"
"go-admin/app/admin/apis/system"
"go-admin/app/admin/apis/system/dict"
. "go-admin/app/admin/apis/tools"
"go-admin/app/admin/middleware/handler"
"go-admin/app/admin/apis/system/sys_dept"
"go-admin/app/admin/apis/system/sys_menu"
"go-admin/app/admin/apis/tools"
"go-admin/common/middleware"
"go-admin/common/middleware/handler"
_ "go-admin/docs"
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
@@ -57,12 +58,18 @@ func sysSwaggerRouter(r *gin.RouterGroup) {
func sysNoCheckRoleRouter(r *gin.RouterGroup) {
v1 := r.Group("/api/v1")
v1.GET("/monitor/server", monitor.ServerInfo)
v1.GET("/getCaptcha", system.GenerateCaptchaHandler)
v1.GET("/gen/preview/:tableId", Preview)
v1.GET("/gen/toproject/:tableId", GenCodeV3)
v1.GET("/gen/todb/:tableId", GenMenuAndApi)
v1.GET("/gen/tabletree", GetSysTablesTree)
m := &monitor.Monitor{}
v1.GET("/monitor/server", m.ServerInfo)
sys := &system.System{}
v1.GET("/getCaptcha", sys.GenerateCaptchaHandler)
gen := &tools.Gen{}
v1.GET("/gen/preview/:tableId", gen.Preview)
v1.GET("/gen/toproject/:tableId", gen.GenCodeV3)
v1.GET("/gen/apitofile/:tableId", gen.GenApiToFile)
v1.GET("/gen/todb/:tableId", gen.GenMenuAndApi)
sysTable := &tools.SysTable{}
v1.GET("/gen/tabletree", sysTable.GetSysTablesTree)
registerDBRouter(v1)
registerSysTableRouter(v1)
@@ -73,22 +80,24 @@ func sysNoCheckRoleRouter(r *gin.RouterGroup) {
func registerDBRouter(api *gin.RouterGroup) {
db := api.Group("/db")
{
db.GET("/tables/page", GetDBTableList)
db.GET("/columns/page", GetDBColumnList)
gen := &tools.Gen{}
db.GET("/tables/page", gen.GetDBTableList)
db.GET("/columns/page", gen.GetDBColumnList)
}
}
func registerSysTableRouter(v1 *gin.RouterGroup) {
systables := v1.Group("/sys/tables")
{
systables.GET("/page", GetSysTableList)
sysTable := &tools.SysTable{}
systables.GET("/page", sysTable.GetSysTableList)
tablesinfo := systables.Group("/info")
{
tablesinfo.POST("", InsertSysTable)
tablesinfo.PUT("", UpdateSysTable)
tablesinfo.DELETE("/:tableId", DeleteSysTables)
tablesinfo.GET("/:tableId", GetSysTables)
tablesinfo.GET("", GetSysTablesInfo)
tablesinfo.POST("", sysTable.InsertSysTable)
tablesinfo.PUT("", sysTable.UpdateSysTable)
tablesinfo.DELETE("/:tableId", sysTable.DeleteSysTables)
tablesinfo.GET("/:tableId", sysTable.GetSysTables)
tablesinfo.GET("", sysTable.GetSysTablesInfo)
}
}
}
@@ -110,12 +119,14 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_menu.SysMenu{}
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api2 := sys_dept.SysDept{}
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
//v1auth.GET("/getinfo", system.GetInfo)
v1auth.GET("/roleMenuTreeselect/:roleId", api.GetMenuTreeSelect)
v1.GET("/menuTreeselect", api.GetMenuTreeSelect)
//v1auth.GET("/roleDeptTreeselect/:roleId", system.GetDeptTreeRoleselect)
v1auth.GET("/roleDeptTreeselect/:roleId", api2.GetDeptTreeRoleSelect)
//GetDeptTreeRoleselect)
v1auth.POST("/logout", handler.LogOut)
}
}
@@ -160,7 +171,7 @@ func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
dictApi := &dict.SysDictType{}
dataApi := &dict.SysDictData{}
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
dicts.GET("/data", dataApi.GetSysDictDataList)
@@ -190,17 +201,19 @@ func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
//}
func registerSysSettingRouter(v1 *gin.RouterGroup) {
api := system.SysSetting{}
m := &monitor.Monitor{}
setting := v1.Group("/setting")
{
setting.GET("", api.GetSetting)
setting.POST("", api.CreateOrUpdateSetting)
setting.GET("/serverInfo", monitor.ServerInfo)
setting.GET("/serverInfo", m.ServerInfo)
}
}
func registerPublicRouter(v1 *gin.RouterGroup) {
p := v1.Group("/public")
{
p.POST("/uploadFile", public.UploadFile)
file := &public.File{}
p.POST("/uploadFile", file.UploadFile)
}
}
+11 -16
View File
@@ -2,7 +2,7 @@ package dto
import (
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models"
"go-admin/common/dto"
@@ -12,8 +12,8 @@ import (
type SysCategorySearch struct {
dto.Pagination `search:"-"`
Name string `form:"name" search:"type:exact;column:name;table:sys_category" comment:"名称"`
Status string `form:"status" search:"type:exact;column:status;table:sys_category" comment:"状态"`
Status string `form:"status" search:"type:exact;column:status;table:sys_category" comment:"状态"`
CateId int `form:"cateId" search:"type:exact;column:cate_id;table:sys_category" comment:"分类id"`
}
func (m *SysCategorySearch) GetNeedSearch() interface{} {
@@ -21,7 +21,7 @@ func (m *SysCategorySearch) GetNeedSearch() interface{} {
}
func (m *SysCategorySearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -35,21 +35,16 @@ func (m *SysCategorySearch) Generate() dto.Index {
}
type SysCategoryControl struct {
ID int `uri:"Id" comment:"标识"` // 标识
Name string `json:"name" comment:"名称"`
Img string `json:"img" comment:"图标"`
Sort string `json:"sort" comment:"排序"`
Status string `json:"status" comment:"状态"`
ID int `uri:"Id" comment:"标识"`
Name string `json:"name" comment:"名称"`
Img string `json:"img" comment:"图标"`
Sort int `json:"sort" comment:"排序"`
Status int `json:"status" comment:"状态"`
Remark string `json:"remark" comment:"备注"`
}
func (s *SysCategoryControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -93,4 +88,4 @@ func (s *SysCategoryById) Generate() dto.Control {
func (s *SysCategoryById) GenerateM() (common.ActiveRecord, error) {
return &models.SysCategory{}, nil
}
}
+11 -6
View File
@@ -2,10 +2,12 @@ package dto
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/apis"
"go-admin/common/dto"
common "go-admin/common/models"
)
@@ -13,9 +15,10 @@ import (
// SysConfigSearch 列表或者搜索使用结构体
type SysConfigSearch struct {
dto.Pagination `search:"-"`
ConfigName string `form:"configName" search:"type:exact;column:config_name;table:sys_config" comment:""`
ConfigKey string `form:"configKey" search:"type:exact;column:config_key;table:sys_config" comment:""`
ConfigName string `form:"configName" search:"type:contains;column:config_name;table:sys_config" comment:""`
ConfigKey string `form:"configKey" search:"type:contains;column:config_key;table:sys_config" comment:""`
ConfigType string `form:"configType" search:"type:exact;column:config_type;table:sys_config" comment:""`
IsFrontend int `json:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config" comment:""`
}
func (m *SysConfigSearch) GetNeedSearch() interface{} {
@@ -24,7 +27,7 @@ func (m *SysConfigSearch) GetNeedSearch() interface{} {
// Bind 映射上下文中的结构体数据
func (m *SysConfigSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -39,12 +42,13 @@ type SysConfigControl struct {
ConfigKey string `uri:"configKey" json:"configKey" comment:""`
ConfigValue string `json:"configValue" comment:""`
ConfigType string `json:"configType" comment:""`
IsFrontend int `json:"isFrontend"`
Remark string `json:"remark" comment:""`
}
// Bind 映射上下文中的结构体数据
func (s *SysConfigControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -71,6 +75,7 @@ func (s *SysConfigControl) Generate() (*system.SysConfig, error) {
ConfigKey: s.ConfigKey,
ConfigValue: s.ConfigValue,
ConfigType: s.ConfigType,
IsFrontend: s.IsFrontend,
Remark: s.Remark,
}, nil
}
@@ -96,7 +101,7 @@ func (s *SysConfigById) GetId() interface{} {
}
func (s *SysConfigById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+10 -8
View File
@@ -2,7 +2,7 @@ package dto
import (
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models"
"go-admin/common/dto"
@@ -11,6 +11,8 @@ import (
type SysContentSearch struct {
dto.Pagination `search:"-"`
Name string `form:"name" search:"type:exact;column:name;table:sys_category" comment:"名称"`
Status string `form:"status" search:"type:exact;column:status;table:sys_category" comment:"状态"`
}
func (m *SysContentSearch) GetNeedSearch() interface{} {
@@ -18,7 +20,7 @@ func (m *SysContentSearch) GetNeedSearch() interface{} {
}
func (m *SysContentSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -33,17 +35,17 @@ func (m *SysContentSearch) Generate() dto.Index {
type SysContentControl struct {
ID int `uri:"ID" comment:""` //
CateId string `json:"cateId" comment:""`
CateId int `json:"cateId" comment:""`
Name string `json:"name" comment:""`
Status string `json:"status" comment:""`
Status int `json:"status" comment:""`
Img string `json:"img" comment:""`
Content string `json:"content" comment:""`
Remark string `json:"remark" comment:""`
Sort string `json:"sort" comment:""`
Sort int `json:"sort" comment:""`
}
func (s *SysContentControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -63,7 +65,7 @@ func (s *SysContentControl) Generate() dto.Control {
func (s *SysContentControl) GenerateM() (common.ActiveRecord, error) {
return &models.SysContent{
Id: s.ID,
Model: common.Model{s.ID},
CateId: s.CateId,
Name: s.Name,
Status: s.Status,
@@ -89,4 +91,4 @@ func (s *SysContentById) Generate() dto.Control {
func (s *SysContentById) GenerateM() (common.ActiveRecord, error) {
return &models.SysContent{}, nil
}
}
+4 -4
View File
@@ -2,10 +2,10 @@ package dto
import (
"encoding/json"
"go-admin/common/apis"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -31,7 +31,7 @@ func (m *SysDeptSearch) GetNeedSearch() interface{} {
// Bind 映射上下文中的结构体数据
func (m *SysDeptSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -54,7 +54,7 @@ type SysDeptControl struct {
// Bind 映射上下文中的结构体数据
func (s *SysDeptControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -109,7 +109,7 @@ func (s *SysDeptById) GetId() interface{} {
}
func (s *SysDeptById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+3 -3
View File
@@ -1,10 +1,10 @@
package dto
import (
"go-admin/common/apis"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -25,7 +25,7 @@ func (m *SysDictDataSearch) GetNeedSearch() interface{} {
}
func (m *SysDictDataSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -53,7 +53,7 @@ type SysDictDataControl struct {
}
func (s *SysDictDataControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+3 -3
View File
@@ -2,8 +2,8 @@ package dto
import (
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
common "go-admin/common/models"
@@ -22,7 +22,7 @@ func (m *SysDictTypeSearch) GetNeedSearch() interface{} {
}
func (m *SysDictTypeSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -48,7 +48,7 @@ type SysDictTypeControl struct {
}
func (s *SysDictTypeControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+3 -3
View File
@@ -2,7 +2,7 @@ package dto
import (
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models"
"go-admin/common/dto"
@@ -24,7 +24,7 @@ func (m *SysFileDirSearch) GetNeedSearch() interface{} {
}
func (m *SysFileDirSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -48,7 +48,7 @@ type SysFileDirControl struct {
}
func (s *SysFileDirControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+2 -2
View File
@@ -2,7 +2,7 @@ package dto
import (
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models"
"go-admin/common/dto"
@@ -24,7 +24,7 @@ func (m *SysJobSearch) GetNeedSearch() interface{} {
}
func (m *SysJobSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Errorf("Bind error: %s", err)
+4 -4
View File
@@ -1,10 +1,10 @@
package dto
import (
"go-admin/common/apis"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -24,7 +24,7 @@ func (m *SysLoginLogSearch) GetNeedSearch() interface{} {
}
func (m *SysLoginLogSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -47,7 +47,7 @@ type SysLoginLogControl struct {
}
func (s *SysLoginLogControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -90,7 +90,7 @@ func (s *SysLoginLogById) GetId() interface{} {
}
func (s *SysLoginLogById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+4 -4
View File
@@ -2,10 +2,10 @@ package dto
import (
"encoding/json"
"go-admin/common/apis"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -30,7 +30,7 @@ func (m *SysMenuSearch) GetNeedSearch() interface{} {
// Bind 映射上下文中的结构体数据
func (m *SysMenuSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -60,7 +60,7 @@ type SysMenuControl struct {
// Bind 映射上下文中的结构体数据
func (s *SysMenuControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -122,7 +122,7 @@ func (s *SysMenuById) GetId() interface{} {
}
func (s *SysMenuById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+4 -4
View File
@@ -1,10 +1,10 @@
package dto
import (
"go-admin/common/apis"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -26,7 +26,7 @@ func (m *SysOperaLogSearch) GetNeedSearch() interface{} {
}
func (m *SysOperaLogSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -57,7 +57,7 @@ type SysOperaLogControl struct {
}
func (s *SysOperaLogControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -112,7 +112,7 @@ func (s *SysOperaLogById) GetId() interface{} {
}
func (s *SysOperaLogById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+4 -4
View File
@@ -2,10 +2,10 @@ package dto
import (
"encoding/json"
"go-admin/common/apis"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -28,7 +28,7 @@ func (m *SysPostSearch) GetNeedSearch() interface{} {
// Bind 映射上下文中的结构体数据
func (m *SysPostSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -48,7 +48,7 @@ type SysPostControl struct {
// Bind 映射上下文中的结构体数据
func (s *SysPostControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -100,7 +100,7 @@ func (s *SysPostById) GetId() interface{} {
}
func (s *SysPostById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+5 -5
View File
@@ -2,10 +2,10 @@ package dto
import (
"encoding/json"
"go-admin/common/apis"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -32,7 +32,7 @@ func (m *SysRoleSearch) GetNeedSearch() interface{} {
// Bind 映射上下文中的结构体数据
func (m *SysRoleSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -50,13 +50,13 @@ type SysRoleControl struct {
Flag string `form:"flag" comment:"标记"` // 标记
Remark string `form:"remark" comment:"备注"` // 备注
Admin bool `form:"admin" comment:"是否管理员"`
DataScope string `form:"dataScope" comment:"是否管理员"`
DataScope string `form:"dataScope"`
MenuIds []int `json:"menuIds"`
}
// Bind 映射上下文中的结构体数据
func (s *SysRoleControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindBodyWith(s, binding.JSON)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -123,4 +123,4 @@ type RoleDataScopeReq struct {
type DeptIdList struct {
DeptId int `json:"DeptId"`
}
}
+3 -3
View File
@@ -2,9 +2,9 @@ package dto
import (
"encoding/json"
"go-admin/common/apis"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models"
)
@@ -18,7 +18,7 @@ type SysSettingControl struct {
// Bind 映射上下文中的结构体数据
func (s *SysSettingControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(s)
if err != nil {
@@ -70,7 +70,7 @@ func (s *SysSettingById) GetId() interface{} {
}
func (s *SysSettingById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
+5 -4
View File
@@ -2,7 +2,7 @@ package dto
import (
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models/system"
"go-admin/common/dto"
@@ -28,7 +28,7 @@ func (m *SysUserSearch) GetNeedSearch() interface{} {
}
func (m *SysUserSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -58,7 +58,7 @@ type SysUserControl struct {
}
func (s *SysUserControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
//err := ctx.ShouldBindUri(s)
//if err != nil {
// log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -113,5 +113,6 @@ func (s *SysUserById) GenerateM() (common.ActiveRecord, error) {
// PassWord 密码
type PassWord struct {
Password string `json:"password"`
NewPassword string `json:"newPassword" binding:"required"`
OldPassword string `json:"oldPassword" binding:"required"`
}
+5 -8
View File
@@ -1,10 +1,10 @@
package dto
import (
"go-admin/common/apis"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/admin/models"
"go-admin/common/dto"
@@ -22,7 +22,7 @@ func (m *SysChinaAreaDataSearch) GetNeedSearch() interface{} {
}
func (m *SysChinaAreaDataSearch) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
@@ -40,7 +40,7 @@ type SysChinaAreaDataControl struct {
}
func (s *SysChinaAreaDataControl) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -59,9 +59,6 @@ func (s *SysChinaAreaDataControl) Generate() (*models.SysChinaAreaData, error) {
Model: common.Model{Id: s.Id},
PId: s.PId,
Name: s.Name,
CreateTime: s.CreateTime,
UpdateTime: s.UpdateTime,
DeleteTime: s.DeleteTime,
}, nil
}
@@ -83,7 +80,7 @@ func (s *SysChinaAreaDataById) GetId() interface{} {
}
func (s *SysChinaAreaDataById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
@@ -98,4 +95,4 @@ func (s *SysChinaAreaDataById) Bind(ctx *gin.Context) error {
func (s *SysChinaAreaDataById) SetUpdateBy(id int) {
}
}
+16
View File
@@ -32,6 +32,22 @@ func (e *SysConfig) GetSysConfigPage(c *dto.SysConfigSearch, list *[]system.SysC
return nil
}
func (e *SysConfig) GetSysConfigByKey(c *dto.SysConfigSearch, list *[]system.SysConfig) error {
var err error
var data system.SysConfig
err = e.Orm.Model(&data).
Scopes(
cDto.MakeCondition(c.GetNeedSearch()),
).
Find(list).Error
if err != nil {
e.Log.Errorf("db error:%s", err)
return err
}
return nil
}
// GetSysConfig 获取SysConfig对象
func (e *SysConfig) GetSysConfig(d *dto.SysConfigById, model *system.SysConfig) error {
var err error
+64 -63
View File
@@ -2,6 +2,7 @@ package service
import (
"errors"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
@@ -220,66 +221,66 @@ func (e *SysDept) deptPageCall(deptlist *[]system.SysDept, menu system.SysDept)
return menu
}
//// GetRoleDeptId 获取角色的部门ID集合
//func (e *SysDept) GetRoleDeptId(roleId int) ([]int, error) {
// deptIds := make([]int, 0)
// deptList := make([]dto.DeptIdList, 0)
// if err := e.Orm.Table("sys_role_dept").
// Select("sys_role_dept.dept_id").
// Joins("LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id").
// Where("role_id = ? ", roleId).
// Where(" sys_role_dept.dept_id not in(select sys_dept.parent_id from sys_role_dept LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id where role_id =? )", roleId).
// Find(&deptList).Error; err != nil {
// return nil, err
// }
//
// for i := 0; i < len(deptList); i++ {
// deptIds = append(deptIds, deptList[i].DeptId)
// }
//
// return deptIds, nil
//}
//
//func (e *SysDept) SetDeptLabel() (m []dto.DeptLabel, err error) {
// list := make([]models.SysDept, 0)
// err = e.Orm.Find(&list).Error
// if err != nil {
// log.Error("find dept list error, %s", e.err)
// return
// }
//
// m = make([]dto.DeptLabel, 0)
// var item dto.DeptLabel
// for i := range list {
// if list[i].ParentId != 0 {
// continue
// }
// item = dto.DeptLabel{}
// item.Id = list[i].DeptId
// item.Label = list[i].DeptName
// deptInfo := digitDeptLabel(&list, item)
//
// m = append(m, deptInfo)
// }
// return
//}
//
//// digitDeptLabel
//func digitDeptLabel(deptList *[]models.SysDept, dept dto.DeptLabel) dto.DeptLabel {
// list := *deptList
//
// var mi dto.DeptLabel
// min := make([]dto.DeptLabel, 0)
// for j := 0; j < len(list); j++ {
//
// if dept.Id != list[j].ParentId {
// continue
// }
// mi = dto.DeptLabel{Id: list[j].DeptId, Label: list[j].DeptName, Children: []dto.DeptLabel{}}
// ms := digitDeptLabel(deptList, mi)
// min = append(min, ms)
//
// }
// dept.Children = min
// return dept
//}
// GetRoleDeptId 获取角色的部门ID集合
func (e *SysDept) GetRoleDeptId(roleId int) ([]int, error) {
deptIds := make([]int, 0)
deptList := make([]dto.DeptIdList, 0)
if err := e.Orm.Table("sys_role_dept").
Select("sys_role_dept.dept_id").
Joins("LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id").
Where("role_id = ? ", roleId).
Where(" sys_role_dept.dept_id not in(select sys_dept.parent_id from sys_role_dept LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id where role_id =? )", roleId).
Find(&deptList).Error; err != nil {
return nil, err
}
for i := 0; i < len(deptList); i++ {
deptIds = append(deptIds, deptList[i].DeptId)
}
return deptIds, nil
}
func (e *SysDept) SetDeptLabel() (m []dto.DeptLabel, err error) {
list := make([]system.SysDept, 0)
err = e.Orm.Find(&list).Error
if err != nil {
log.Error("find dept list error, %s", err.Error())
return
}
m = make([]dto.DeptLabel, 0)
var item dto.DeptLabel
for i := range list {
if list[i].ParentId != 0 {
continue
}
item = dto.DeptLabel{}
item.Id = list[i].DeptId
item.Label = list[i].DeptName
deptInfo := digitDeptLabel(&list, item)
m = append(m, deptInfo)
}
return
}
// digitDeptLabel
func digitDeptLabel(deptList *[]system.SysDept, dept dto.DeptLabel) dto.DeptLabel {
list := *deptList
var mi dto.DeptLabel
min := make([]dto.DeptLabel, 0)
for j := 0; j < len(list); j++ {
if dept.Id != list[j].ParentId {
continue
}
mi = dto.DeptLabel{Id: list[j].DeptId, Label: list[j].DeptName, Children: []dto.DeptLabel{}}
ms := digitDeptLabel(deptList, mi)
min = append(min, ms)
}
dept.Children = min
return dept
}
+2 -2
View File
@@ -197,7 +197,7 @@ func (e *SysRole) UpdateDataScope(c *system.SysRole) (err error) {
tx.Commit()
}
}()
err = tx.Model(&system.SysRole{}).Where("role_id = ?", c.RoleId).Select("data_scope, update_by").Updates(c).Error
err = tx.Model(&system.SysRole{}).Where("role_id = ?", c.RoleId).Select("data_scope", "update_by").Updates(c).Error
if err != nil {
return err
}
@@ -221,4 +221,4 @@ func (e *SysRole) UpdateDataScope(c *system.SysRole) (err error) {
}
}
return err
}
}
+31 -12
View File
@@ -3,6 +3,8 @@ package service
import (
"errors"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
"go-admin/app/admin/models/system"
@@ -115,29 +117,46 @@ func (e *SysUser) RemoveSysUser(d cDto.Control, c common.ActiveRecord, p *action
}
// UpdateSysUserPwd 修改SysUser对象密码
func (e *SysUser) UpdateSysUserPwd(c *system.SysUser, p *actions.DataPermission) error {
func (e *SysUser) UpdateSysUserPwd(id int, oldPassword, newPassword string, p *actions.DataPermission) error {
var err error
if c.Password == "" {
if newPassword == "" {
return nil
}
c := &system.SysUser{}
err = c.Encrypt()
if err != nil {
return err
}
db := e.Orm.Model(c).
err = e.Orm.Model(c).
Scopes(
actions.Permission(c.TableName(), p),
).Where(c.GetId()).Updates(c)
if db.Error != nil {
).Where(id).Select("UserId", "Password", "Salt").First(c).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("无权更新该数据")
}
e.Log.Errorf("db error: %s", err)
return err
}
var ok bool
ok, err = pkg.CompareHashAndPassword(c.Password, oldPassword)
if err != nil {
e.Log.Errorf("CompareHashAndPassword error, %s", err.Error())
return err
}
if !ok {
err = errors.New("incorrect Password")
e.Log.Warnf("user[%d] %s", id, err.Error())
return err
}
c.Password = newPassword
db := e.Orm.Model(c).Where(id).Select("Password", "Salt").Updates(c)
if err = db.Error; err != nil {
e.Log.Errorf("db error: %s", err)
return err
}
if db.RowsAffected == 0 {
return errors.New("无权更新该数据")
err = errors.New("set password error")
log.Warnf("db update error")
return err
}
return nil
}
+14 -4
View File
@@ -3,8 +3,6 @@ package api
import (
"context"
"fmt"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"log"
"net/http"
"os"
@@ -13,10 +11,13 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/config/source/file"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/logger"
"github.com/spf13/cobra"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg/logger"
"go-admin/app/admin/models/system"
"go-admin/app/admin/router"
"go-admin/app/jobs"
"go-admin/common/database"
@@ -62,9 +63,18 @@ func setup() {
config.LoggerConfig.Stdout))
//3. 初始化数据库链接
database.Setup()
//4. 设置缓存
cacheAdapter, err := config.CacheConfig.Setup()
if err != nil {
log.Fatalf("cache setup error, %s\n", err.Error())
}
sdk.Runtime.SetCacheAdapter(cacheAdapter)
usageStr := `starting api server...`
log.Println(usageStr)
//注册监听函数
sdk.Runtime.GetCacheAdapter().Register(global.LoginLog, system.SaveLoginLog)
sdk.Runtime.GetCacheAdapter().Register(global.OperateLog, system.SaveOperaLog)
}
func run() error {
@@ -0,0 +1,29 @@
package version
import (
"gorm.io/gorm"
"runtime"
"strings"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
)
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1615948084336Test)
}
func _1615948084336Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Exec("alter table sys_config add is_frontend int default 1 null comment '是否前台参数' after config_type").Error
if err != nil && !strings.Contains(err.Error(),"Duplicate column name 'is_frontend'") {
return err
}
return tx.Create(&common.Migration{
Version: version,
}).Error
})
}
@@ -0,0 +1,33 @@
package version
import (
"gorm.io/gorm"
"runtime"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
)
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1615950701614Test)
}
func _1615950701614Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Exec("UPDATE sys_dict_data t SET t.dict_value = '2' WHERE t.dict_code = 16").Error
if err != nil {
return err
}
err = tx.Exec("UPDATE sys_opera_log t SET t.status = '2' WHERE t.status = '0'").Error
if err != nil {
return err
}
return tx.Create(&common.Migration{
Version: version,
}).Error
})
}
@@ -0,0 +1,33 @@
package version
import (
"gorm.io/gorm"
"runtime"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
)
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1615961953379Test)
}
func _1615961953379Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Exec("INSERT INTO `sys_config` (`id`, `config_name`, `config_key`, `config_value`, `config_type`, `is_frontend`, `remark`, `create_by`, `update_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (4, '系统名称', 'sys_app_name', 'go-admin管理系统', 'Y', 1, '', 1, 0, '2021-03-17 08:52:06.067', '2021-03-17 08:52:06.067', NULL);").Error
if err != nil {
return err
}
err = tx.Exec("INSERT INTO `sys_config` (`id`, `config_name`, `config_key`, `config_value`, `config_type`, `is_frontend`, `remark`, `create_by`, `update_by`, `created_at`, `updated_at`, `deleted_at`) VALUES (5, '系统logo', 'sys_app_logo', 'https://gitee.com/mydearzwj/image/raw/master/img/go-admin.png', 'Y', 1, '', 1, 0, '2021-03-17 08:53:19.462', '2021-03-17 08:53:19.462', NULL);").Error
if err != nil {
return err
}
return tx.Create(&common.Migration{
Version: version,
}).Error
})
}
+6 -6
View File
@@ -4,11 +4,11 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/common/apis"
"go-admin/common/dto"
"go-admin/common/models"
)
@@ -16,7 +16,7 @@ import (
// CreateAction 通用新增动作
func CreateAction(control dto.Control) gin.HandlerFunc {
return func(c *gin.Context) {
log := apis.GetRequestLogger(c)
log := api.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
if err != nil {
log.Error(err)
@@ -27,23 +27,23 @@ func CreateAction(control dto.Control) gin.HandlerFunc {
req := control.Generate()
err = req.Bind(c)
if err != nil {
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object models.ActiveRecord
object, err = req.GenerateM()
if err != nil {
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
response.Error(c, http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetCreateBy(user.GetUserId(c))
err = db.WithContext(c).Create(object).Error
if err != nil {
log.Errorf("Create error: %s", err)
app.Error(c, http.StatusInternalServerError, err, "创建失败")
response.Error(c, http.StatusInternalServerError, err, "创建失败")
return
}
app.OK(c, object.GetId(), "创建成功")
response.OK(c, object.GetId(), "创建成功")
c.Next()
}
}
+5 -5
View File
@@ -28,13 +28,13 @@ func DeleteAction(control dto.Control) gin.HandlerFunc {
err = req.Bind(c)
if err != nil {
log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object models.ActiveRecord
object, err = req.GenerateM()
if err != nil {
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
response.Error(c, http.StatusInternalServerError, err, "模型生成失败")
return
}
@@ -48,14 +48,14 @@ func DeleteAction(control dto.Control) gin.HandlerFunc {
).Where(req.GetId()).Delete(object)
if db.Error != nil {
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
app.Error(c, http.StatusInternalServerError, err, "删除失败")
response.Error(c, http.StatusInternalServerError, err, "删除失败")
return
}
if db.RowsAffected == 0 {
app.Error(c, http.StatusForbidden, nil, "无权删除该数据")
response.Error(c, http.StatusForbidden, nil, "无权删除该数据")
return
}
app.OK(c, object.GetId(), "删除成功")
response.OK(c, object.GetId(), "删除成功")
c.Next()
}
}
+3 -3
View File
@@ -32,7 +32,7 @@ func IndexAction(m models.ActiveRecord, d dto.Index, f func() interface{}) gin.H
//查询列表
err = req.Bind(c)
if err != nil {
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
@@ -49,10 +49,10 @@ func IndexAction(m models.ActiveRecord, d dto.Index, f func() interface{}) gin.H
Count(&count).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
log.Errorf("MsgID[%s] Index error: %s", msgID, err)
app.Error(c, http.StatusInternalServerError, err, "查询失败")
response.Error(c, http.StatusInternalServerError, err, "查询失败")
return
}
app.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
response.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
c.Next()
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ func PermissionAction() gin.HandlerFunc {
p, err = newDataPermission(db, userId)
if err != nil {
log.Errorf("MsgID[%s] PermissionAction error: %s", msgID, err)
app.Error(c, http.StatusInternalServerError, err, "权限范围鉴定错误")
response.Error(c, http.StatusInternalServerError, err, "权限范围鉴定错误")
c.Abort()
return
}
+5 -5
View File
@@ -27,13 +27,13 @@ func UpdateAction(control dto.Control) gin.HandlerFunc {
//更新操作
err = req.Bind(c)
if err != nil {
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object models.ActiveRecord
object, err = req.GenerateM()
if err != nil {
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
response.Error(c, http.StatusInternalServerError, err, "模型生成失败")
return
}
object.SetUpdateBy(user.GetUserId(c))
@@ -46,14 +46,14 @@ func UpdateAction(control dto.Control) gin.HandlerFunc {
).Where(req.GetId()).Updates(object)
if db.Error != nil {
log.Errorf("MsgID[%s] Update error: %s", msgID, err)
app.Error(c, http.StatusInternalServerError, err, "更新失败")
response.Error(c, http.StatusInternalServerError, err, "更新失败")
return
}
if db.RowsAffected == 0 {
app.Error(c, http.StatusForbidden, nil, "无权更新该数据")
response.Error(c, http.StatusForbidden, nil, "无权更新该数据")
return
}
app.OK(c, object.GetId(), "更新成功")
response.OK(c, object.GetId(), "更新成功")
c.Next()
}
}
+6 -6
View File
@@ -2,6 +2,7 @@ package actions
import (
"errors"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"net/http"
"github.com/gin-gonic/gin"
@@ -9,7 +10,6 @@ import (
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/common/dto"
"go-admin/common/models"
)
@@ -28,13 +28,13 @@ func ViewAction(control dto.Control, f func() interface{}) gin.HandlerFunc {
req := control.Generate()
err = req.Bind(c)
if err != nil {
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
var object models.ActiveRecord
object, err = req.GenerateM()
if err != nil {
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
response.Error(c, http.StatusInternalServerError, err, "模型生成失败")
return
}
@@ -53,15 +53,15 @@ func ViewAction(control dto.Control, f func() interface{}) gin.HandlerFunc {
).Where(req.GetId()).First(rsp).Error
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
app.Error(c, http.StatusNotFound, nil, "查看对象不存在或无权查看")
response.Error(c, http.StatusNotFound, nil, "查看对象不存在或无权查看")
return
}
if err != nil {
log.Errorf("MsgID[%s] View error: %s", msgID, err)
app.Error(c, http.StatusInternalServerError, err, "查看失败")
response.Error(c, http.StatusInternalServerError, err, "查看失败")
return
}
app.OK(c, rsp, "查看成功")
response.OK(c, rsp, "查看成功")
c.Next()
}
}
+8 -45
View File
@@ -1,15 +1,14 @@
package apis
import (
"encoding/json"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"gorm.io/gorm"
"go-admin/common/models"
)
type Api struct {
@@ -17,7 +16,7 @@ type Api struct {
// GetLogger 获取上下文提供的日志
func (e *Api) GetLogger(c *gin.Context) *logger.Logger {
return GetRequestLogger(c)
return api.GetRequestLogger(c)
}
// GetOrm 获取Orm DB
@@ -32,56 +31,20 @@ func (e *Api) GetOrm(c *gin.Context) (*gorm.DB, error) {
// Error 通常错误数据处理
func (e *Api) Error(c *gin.Context, code int, err error, msg string) {
var res models.Response
if err != nil {
res.Msg = err.Error()
}
if msg != "" {
res.Msg = msg
}
res.RequestId = pkg.GenerateMsgIDFromContext(c)
Return := res.ReturnError(code)
e.setResult(c, Return, res.RequestId, code)
c.AbortWithStatusJSON(http.StatusOK, Return)
response.Error(c, code, err, msg)
}
// OK 通常成功数据处理
func (e *Api) OK(c *gin.Context, data interface{}, msg string) {
var res models.Response
res.Data = data
if msg != "" {
res.Msg = msg
}
res.RequestId = pkg.GenerateMsgIDFromContext(c)
Return := res.ReturnOK()
e.setResult(c, Return, res.RequestId, 200)
c.AbortWithStatusJSON(http.StatusOK, Return)
response.OK(c, data, msg)
}
// PageOK 分页数据处理
func (e *Api) PageOK(c *gin.Context, result interface{}, count int, pageIndex int, pageSize int, msg string) {
var res models.Page
res.List = result
res.Count = count
res.PageIndex = pageIndex
res.PageSize = pageSize
e.OK(c, res, msg)
response.PageOK(c, result, count, pageIndex, pageSize, msg)
}
// Custom 兼容函数
func (e *Api) Custom(c *gin.Context, data gin.H) {
msgID := pkg.GenerateMsgIDFromContext(c)
Return := data
e.setResult(c, Return, msgID, 200)
c.AbortWithStatusJSON(http.StatusOK, Return)
}
func (e *Api) setResult(c *gin.Context, Return interface{}, msgID string, status int) {
requestLogger := e.GetLogger(c)
jsonStr, err := json.Marshal(Return)
if err != nil {
requestLogger.Debugf("setResult error: %#v", msgID, err.Error())
}
c.Set("result", string(jsonStr))
c.Set("status", status)
response.Custum(c, data)
}
+2 -3
View File
@@ -4,8 +4,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
)
type ObjectById struct {
@@ -15,7 +14,7 @@ type ObjectById struct {
func (s *ObjectById) Bind(ctx *gin.Context) error {
var err error
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err = ctx.ShouldBindUri(s)
if err != nil {
log.Warnf("ShouldBindUri error: %s", err.Error())
+2 -2
View File
@@ -2,11 +2,11 @@ package global
const (
// go-admin Version Info
Version = "1.3.0-rc.0"
Version = "1.3.2"
)
var (
Source string
Driver string
DBName string
)
)
+2 -2
View File
@@ -4,11 +4,11 @@ import (
"github.com/casbin/casbin/v2"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"go-admin/common/apis"
"github.com/go-admin-team/go-admin-core/sdk/api"
)
func LoadPolicy(c *gin.Context) (*casbin.SyncedEnforcer, error) {
log := apis.GetRequestLogger(c)
log := api.GetRequestLogger(c)
if err := sdk.Runtime.GetCasbinKey(c.Request.Host).LoadPolicy(); err == nil {
return sdk.Runtime.GetCasbinKey(c.Request.Host), err
} else {
+6
View File
@@ -0,0 +1,6 @@
package global
const (
LoginLog = "login_log_queue"
OperateLog = "operate_log_queue"
)
@@ -5,7 +5,7 @@ import (
"github.com/go-admin-team/go-admin-core/sdk/config"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/middleware/handler"
"go-admin/common/middleware/handler"
)
// AuthInit jwt验证new
@@ -4,6 +4,8 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
@@ -13,16 +15,15 @@ import (
"github.com/mssola/user_agent"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/common/apis"
"go-admin/common/global"
)
var store = base64Captcha.DefaultMemStore
func PayloadFunc(data interface{}) jwt.MapClaims {
if v, ok := data.(map[string]interface{}); ok {
u, _ := v["user"].(system.SysUser)
r, _ := v["role"].(system.SysRole)
u, _ := v["user"].(SysUser)
r, _ := v["role"].(SysRole)
return jwt.MapClaims{
jwt.IdentityKey: u.UserId,
jwt.RoleIdKey: r.RoleId,
@@ -56,19 +57,19 @@ func IdentityHandler(c *gin.Context) interface{} {
// @Description 注意:开发模式:需要注意全部字段不能为空,账号密码外可以传入0值
// @Accept application/json
// @Product application/json
// @Param account body models.Login true "account"
// @Param account body system.Login true "account"
// @Success 200 {string} string "{"code": 200, "expire": "2019-08-07T12:45:48+08:00", "token": ".eyJleHAiOjE1NjUxNTMxNDgsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTU2NTE0OTU0OH0.-zvzHvbg0A" }"
// @Router /login [post]
func Authenticator(c *gin.Context) (interface{}, error) {
log := apis.GetRequestLogger(c)
log := api.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
response.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return nil, jwt.ErrFailedAuthentication
}
var loginVals system.Login
var loginVals Login
var status = "2"
var msg = "登录成功"
var username = ""
@@ -107,29 +108,35 @@ func Authenticator(c *gin.Context) (interface{}, error) {
// LoginLogToDB Write log to database
func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
log := apis.GetRequestLogger(c)
if config.LoggerConfig.EnabledDB {
var loginLog system.SysLoginLog
db, err := pkg.GetOrm(c)
if !config.LoggerConfig.EnabledDB {
return
}
log := api.GetRequestLogger(c)
l := make(map[string]interface{})
ua := user_agent.New(c.Request.UserAgent())
l["ipaddr"] = c.ClientIP()
l["loginLocation"] = pkg.GetLocation(c.ClientIP())
l["loginTime"] = pkg.GetCurrentTime()
l["status"] = status
l["remark"] = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
l["browser"] = browserName + " " + browserVersion
l["os"] = ua.OS()
l["platform"] = ua.Platform()
l["username"] = username
l["msg"] = msg
q := sdk.Runtime.GetCachePrefix(c.Request.Host)
message, err := sdk.Runtime.GetStreamMessage("", global.LoginLog, l)
if err != nil {
log.Errorf("GetStreamMessage error, %s", err.Error())
//日志报错错误,不中断请求
} else {
err = q.Append(message)
if err != nil {
log.Errorf("获取Orm失败, error:%s", err)
log.Errorf("Append message error, %s", err.Error())
}
ua := user_agent.New(c.Request.UserAgent())
loginLog.Ipaddr = c.ClientIP()
loginLog.Username = username
location := pkg.GetLocation(c.ClientIP())
loginLog.LoginLocation = location
loginLog.LoginTime = pkg.GetCurrentTime()
loginLog.Status = status
loginLog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginLog.Browser = browserName + " " + browserVersion
loginLog.Os = ua.OS()
loginLog.Msg = msg
loginLog.Platform = ua.Platform()
serviceLoginLog := service.SysLoginLog{}
serviceLoginLog.Orm = db
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
}
}
@@ -143,28 +150,27 @@ func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
// @Router /logout [post]
// @Security Bearer
func LogOut(c *gin.Context) {
log := apis.GetRequestLogger(c)
var loginLog system.SysLoginLog
ua := user_agent.New(c.Request.UserAgent())
loginLog.Ipaddr = c.ClientIP()
location := pkg.GetLocation(c.ClientIP())
loginLog.LoginLocation = location
loginLog.LoginTime = pkg.GetCurrentTime()
loginLog.Status = "2"
loginLog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginLog.Browser = browserName + " " + browserVersion
loginLog.Os = ua.OS()
loginLog.Platform = ua.Platform()
loginLog.Username = user.GetUserName(c)
loginLog.Msg = "退出成功"
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("获取Orm失败, error:%s", err)
}
serviceLoginLog := service.SysLoginLog{}
serviceLoginLog.Orm = db
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
LoginLogToDB(c, "2", "退出成功", user.GetUserName(c))
//var loginLog system.SysLoginLog
//loginLog.Ipaddr = c.ClientIP()
//location := pkg.GetLocation(c.ClientIP())
//loginLog.LoginLocation = location
//loginLog.LoginTime = pkg.GetCurrentTime()
//loginLog.Status = "2"
//loginLog.Remark = c.Request.UserAgent()
//browserName, browserVersion := ua.Browser()
//loginLog.Browser = browserName + " " + browserVersion
//loginLog.Os = ua.OS()
//loginLog.Platform = ua.Platform()
//loginLog.Username = user.GetUserName(c)
//loginLog.Msg = "退出成功"
//db, err := pkg.GetOrm(c)
//if err != nil {
// log.Errorf("获取Orm失败, error:%s", err)
//}
//serviceLoginLog := service.SysLoginLog{}
//serviceLoginLog.Orm = db
//_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
c.JSON(http.StatusOK, gin.H{
"code": 200,
@@ -1,7 +1,6 @@
package system
package handler
import (
"fmt"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
@@ -20,7 +19,6 @@ func (u *Login) GetUser(tx *gorm.DB) (user SysUser, role SysRole, err error) {
log.Errorf("get user error, %s", err.Error())
return
}
fmt.Println(user.Password, u.Password)
_, err = pkg.CompareHashAndPassword(user.Password, u.Password)
if err != nil {
log.Errorf("user login error, %s", err.Error())
+24
View File
@@ -0,0 +1,24 @@
package handler
import "go-admin/common/models"
type SysRole struct {
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
Status string `json:"status" gorm:"size:4;"` //
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
RoleSort int `json:"roleSort" gorm:""` //角色排序
Flag string `json:"flag" gorm:"size:128;"` //
Remark string `json:"remark" gorm:"size:255;"` //备注
Admin bool `json:"admin" gorm:"size:4;"`
DataScope string `json:"dataScope" gorm:"size:128;"`
Params string `json:"params" gorm:"-"`
MenuIds []int `json:"menuIds" gorm:"-"`
DeptIds []int `json:"deptIds" gorm:"-"`
models.ControlBy
models.ModelTime
}
func (SysRole) TableName() string {
return "sys_role"
}
+40
View File
@@ -0,0 +1,40 @@
package handler
import (
"go-admin/common/models"
"gorm.io/gorm"
)
type SysUser struct {
models.ControlBy
models.ModelTime
UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
Username string `json:"username" gorm:"type:varchar(64);comment:用户名"`
Password string `json:"-" gorm:"type:varchar(128);comment:密码"`
NickName string `json:"nickName" gorm:"type:varchar(128);comment:昵称"`
Phone string `json:"phone" gorm:"type:varchar(11);comment:手机号"`
RoleId int `json:"roleId" gorm:"type:bigint(20);comment:角色ID"`
Salt string `json:"-" gorm:"type:varchar(255);comment:加盐"`
Avatar string `json:"avatar" gorm:"type:varchar(255);comment:头像"`
Sex string `json:"sex" gorm:"type:varchar(255);comment:性别"`
Email string `json:"email" gorm:"type:varchar(128);comment:邮箱"`
DeptId int `json:"deptId" gorm:"type:bigint(20);comment:部门"`
PostId int `json:"postId" gorm:"type:bigint(20);comment:岗位"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Status string `json:"status" gorm:"type:varchar(4);comment:状态"`
DeptIds []int `json:"deptIds" gorm:"-"`
PostIds []int `json:"postIds" gorm:"-"`
RoleIds []int `json:"roleIds" gorm:"-"`
//Dept *SysDept `json:"dept"`
}
func (SysUser) TableName() string {
return "sys_user"
}
func (e *SysUser) AfterFind(_ *gorm.DB) error {
e.DeptIds = []int{e.DeptId}
e.PostIds = []int{e.PostId}
e.RoleIds = []int{e.RoleId}
return nil
}
@@ -2,13 +2,11 @@ package middleware
import (
"github.com/gin-gonic/gin"
"go-admin/common/middleware"
)
func InitMiddleware(r *gin.Engine) {
// 数据库链接
r.Use(middleware.WithContextDb)
r.Use(WithContextDb)
// 日志处理
r.Use(LoggerToFile())
// 自定义错误处理
@@ -1,35 +1,36 @@
package middleware
import (
"fmt"
"encoding/json"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/common/apis"
"go-admin/common/global"
)
// LoggerToFile 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
return func(c *gin.Context) {
defer c.Next()
if c.Request.Method == http.MethodOptions {
return
}
log := apis.GetRequestLogger(c)
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
if c.Request.Method == http.MethodOptions {
return
}
log := api.GetRequestLogger(c)
bd, bl := c.Get("body")
var body = ""
if bl {
@@ -39,7 +40,12 @@ func LoggerToFile() gin.HandlerFunc {
rt, bl := c.Get("result")
var result = ""
if bl {
result = rt.(string)
rb, err := json.Marshal(rt)
if err != nil {
log.Warnf("json Marshal result error, %s", err.Error())
} else {
result = string(rb)
}
}
st, bl := c.Get("status")
@@ -56,8 +62,6 @@ func LoggerToFile() gin.HandlerFunc {
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
// 结束时间
endTime := time.Now()
// 执行时间
latencyTime := endTime.Sub(startTime)
// 日志格式
@@ -79,61 +83,50 @@ func LoggerToFile() gin.HandlerFunc {
// SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用
func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration, body string, result string, status int) {
log := apis.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
app.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
menu := models.Menu{}
menu.Path = reqUri
menu.Action = reqMethod
menuList, _ := menu.Get(db)
sysOperaLog := system.SysOperaLog{}
sysOperaLog.OperIp = clientIP
sysOperaLog.OperLocation = pkg.GetLocation(clientIP)
sysOperaLog.Status = pkg.IntToString(statusCode)
sysOperaLog.OperName = user.GetUserName(c)
sysOperaLog.RequestMethod = c.Request.Method
sysOperaLog.OperUrl = reqUri
sysOperaLog.OperParam = body
log := api.GetRequestLogger(c)
l := make(map[string]interface{})
l["_fullPath"] = c.FullPath()
l["operUrl"] = reqUri
l["method"] = reqMethod
l["operIp"] = clientIP
l["operLocation"] = pkg.GetLocation(clientIP)
l["operName"] = user.GetUserName(c)
l["requestMethod"] = c.Request.Method
l["operParam"] = body
l["operTime"] = time.Now()
if reqUri == "/login" {
sysOperaLog.BusinessType = "10"
sysOperaLog.Title = "用户登录"
sysOperaLog.OperName = "-"
l["businessType"] = "10"
l["title"] = "用户登录"
l["operName"] = "-"
} else if strings.Contains(reqUri, "/api/v1/logout") {
sysOperaLog.BusinessType = "11"
l["businessType"] = "11"
l["title"] = "退出登录"
} else if strings.Contains(reqUri, "/api/v1/getCaptcha") {
sysOperaLog.BusinessType = "12"
sysOperaLog.Title = "验证码"
l["businessType"] = "12"
l["title"] = "验证码"
} else {
if reqMethod == "POST" {
sysOperaLog.BusinessType = "1"
l["businessType"] = "1"
} else if reqMethod == "PUT" {
sysOperaLog.BusinessType = "2"
l["businessType"] = "2"
} else if reqMethod == "DELETE" {
sysOperaLog.BusinessType = "3"
l["businessType"] = "3"
}
}
sysOperaLog.Method = reqMethod
if len(menuList) > 0 {
sysOperaLog.Title = menuList[0].Title
}
sysOperaLog.CreateBy = user.GetUserId(c)
sysOperaLog.OperTime = pkg.GetCurrentTime()
sysOperaLog.LatencyTime = fmt.Sprintf("%v", latencyTime)
sysOperaLog.JsonResult = result
sysOperaLog.UserAgent = c.Request.UserAgent()
if status == 200 {
sysOperaLog.Status = "2"
if status == http.StatusOK {
l["status"] = "2"
} else {
sysOperaLog.Status = "1"
l["status"] = "1"
}
q := sdk.Runtime.GetCachePrefix(c.Request.Host)
message, err := sdk.Runtime.GetStreamMessage("", global.OperateLog, l)
if err != nil {
log.Errorf("GetStreamMessage error, %s", err.Error())
//日志报错错误,不中断请求
} else {
err = q.Append(message)
if err != nil {
log.Errorf("Append message error, %s", err.Error())
}
}
serviceOperaLog := service.SysOperaLog{}
serviceOperaLog.Orm = db
serviceOperaLog.Log = log
_ = serviceOperaLog.InsertSysOperaLog(&sysOperaLog)
}
+3 -4
View File
@@ -5,16 +5,15 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/common/apis"
)
//权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
return func(c *gin.Context) {
log := apis.GetRequestLogger(c)
log := api.GetRequestLogger(c)
data, _ := c.Get(jwtauth.JwtPayloadKey)
v := data.(jwtauth.MapClaims)
e := sdk.Runtime.GetCasbinKey(c.Request.Host)
@@ -28,7 +27,7 @@ func AuthCheckRole() gin.HandlerFunc {
res, err = e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
if err != nil {
log.Errorf("AuthCheckRole error:%s method:%s path:%s", err, c.Request.Method, c.Request.URL.Path)
app.Error(c, 500, err, "")
response.Error(c, 500, err, "")
return
}
}
+12 -12
View File
@@ -144,17 +144,17 @@ INSERT INTO sys_menu VALUES (468, 'sys_job', '创建定时任务', 'bug', '/api/
INSERT INTO sys_menu VALUES (469, 'sys_job', '修改定时任务', 'bug', '/api/v1/sysjob', '/0/63/465/469', 'A', 'PUT', '', 465, 0, '', '', 0, '1', '1', '1', '0', '2020-08-03 09:17:37', '2020-08-03 09:17:37', NULL);
INSERT INTO sys_menu VALUES (470, 'sys_job', '删除定时任务', 'bug', '/api/v1/sysjob/:id', '/0/63/465/470', 'A', 'DELETE', '', 465, 0, '', '', 0, '1', '1', '1', '0', '2020-08-03 09:17:37', '2020-08-03 09:17:37', NULL);
INSERT INTO sys_menu VALUES (471, 'job_log', '日志', 'bug', 'job_log', '/0/459/471', 'C', '', '', 459, 0, '', '/sysjob/log', 0, '1', '1', '1', '1', '2020-08-05 21:24:46', '2020-08-06 00:02:20', NULL);
INSERT INTO sys_menu VALUES (473, 'sysSetting', '系统配置', 'form', 'syssettings', '/0/60/473', 'C', '无', 'syssetting:syssetting:list', 60, 0, '', '/system/settings', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 02:17:10', NULL);
INSERT INTO sys_menu VALUES (474, 'sys_setting', '分页获取SysSetting', 'pass', 'sys_setting', '/0/60/473/474', 'F', '无', 'syssetting:syssetting:query', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (475, 'sys_setting', '创建SysSetting', 'pass', 'sys_setting', '/0/60/473/475', 'F', '无', 'syssetting:syssetting:add', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (476, 'sys_setting', '修改SysSetting', 'pass', 'sys_setting', '/0/60/473/476', 'F', '无', 'syssetting:syssetting:edit', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (477, 'sys_setting', '删除SysSetting', 'pass', 'sys_setting', '/0/60/473/477', 'F', '无', 'syssetting:syssetting:remove', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (478, 'sys_setting', 'SysSetting', 'bug', 'sys_setting', '/0/63/478', 'M', '无', '', 63, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (479, 'sys_setting', '分页获取SysSetting', 'bug', '/api/v1/syssettingList', '/0/63/478/479', 'A', 'GET', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (480, 'sys_setting', '根据id获取SysSetting', 'bug', '/api/v1/syssetting/:id', '/0/63/478/480', 'A', 'GET', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (481, 'sys_setting', '创建SysSetting', 'bug', '/api/v1/syssetting', '/0/63/478/481', 'A', 'POST', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (482, 'sys_setting', '修改SysSetting', 'bug', '/api/v1/syssetting', '/0/63/478/482', 'A', 'PUT', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
INSERT INTO sys_menu VALUES (483, 'sys_setting', '删除SysSetting', 'bug', '/api/v1/syssetting/:id', '/0/63/478/483', 'A', 'DELETE', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (473, 'sysSetting', '系统配置', 'form', 'syssettings', '/0/60/473', 'C', '无', 'syssetting:syssetting:list', 60, 0, '', '/system/settings', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 02:17:10', NULL);
-- INSERT INTO sys_menu VALUES (474, 'sys_setting', '分页获取SysSetting', 'pass', 'sys_setting', '/0/60/473/474', 'F', '无', 'syssetting:syssetting:query', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (475, 'sys_setting', '创建SysSetting', 'pass', 'sys_setting', '/0/60/473/475', 'F', '无', 'syssetting:syssetting:add', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (476, 'sys_setting', '修改SysSetting', 'pass', 'sys_setting', '/0/60/473/476', 'F', '无', 'syssetting:syssetting:edit', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (477, 'sys_setting', '删除SysSetting', 'pass', 'sys_setting', '/0/60/473/477', 'F', '无', 'syssetting:syssetting:remove', 473, 0, '', '', 0, '0', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (478, 'sys_setting', 'SysSetting', 'bug', 'sys_setting', '/0/63/478', 'M', '无', '', 63, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (479, 'sys_setting', '分页获取SysSetting', 'bug', '/api/v1/syssettingList', '/0/63/478/479', 'A', 'GET', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (480, 'sys_setting', '根据id获取SysSetting', 'bug', '/api/v1/syssetting/:id', '/0/63/478/480', 'A', 'GET', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (481, 'sys_setting', '创建SysSetting', 'bug', '/api/v1/syssetting', '/0/63/478/481', 'A', 'POST', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (482, 'sys_setting', '修改SysSetting', 'bug', '/api/v1/syssetting', '/0/63/478/482', 'A', 'PUT', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
-- INSERT INTO sys_menu VALUES (483, 'sys_setting', '删除SysSetting', 'bug', '/api/v1/syssetting/:id', '/0/63/478/483', 'A', 'DELETE', '', 478, 0, '', '', 0, '1', '1', '1', '0', '2020-08-09 01:05:22', '2020-08-09 01:05:22', NULL);
COMMIT;
-- 数据完成 ;
-- 数据完成 ;
+735 -885
View File
File diff suppressed because it is too large Load Diff
+735 -885
View File
File diff suppressed because it is too large Load Diff
+483 -588
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -8,8 +8,7 @@ require (
github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5
github.com/casbin/casbin/v2 v2.25.1
github.com/gin-gonic/gin v1.6.3
github.com/go-admin-team/go-admin-core v1.3.0
github.com/go-admin-team/go-admin-core/sdk v1.3.0-rc.2
github.com/go-admin-team/go-admin-core v1.3.2-rc.0
github.com/google/uuid v1.2.0
github.com/mojocn/base64Captcha v1.3.1
github.com/mssola/user_agent v0.5.2
+13 -1
View File
@@ -4,6 +4,18 @@ import (
"go-admin/cmd"
)
//go:generate swag init --parseDependency
// @title go-admin API
// @version 1.3.1
// @description 基于Gin + Vue + Element UI的前后端分离权限管理系统的接口文档
// @description 添加qq群: 74520518 进入技术交流群 请备注,谢谢!
// @license.name MIT
// @license.url https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
func main() {
cmd.Execute()
}
}
+326
View File
@@ -0,0 +1,326 @@
package version
import (
"gorm.io/gorm"
"runtime"
"time"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
)
type Menu struct {
MenuId int `json:"menuId" gorm:"primaryKey;autoIncrement"`
MenuName string `json:"menuName" gorm:"size:128;"`
Title string `json:"title" gorm:"size:128;"`
Icon string `json:"icon" gorm:"size:128;"`
Path string `json:"path" gorm:"size:128;"`
Paths string `json:"paths" gorm:"size:128;"`
MenuType string `json:"menuType" gorm:"size:1;"`
Action string `json:"action" gorm:"size:16;"`
Permission string `json:"permission" gorm:"size:255;"`
ParentId int `json:"parentId" gorm:"size:11;"`
NoCache bool `json:"noCache" gorm:"size:8;"`
Breadcrumb string `json:"breadcrumb" gorm:"size:255;"`
Component string `json:"component" gorm:"size:255;"`
Sort int `json:"sort" gorm:"size:4;"`
Visible string `json:"visible" gorm:"size:1;"`
CreateBy string `json:"createBy" gorm:"size:128;"`
UpdateBy string `json:"updateBy" gorm:"size:128;"`
IsFrame string `json:"isFrame" gorm:"size:1;DEFAULT:0;"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
func (Menu) TableName() string {
return "sys_menu"
}
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _{{.GenerateTime}}Test)
}
func _{{.GenerateTime}}Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
timeNow := pkg.GetCurrentTime()
Mmenu := Menu{}
Mmenu.MenuName = "{{.TBName}}Manage"
Mmenu.Title = "{{.TableComment}}"
Mmenu.Icon = "pass"
Mmenu.Path = "/{{.TBName}}"
Mmenu.MenuType = "M"
Mmenu.Action = "无"
Mmenu.ParentId = 0
Mmenu.NoCache = false
Mmenu.Component = "Layout"
Mmenu.Sort = 0
Mmenu.Visible = "0"
Mmenu.IsFrame = "0"
Mmenu.CreateBy = "1"
Mmenu.UpdateBy = "1"
Mmenu.CreatedAt = timeNow
Mmenu.UpdatedAt = timeNow
// Mmenu.MenuId, err = Mmenu.Create(db)
err := tx.Create(&Mmenu).Error
if err != nil {
return err
}
Cmenu := Menu{}
Cmenu.MenuName = "{{.TBName}}"
Cmenu.Title = "{{.TableComment}}"
Cmenu.Icon = "pass"
Cmenu.Path = "{{.TBName}}"
Cmenu.MenuType = "C"
Cmenu.Action = "无"
Cmenu.Permission = "{{.PackageName}}:{{.BusinessName}}:list"
Cmenu.ParentId = Mmenu.MenuId
Cmenu.NoCache = false
Cmenu.Component = "/{{.BusinessName}}/index"
Cmenu.Sort = 0
Cmenu.Visible = "0"
Cmenu.IsFrame = "0"
Cmenu.CreateBy = "1"
Cmenu.UpdateBy = "1"
Cmenu.CreatedAt = timeNow
Cmenu.UpdatedAt = timeNow
// Cmenu.MenuId, err = Cmenu.Create(db)
err = tx.Create(&Cmenu).Error
if err != nil {
return err
}
MList := Menu{}
MList.MenuName = ""
MList.Title = "分页获取{{.TableComment}}"
MList.Icon = ""
MList.Path = "{{.TBName}}"
MList.MenuType = "F"
MList.Action = "无"
MList.Permission = "{{.PackageName}}:{{.BusinessName}}:query"
MList.ParentId = Cmenu.MenuId
MList.NoCache = false
MList.Sort = 0
MList.Visible = "0"
MList.IsFrame = "0"
MList.CreateBy = "1"
MList.UpdateBy = "1"
MList.CreatedAt = timeNow
MList.UpdatedAt = timeNow
// MList.MenuId, err = MList.Create(db)
err = tx.Create(&MList).Error
if err != nil {
return err
}
MCreate := Menu{}
MCreate.MenuName = ""
MCreate.Title = "创建{{.TableComment}}"
MCreate.Icon = ""
MCreate.Path = "{{.TBName}}"
MCreate.MenuType = "F"
MCreate.Action = "无"
MCreate.Permission = "{{.PackageName}}:{{.BusinessName}}:add"
MCreate.ParentId = Cmenu.MenuId
MCreate.NoCache = false
MCreate.Sort = 0
MCreate.Visible = "0"
MCreate.IsFrame = "0"
MCreate.CreateBy = "1"
MCreate.UpdateBy = "1"
MCreate.CreatedAt = timeNow
MCreate.UpdatedAt = timeNow
// MCreate.MenuId, err = MCreate.Create(db)
err = tx.Create(&MCreate).Error
if err != nil {
return err
}
MUpdate := Menu{}
MUpdate.MenuName = ""
MUpdate.Title = "修改{{.TableComment}}"
MUpdate.Icon = ""
MUpdate.Path = "{{.TBName}}"
MUpdate.MenuType = "F"
MUpdate.Action = "无"
MUpdate.Permission ="{{.PackageName}}:{{.BusinessName}}:edit"
MUpdate.ParentId = Cmenu.MenuId
MUpdate.NoCache = false
MUpdate.Sort = 0
MUpdate.Visible = "0"
MUpdate.IsFrame = "0"
MUpdate.CreateBy = "1"
MUpdate.UpdateBy = "1"
MUpdate.CreatedAt = timeNow
MUpdate.UpdatedAt = timeNow
// MUpdate.MenuId, err = MUpdate.Create(db)
err = tx.Create(&MUpdate).Error
if err != nil {
return err
}
MDelete := Menu{}
MDelete.MenuName = ""
MDelete.Title = "删除{{.TableComment}}"
MDelete.Icon = ""
MDelete.Path = "{{.TBName}}"
MDelete.MenuType = "F"
MDelete.Action = "无"
MDelete.Permission = "{{.PackageName}}:{{.BusinessName}}:remove"
MDelete.ParentId = Cmenu.MenuId
MDelete.NoCache = false
MDelete.Sort = 0
MDelete.Visible = "0"
MDelete.IsFrame = "0"
MDelete.CreateBy = "1"
MDelete.UpdateBy = "1"
MDelete.CreatedAt = timeNow
MDelete.UpdatedAt = timeNow
// MDelete.MenuId, err = MDelete.Create(db)
err = tx.Create(&MDelete).Error
if err != nil {
return err
}
var InterfaceId = 63
Amenu := Menu{}
Amenu.MenuName = "{{.TBName}}"
Amenu.Title = "{{.TableComment}}"
Amenu.Icon = "bug"
Amenu.Path = "{{.TBName}}"
Amenu.MenuType = "M"
Amenu.Action = "无"
Amenu.ParentId = InterfaceId
Amenu.NoCache = false
Amenu.Sort = 0
Amenu.Visible = "1"
Amenu.IsFrame = "0"
Amenu.CreateBy = "1"
Amenu.UpdateBy = "1"
Amenu.CreatedAt = timeNow
Amenu.UpdatedAt = timeNow
// Amenu.MenuId, err = Amenu.Create(db)
err = tx.Create(&Amenu).Error
if err != nil {
return err
}
AList := Menu{}
AList.MenuName = ""
AList.Title = "分页获取{{.TableComment}}"
AList.Icon = "bug"
AList.Path = "/api/v1/{{.ModuleName}}"
AList.MenuType = "A"
AList.Action = "GET"
AList.ParentId = Amenu.MenuId
AList.NoCache = false
AList.Sort = 0
AList.Visible = "1"
AList.IsFrame = "0"
AList.CreateBy = "1"
AList.UpdateBy = "1"
AList.CreatedAt = timeNow
AList.UpdatedAt = timeNow
// AList.MenuId, err = AList.Create(db)
err = tx.Create(&AList).Error
if err != nil {
return err
}
AGet := Menu{}
AGet.MenuName = ""
AGet.Title = "根据id获取{{.TableComment}}"
AGet.Icon = "bug"
AGet.Path = "/api/v1/{{.ModuleName}}/:id"
AGet.MenuType = "A"
AGet.Action = "GET"
AGet.ParentId = Amenu.MenuId
AGet.NoCache = false
AGet.Sort = 0
AGet.Visible = "1"
AGet.IsFrame = "0"
AGet.CreateBy = "1"
AGet.UpdateBy = "1"
AGet.CreatedAt = timeNow
AGet.UpdatedAt = timeNow
// AGet.MenuId, err = AGet.Create(db)
err = tx.Create(&AGet).Error
if err != nil {
return err
}
ACreate := Menu{}
ACreate.MenuName = ""
ACreate.Title = "创建{{.TableComment}}"
ACreate.Icon = "bug"
ACreate.Path = "/api/v1/{{.ModuleName}}"
ACreate.MenuType = "A"
ACreate.Action = "POST"
ACreate.ParentId = Amenu.MenuId
ACreate.NoCache = false
ACreate.Sort = 0
ACreate.Visible = "1"
ACreate.IsFrame = "0"
ACreate.CreateBy = "1"
ACreate.UpdateBy = "1"
ACreate.CreatedAt = timeNow
ACreate.UpdatedAt = timeNow
// ACreate.MenuId, err = ACreate.Create(db)
err = tx.Create(&ACreate).Error
if err != nil {
return err
}
AUpdate := Menu{}
AUpdate.MenuName = ""
AUpdate.Title = "修改{{.TableComment}}"
AUpdate.Icon = "bug"
AUpdate.Path = "/api/v1/{{.ModuleName}}/:id"
AUpdate.MenuType = "A"
AUpdate.Action = "PUT"
AUpdate.ParentId = Amenu.MenuId
AUpdate.NoCache = false
AUpdate.Sort = 0
AUpdate.Visible = "1"
AUpdate.IsFrame = "0"
AUpdate.CreateBy = "1"
AUpdate.UpdateBy = "1"
AUpdate.CreatedAt = timeNow
AUpdate.UpdatedAt = timeNow
// AUpdate.MenuId, err = AUpdate.Create(db)
err = tx.Create(&AUpdate).Error
if err != nil {
return err
}
ADelete := Menu{}
ADelete.MenuName = ""
ADelete.Title = "删除{{.TableComment}}"
ADelete.Icon = "bug"
ADelete.Path = "/api/v1/{{.ModuleName}}"
ADelete.MenuType = "A"
ADelete.Action = "DELETE"
ADelete.ParentId = Amenu.MenuId
ADelete.NoCache = false
ADelete.Sort = 0
ADelete.Visible = "1"
ADelete.IsFrame = "0"
ADelete.CreateBy = "1"
ADelete.UpdateBy = "1"
ADelete.CreatedAt = timeNow
ADelete.UpdatedAt = timeNow
//ADelete.MenuId, err = ADelete.Create(db)
err = tx.Create(&ADelete).Error
if err != nil {
return err
}
return tx.Create(&common.Migration{
Version: version,
}).Error
})
}
+9 -9
View File
@@ -2,10 +2,10 @@ package dto
import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/api"
"go-admin/app/{{.PackageName}}/models"
"go-admin/common/dto"
"go-admin/common/apis"
common "go-admin/common/models"
)
@@ -30,10 +30,10 @@ func (m *{{.ClassName}}Search) Generate() dto.Index {
}
func (m *{{.ClassName}}Search) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
log.Warnf("ShouldBind error: %s", err.Error())
}
return err
}
@@ -60,15 +60,15 @@ func (s *{{.ClassName}}Control) Generate() dto.Control {
}
func (s *{{.ClassName}}Control) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
log.Warnf("ShouldBindUri error: %s", err.Error())
return err
}
err = ctx.ShouldBind(s)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
log.Warnf("ShouldBind error: %s", err.Error())
}
return err
}
@@ -108,15 +108,15 @@ func (s *{{.ClassName}}ById) GetId() interface{} {
}
func (s *{{.ClassName}}ById) Bind(ctx *gin.Context) error {
log := apis.GetRequestLogger(ctx)
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
log.Warnf("ShouldBindUri error: %s", err.Error())
return err
}
err = ctx.ShouldBind(s)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
log.Warnf("ShouldBind error: %s", err.Error())
}
return err
}
+16 -23
View File
@@ -5,10 +5,11 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/app/{{.PackageName}}/models"
"go-admin/app/{{.PackageName}}/service"
"go-admin/app/{{.PackageName}}/service/dto"
"go-admin/common/actions"
"go-admin/common/apis"
)
@@ -23,13 +24,10 @@ type {{.ClassName}} struct {
{{ $tablename := .TBName -}}
{{ range .Columns -}}
{{$z := .IsQuery}}
{{- if ($z) -}}
// @Param {{.JsonField}} query {{.GoType}} false "{{.ColumnComment}}"
{{ end -}}
{{- end }}
{{- if ($z) -}}// @Param {{.JsonField}} query {{.GoType}} false "{{.ColumnComment}}"{{ end -}}{{- end }}
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.{{.ClassName}}}} "{"code": 200, "data": [...]}"
// @Router /api/v1/{{.ModuleName}} [get]
// @Security Bearer
// Get{{.ClassName}}List 获取{{.TableComment}}列表
@@ -72,9 +70,8 @@ func (e *{{.ClassName}}) Get{{.ClassName}}List(c *gin.Context) {
// @Description 获取{{.TableComment}}
// @Tags {{.TableComment}}
// @Param id path string false "id"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /api/v1/{{.ModuleName}} [get]
// @Success 200 {object} response.Response{data=models.{{.ClassName}}} "{"code": 200, "data": [...]}"
// @Router /api/v1/{{.ModuleName}}/{id} [get]
// @Security Bearer
// Get{{.ClassName}} 获取{{.TableComment}}
func (e *{{.ClassName}}) Get{{.ClassName}}(c *gin.Context) {
@@ -118,9 +115,8 @@ func (e *{{.ClassName}}) Get{{.ClassName}}(c *gin.Context) {
// @Accept application/json
// @Product application/json
// @Param data body dto.{{.ClassName}}Control true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/{{.ClassName}} [post]
// @Success 200 {object} response.Response "{"code": 200, "message": "添加成功"}"
// @Router /api/v1/{{.ModuleName}} [post]
// Insert{{.ClassName}} 创建{{.TableComment}}
func (e *{{.ClassName}}) Insert{{.ClassName}}(c *gin.Context) {
log := e.GetLogger(c)
@@ -151,7 +147,7 @@ func (e *{{.ClassName}}) Insert{{.ClassName}}(c *gin.Context) {
service{{.ClassName}} := service.{{.ClassName}}{}
service{{.ClassName}}.Orm = db
service{{.ClassName}}.Log = log
err = service{{.ClassName}}.Insert{{.ClassName}}(object.(*(models.{{.ClassName}})))
err = service{{.ClassName}}.Insert{{.ClassName}}(object.(*models.{{.ClassName}}))
if err != nil {
log.Errorf("Insert {{.ClassName}} error, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "创建失败")
@@ -167,9 +163,8 @@ func (e *{{.ClassName}}) Insert{{.ClassName}}(c *gin.Context) {
// @Accept application/json
// @Product application/json
// @Param data body dto.{{.ClassName}}Control true "body"
// @Success 200 {string} string "{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string "{"code": -1, "message": "修改失败"}"
// @Router /api/v1/{{.ClassName}} [put]
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
// @Router /api/v1/{{.ModuleName}} [put]
// Update{{.ClassName}} 修改{{.TableComment}}
func (e *{{.ClassName}}) Update{{.ClassName}}(c *gin.Context) {
log := e.GetLogger(c)
@@ -214,11 +209,9 @@ func (e *{{.ClassName}}) Update{{.ClassName}}(c *gin.Context) {
// @Summary 删除{{.TableComment}}
// @Description 删除{{.TableComment}}
// @Tags {{.TableComment}}
// @Param id path int false "id"
// @Param ids body string false "ids"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/{{.ClassName}}/{id} [delete]
// @Param ids body []int false "ids"
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
// @Router /api/v1/{{.ModuleName}} [delete]
// Delete{{.ClassName}} 删除{{.TableComment}}
func (e *{{.ClassName}}) Delete{{.ClassName}}(c *gin.Context) {
log := e.GetLogger(c)
@@ -4,7 +4,7 @@ import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/{{.ModuleName}}"
"go-admin/app/{{.PackageName}}/apis/{{.ModuleName}}"
"go-admin/common/middleware"
)
@@ -23,4 +23,4 @@ func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJW
r.PUT("/:id", api.Update{{.ClassName}})
r.DELETE("", api.Delete{{.ClassName}})
}
}
}
@@ -4,7 +4,7 @@ import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/apis/{{.ModuleName}}"
"go-admin/app/{{.PackageName}}/apis/{{.ModuleName}}"
)
func init() {
@@ -22,4 +22,4 @@ func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJW
r.PUT("/:id", api.Update{{.ClassName}})
r.DELETE("", api.Delete{{.ClassName}})
}
}
}
+2 -2
View File
@@ -5,10 +5,10 @@ import (
"gorm.io/gorm"
"go-admin/app/admin/models"
"go-admin/app/{{.PackageName}}/models"
"go-admin/common/actions"
cDto "go-admin/common/dto"
"go-admin/app/admin/service/dto"
"go-admin/app/{{.PackageName}}/service/dto"
"go-admin/common/service"
)