Compare commits

..
Author SHA1 Message Date
wenjianzhang badeda69b7 Merge pull request #726 from dongzhiwei-git/dev
refactor🎨:优化sys_config相关代码
2022-12-30 23:55:17 +08:00
dongzhiwei d4cfd2d031 refactor🎨:优化sys_config相关代码 2022-11-30 18:48:07 +08:00
139 changed files with 1385 additions and 5121 deletions
-8
View File
@@ -1,8 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: 🆕 Create new issue
url: http://new-issue.go-admin.dev
about: The issue which is not created via http://new-issue.go-admin.dev will be closed immediately.
- name: 🆕 创建一个新 Issue
url: http://new-issue.go-admin.dev
about: 不是用 http://new-issue.go-admin.dev 创建的 issue 会被机器人自动关闭。
-66
View File
@@ -1,66 +0,0 @@
<!--
First of all, thank you for your contribution! 😄
For requesting to pull a new feature or bugfix, please send it from a feature/bugfix branch based on the `master` branch.
Before submitting your pull request, please make sure the checklist below is confirmed.
Your pull requests will be merged after one of the collaborators approve.
Thank you!
-->
[[中文版模板 / Chinese template](https://github.com/go-admin-team/go-admin/blob/master/.github/PULL_REQUEST_TEMPLATE/pr_cn.md)]
### 🤔 This is a ...
- [ ] New feature
- [ ] Bug fix
- [ ] Site / documentation update
- [ ] Demo update
- [ ] Component style update
- [ ] TypeScript definition update
- [ ] Bundle size optimization
- [ ] Performance optimization
- [ ] Enhancement feature
- [ ] Internationalization
- [ ] Refactoring
- [ ] Code style optimization
- [ ] Test Case
- [ ] Branch merge
- [ ] Other (about what?)
### 🔗 Related issue link
<!--
1. Put the related issue or discussion links here.
-->
### 💡 Background and solution
<!--
1. Describe the problem and the scenario.
2. GIF or snapshot should be provided if includes UI/interactive modification.
3. How to fix the problem, and list the final API implementation and usage sample if that is a new feature.
-->
### 📝 Changelog
<!--
Describe changes from the user side, and list all potential break changes or other risks.
--->
| Language | Changelog |
| ---------- | --------- |
| 🇺🇸 English | |
| 🇨🇳 Chinese | |
### ☑️ Self-Check before Merge
⚠️ Please check all items below before review. ⚠️
- [ ] Doc is updated/provided or not needed
- [ ] Demo is updated/provided or not needed
- [ ] TypeScript's definition is updated/provided or not needed
- [ ] Changelog is provided or not needed
-61
View File
@@ -1,61 +0,0 @@
<!--
首先,感谢你的贡献!😄
新特性请提交至 feature 分支,其余可提交至 master 分支。
在维护者审核通过后会合并。
请确保填写以下 pull request 的信息,谢谢!~
-->
[[English Template / 英文模板](https://github.com/go-admin-team/go-admin/blob/master/.github/PULL_REQUEST_TEMPLATE.md)]
### 🤔 这个变动的性质是?
- [ ] 新特性提交
- [ ] 日常 bug 修复
- [ ] 站点、文档改进
- [ ] 演示代码改进
- [ ] 组件样式/交互改进
- [ ] TypeScript 定义更新
- [ ] 包体积优化
- [ ] 性能优化
- [ ] 功能增强
- [ ] 国际化改进
- [ ] 重构
- [ ] 代码风格优化
- [ ] 测试用例
- [ ] 分支合并
- [ ] 其他改动(是关于什么的改动?)
### 🔗 相关 Issue
<!--
1. 描述相关需求的来源,如相关的 issue 讨论链接。
-->
### 💡 需求背景和解决方案
<!--
1. 要解决的具体问题。
2. 列出最终的 API 实现和用法。
3. 涉及UI/交互变动需要有截图或 GIF。
-->
### 📝 更新日志
<!--
从用户角度描述具体变化,以及可能的 breaking change 和其他风险。
-->
| 语言 | 更新描述 |
| ------- | -------- |
| 🇺🇸 英文 | |
| 🇨🇳 中文 | |
### ☑️ 请求合并前的自查清单
⚠️ 请自检并全部**勾选全部选项**。⚠️
- [ ] 文档已补充或无须补充
- [ ] 代码演示已提供或无须提供
- [ ] TypeScript 定义已补充或无须补充
- [ ] Changelog 已提供或无须提供
-63
View File
@@ -1,63 +0,0 @@
name: Build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
env:
IMAGE_NAME: registry.ap-northeast-1.aliyuncs.com/go-admin/go-admin-api # 镜像名称
TAG: ${{ github.sha }}
IMAGE_NAME_TAG: registry.ap-northeast-1.aliyuncs.com/go-admin/go-admin-api:${{ github.sha }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: 1.26.5
- name: Tidy
run: go mod tidy
- name: Build
run: env CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -tags "sqlite3,json1" --ldflags "-extldflags -static" -o main .
# 以下推镜像与重启步骤仅在 master 收到 push 时执行。
# pull_request 事件同样会触发本工作流,若不加限制,任何指向 master 的
# PR 一经创建就会把 PR 分支的镜像推上仓库,并直接重启线上 API 服务,
# 且发生在合并之前。构建与编译校验不受影响,PR 仍会执行。
- name: Build the Docker image and push
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: |
docker login --username=${{ secrets.DOCKER_USERNAME }} registry.ap-northeast-1.aliyuncs.com --password=${{ secrets.DOCKER_PASSWORD }}
echo "************ docker login end"
docker build -t go-admin-api:latest .
echo "************ docker build end"
docker tag go-admin-api ${{ env.IMAGE_NAME_TAG }}
echo "************ docker tag end"
docker images
echo "************ docker images end"
docker push ${{ env.IMAGE_NAME_TAG }} # 推送
echo "************ docker push end"
- name: Restart server # 第五步,重启服务
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
uses: appleboy/ssh-action@0ff4204d59e8e51228ff73bce53f80d53301dee2 # v1.2.5
env:
GITHUB_SHA_X: ${GITHUB_SHA}
with:
host: ${{ secrets.SSH_HOST }} # 下面三个配置与上一步类似
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.DEPLOY_KEY }}
# 重启的脚本,根据自身情况做相应改动,一般要做的是migrate数据库以及重启服务器
script: |
sudo docker rm -f go-admin-api
sudo docker login --username=${{ secrets.DOCKER_USERNAME }} registry.ap-northeast-1.aliyuncs.com --password=${{ secrets.DOCKER_PASSWORD }}
sudo docker run -d -p 8000:8000 --name go-admin-api ${{ env.IMAGE_NAME_TAG }}
+4 -4
View File
@@ -19,11 +19,11 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -34,7 +34,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -48,4 +48,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
uses: github/codeql-action/analyze@v1
+10 -15
View File
@@ -3,7 +3,6 @@ name: build
on:
push:
branches: [ master, dev ]
tags: [ 'v*', '[0-9]*' ]
pull_request:
branches: [ master ]
env:
@@ -17,27 +16,23 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.26
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
- name: Set up Go 1.15
uses: actions/setup-go@v3
with:
go-version: 1.26.5
go-version: 1.15
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
uses: actions/checkout@v3
- name: Get dependencies
run: go mod tidy
- name: Build
run: make build
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
if: startsWith(github.ref, 'refs/tags/')
- name: Log in to the Container registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
if: startsWith(github.ref, 'refs/tags/')
uses: docker/login-action@v2
if: startsWith(${{github.ref}}, 'refs/tags/')
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -45,8 +40,8 @@ jobs:
- name: Extract metadata (tags, labels) for Docker
id: meta
if: startsWith(github.ref, 'refs/tags/')
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
if: startsWith(${{github.ref}}, 'refs/tags/')
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
flavor: |
@@ -57,8 +52,8 @@ jobs:
type=sha,prefix=,format=long,enable=true,priority=100
- name: Build and push Docker image
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
if: startsWith(github.ref, 'refs/tags/')
uses: docker/build-push-action@v3
if: startsWith(${{github.ref}}, 'refs/tags/')
with:
context: .
file: scripts/Dockerfile
+4 -8
View File
@@ -7,11 +7,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
uses: actions/checkout@v1
- name: 'Mirror to gitee'
uses: pixta-dev/repository-mirroring-action@674e65a7d483ca28dafaacba0d07351bdcc8bd75 # v1
uses: pixta-dev/repository-mirroring-action@v1
with:
target_repo_url:
git@gitee.com:go-admin-team/go-admin.git
@@ -21,11 +19,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
uses: actions/checkout@v1
- name: 'Mirror to gitlab'
uses: pixta-dev/repository-mirroring-action@674e65a7d483ca28dafaacba0d07351bdcc8bd75 # v1
uses: pixta-dev/repository-mirroring-action@v1
with:
target_repo_url:
git@gitlab.com:go-admin-team/go-admin.git
+6 -7
View File
@@ -1,15 +1,15 @@
.idea
.vscode
.DS_Store
*/.DS_Store
static/uploadfile
main.exe
*.exe
go-admin
go-admin.exe
temp/
!temp
vendor
config/settings.dev.yml
go-admin
common/middleware/demo.go
config/settings.dev.*.yml
config/settings.dev.*.yml.log
temp/logs
@@ -17,9 +17,8 @@ config/settings.dev.yml.log
config/settings.b.dev.yml
cmd/migrate/migration/version-local/*
!cmd/migrate/migration/version-local/doc.go
*/.DS_Store
# go sum
go.sum
config/settings.deva.yml
go-admin-server
CLAUDE.md
.claude/
config/settings.local.dev.yml
-206
View File
@@ -1,206 +0,0 @@
# AGENTS.md — go-admin 后端
> 给 AI 编码工具与新贡献者的约定。**只写"不遵守就会出错"的规则**;技术栈版本以
> `go.mod` 为准,命令以 `Makefile` 为准,此处不复述,避免与代码脱节。
>
> 标准 CRUD 模块的完整写法见 **`app/demo/`** —— 那是可编译、有测试、CI 会跑的参照物。
> 本文与它冲突时,以 `app/demo/` 为准。
## 分层
```
Router → Api → Service → Model
路由注册 参数绑定 业务逻辑 GORM 结构体
中间件链 调用 Service 操作数据库 TableName()
```
对应目录:`app/{模块}/router|apis|service|models`,DTO 位于 `service/dto`。
**不可跨层**:Api 不直接操作 `Orm`,Service 不接触 `gin.Context`。
## 优先使用通用 Action
单表 CRUD **不要手写 Handler 与 Service**。`common/actions` 提供的五个
Action 已覆盖参数绑定、数据权限过滤、操作人注入、分页与错误响应:
```go
r := v1.Group("/demo-product").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
m := &models.DemoProduct{}
r.GET("", actions.PermissionAction(), actions.IndexAction(m, new(dto.DemoProductSearch), func() interface{} {
list := make([]models.DemoProduct, 0); return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.DemoProductById), func() interface{} {
return &models.DemoProduct{}
}))
r.POST("", actions.CreateAction(new(dto.DemoProductControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.DemoProductControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.DemoProductById)))
}
```
这样一个模块只需 **model + dto + router** 三个文件,完整示例见 `app/demo/`。
使用通用 Action 的前提:
- Model 实现 `models.ActiveRecord`(`Generate` / `GetId` / `TableName`)
- 列表 DTO 实现 `dto.Index`,增改删 DTO 实现 `dto.Control`
- **所有 `Generate()` 必须返回副本** —— Action 在并发请求间复用实例,
就地返回会串数据(`app/demo` 的测试锁定了这一点)
- 详情/删除 DTO 内嵌 `dto.ObjectById` 即可继承 `Bind` 与 `GetId`,无需重写
仅当业务超出单表 CRUD(跨表事务、外部调用、复杂校验)时才自行编写 Handler
与 Service,写法见下。
## Api 层(仅在通用 Action 不适用时)
结构体嵌入 `api.Api`,链式初始化后**必须检查 `Errors`**:
```go
func (e SysPost) GetPage(c *gin.Context) {
s := service.SysPost{}
req := dto.SysPostPageReq{}
err := e.MakeContext(c).MakeOrm().Bind(&req, binding.Form).MakeService(&s.Service).Errors
if err != nil {
e.Logger.Error(err)
e.Error(500, err, err.Error())
return
}
// ... 调用 s.GetPage(...)
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
```
响应一律走 `e.OK` / `e.PageOK` / `e.Error`,不要自行 `c.JSON`。
## Service 层(仅在通用 Action 不适用时)
结构体嵌入 `service.Service`(持有 `Orm` 与 `Log`)。查询通过 Scopes 组合:
```go
err = e.Orm.Model(&data).Scopes(
cDto.MakeCondition(c.GetNeedSearch()), // 由 search tag 生成 WHERE
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
actions.Permission(data.TableName(), p), // 数据权限,列表/详情必须带
).Find(list).Limit(-1).Offset(-1).Count(count).Error
```
**遗漏 `actions.Permission` 会使数据权限配置静默失效** —— 这是最容易出的错。
错误一律 `return err` 向上传递,日志用 `e.Log.Errorf`,不使用 `panic`。
## DTO
搜索条件由 tag 声明,`MakeCondition` 据此拼 SQL:
```go
type SysPostPageReq struct {
dto.Pagination `search:"-"`
PostName string `form:"postName" search:"type:contains;column:post_name;table:sys_post"`
}
func (m *SysPostPageReq) GetNeedSearch() interface{} { return *m }
```
`type` 可选:`exact` `iexact` `contains` `gt` `gte` `lt` `lte` `order` `left`(联表)。
## Model
```go
type SysPost struct {
PostId int `gorm:"primaryKey;autoIncrement" json:"postId"`
// ... 业务字段
models.ControlBy // CreateBy / UpdateBy
models.ModelTime // CreatedAt / UpdatedAt / DeletedAt
}
func (SysPost) TableName() string { return "sys_post" }
```
`TableName()` 必须显式声明(GORM 配置了 `SingularTable`,不会自动推导复数)。
## 路由注册
通过 `init()` 自注册,不在中心文件手工添加:
```go
func init() { routerCheckRole = append(routerCheckRole, registerSysPostRouter) }
func registerSysPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := apis.SysPost{}
r := v1.Group("/post").
Use(authMiddleware.MiddlewareFunc()).
Use(middleware.AuthCheckRole()). // Casbin 鉴权
Use(actions.PermissionAction()) // 注入数据权限
{ r.GET("", api.GetPage); r.POST("", api.Insert); /* ... */ }
}
```
新增路由文件后,需确认 `cmd/api/` 中已用 `_` 导入该包。
## 命名
| 对象 | 规则 | 示例 |
|---|---|---|
| 数据表 | `sys_` 前缀 + 下划线 | `sys_post` |
| API 路径 | `/api/v1/` + kebab-case | `/api/v1/sys-user` |
| DTO | `{Model}{Action}Req` | `SysPostPageReq` |
| 权限标识 | `模块:资源:操作` | `admin:sysPost:add` |
权限标识需与前端 `v-permisaction` 一致,并写入 `sys_menu` 种子数据。
## Swagger
Handler 必须带完整注解,`go generate` 会据此生成文档:
```go
// @Summary 岗位列表
// @Tags 岗位
// @Success 200 {object} response.Response
// @Router /api/v1/post [get]
// @Security Bearer
```
## 本地运行
**配置 `driver: sqlite3` 时必须带构建标签**,否则启动即 panic:
```bash
go run -tags sqlite3 . migrate -c config/settings.sqlite.yml
go run -tags sqlite3 . server -c config/settings.sqlite.yml
```
原因:`common/database/open.go` 带 `//go:build !sqlite3`,不加标签时编进的是
不含 sqlite3 的版本,`opens["sqlite3"]` 为 nil,调用时在 nil 函数上崩溃。
报错信息不会提到构建标签,容易误判成环境损坏。MySQL / PostgreSQL 无此问题。
对应 `Makefile` 的 `build-sqlite` 目标。
## 数据库迁移
文件名前 13 位为时间戳版本号。**已执行过的迁移文件不可修改** ——
`sys_migration` 表按版本号去重,改动不会重跑,只能新增一个迁移来修正。
放哪个目录取决于身份:
| 目录 | 用途 | 是否入库 |
|---|---|---|
| `version/` | 框架自带迁移,随仓库分发给所有使用者 | 是 |
| `version-local/` | 使用者自己项目的迁移 | 否(已在 `.gitignore`) |
**向本仓库提交迁移必须放 `version/`** —— 放进 `version-local/` 会被忽略掉,
`git status` 看不到,PR 里也不会出现。两个目录的包名分别是 `version` 与
`version_local`(后者与目录名不一致,因为标识符不能含连字符)。
## 提交规范
格式 `type+emoji: 描述`:
`feat✨` `fix🐛` `style💄` `docs📝` `perf👌` `test✅` `refactor🎨` `chore🔧`
一个提交只做一件事。改动跨越多个语义时拆分提交,不要混在一起。
## 红线
- 不使用全局 DB 变量,一律用 `e.Orm`(来自请求上下文,多租户依赖它)
- 不在 Service 中引用 `gin.Context`
- 生产部署前确认 `mode: prod` 且已修改 `jwt.secret`(dev 模式下 token 几乎不过期)
- 不提交 `config/settings.yml` 中的真实凭据
+22 -12
View File
@@ -1,18 +1,28 @@
FROM golang:alpine as builder
MAINTAINER lwnmengjing
ENV GOPROXY https://goproxy.cn/
WORKDIR /go/release
#RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk update && apk add tzdata
COPY go.mod ./go.mod
RUN go mod tidy
COPY . .
RUN pwd && ls
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -a -installsuffix cgo -o go-admin .
FROM alpine
# ENV GOPROXY https://goproxy.cn/
COPY --from=builder /go/release/go-admin /
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
COPY --from=builder /go/release/config/settings.yml /config/settings.yml
RUN apk update --no-cache
RUN apk add --update gcc g++ libc6-compat
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
COPY ./main /main
COPY ./config/settings.demo.yml /config/settings.yml
COPY ./go-admin-db.db /go-admin-db.db
EXPOSE 8000
RUN chmod +x /main
CMD ["/main","server","-c", "/config/settings.yml"]
CMD ["/go-admin","server","-c", "/config/settings.yml"]
-28
View File
@@ -1,28 +0,0 @@
FROM golang:alpine as builder
MAINTAINER lwnmengjing
ENV GOPROXY https://goproxy.cn/
WORKDIR /go/release
#RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk update && apk add tzdata
COPY go.mod ./go.mod
RUN go mod tidy
COPY . .
RUN pwd && ls
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -a -installsuffix cgo -o go-admin .
FROM alpine
COPY --from=builder /go/release/go-admin /
COPY --from=builder /go/release/config/settings.yml /config/settings.yml
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
EXPOSE 8000
CMD ["/go-admin","server","-c", "/config/settings.yml"]
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2026 go-admin-team
Copyright (c) 2020 go-admin-team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+2 -40
View File
@@ -2,41 +2,11 @@ PROJECT:=go-admin
.PHONY: build
build:
CGO_ENABLED=0 go build -ldflags="-w -s" -a -installsuffix "" -o go-admin .
# make build-linux
CGO_ENABLED=0 go build -ldflags="-w -s" -a -installsuffix -o go-admin .
build-linux:
@docker build -t go-admin:latest .
@echo "build successful"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -a -installsuffix -o go-admin .
build-sqlite:
go build -tags sqlite3 -ldflags="-w -s" -a -installsuffix -o go-admin .
# make run
run:
# delete go-admin-api container
@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker rm -f go-admin; fi
# 启动方法一 run go-admin-api container docker-compose 启动方式
# 进入到项目根目录 执行 make run 命令
@docker-compose up -d
# 启动方式二 docker run 这里注意-v挂载的宿主机的地址改为部署时的实际绝对路径
#@docker run --name=go-admin -p 8000:8000 -v /home/code/go/src/go-admin/go-admin/config:/go-admin-api/config -v /home/code/go/src/go-admin/go-admin-api/static:/go-admin/static -v /home/code/go/src/go-admin/go-admin/temp:/go-admin-api/temp -d --restart=always go-admin:latest
@echo "go-admin service is running..."
# delete Tag=<none> 的镜像
@docker image prune -f
@docker ps -a | grep "go-admin"
stop:
# delete go-admin-api container
@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker-compose down; fi
#@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker rm -f go-admin; fi
#@echo "go-admin stop success"
#.PHONY: test
#test:
# go test -v ./... -cover
@@ -44,11 +14,3 @@ stop:
#.PHONY: docker
#docker:
# docker build . -t go-admin:latest
# make deploy
deploy:
#@git checkout master
#@git pull origin master
make build-linux
make run
+38 -96
View File
@@ -1,6 +1,6 @@
# go-admin
<img align="right" width="320" src="https://doc-image.zhangwj.com/img/go-admin.svg">
<img align="right" width="320" src="https://raw.githubusercontent.com/wenjianzhang/image/a44d60756c9fdedbd70f6bff076a31cbf314936a/img/go-admin.svg">
[![Build Status](https://github.com/wenjianzhang/go-admin/workflows/build/badge.svg)](https://github.com/go-admin-team/go-admin)
@@ -9,22 +9,18 @@
[English](https://github.com/go-admin-team/go-admin/blob/master/README.md) | 简体中文
基于Gin + Vue + Element UI OR Arco Design OR Ant Design的前后端分离权限管理系统,系统初始化极度简单,只需要配置文件中,修改数据库连接,系统支持多指令操作,迁移指令可以让初始化数据库信息变得更简单,服务指令可以很简单的启动api服务
基于Gin + Vue + Element UI的前后端分离权限管理系统,系统初始化极度简单,只需要配置文件中,修改数据库连接,系统支持多指令操作,迁移指令可以让初始化数据库信息变得更简单,服务指令可以很简单的启动api服务
[在线文档](https://www.go-admin.pro)
[在线文档](https://doc.go-admin.dev)
[github在线文档](https://wenjianzhang.github.io)
[gitee在线文档](http://mydearzwj.gitee.io/go-admin-doc/)
[前端项目](https://github.com/go-admin-team/go-admin-ui)
[视频教程](https://space.bilibili.com/565616721/channel/detail?cid=125737)
## 🎬 在线体验
Element Plus vue3 体验:[https://vue.go-admin.pro](https://vue.go-admin.pro/#/login)
> ⚠️⚠️⚠️ 账号 / 密码: admin / 123456
antd 体验(go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admin.pro/)
> ⚠️⚠️⚠️ 账号 / 密码: admin / 123456
## ✨ 特性
- 遵循 RESTful API 设计规范
@@ -104,14 +100,6 @@ antd 体验(go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admi
## 📦 本地开发
### 环境要求
go 1.26.5
node版本: v22+(推荐 v24 LTS)
包管理器: pnpm v9+(UI 项目使用 pnpm)
### 开发目录创建
```bash
@@ -142,22 +130,19 @@ git clone https://github.com/go-admin-team/go-admin-ui.git
# 进入 go-admin 后端项目
cd ./go-admin
# 更新整理依赖
go mod tidy
# 编译项目
go build
# 修改配置
# 文件路径 go-admin/config/settings.yml
vi ./config/settings.yml
vi ./config/setting.yml
# 1. 配置文件中修改数据库信息
# 注意: settings.database 下对应的配置数据
# 2. 确认log路径
```
⚠️注意 在windows环境如果没有安装中CGO,会出现这个问题;
:::tip ⚠️注意 在windows环境如果没有安装中CGO,会出现这个问题;
```bash
E:\go-admin>go build
@@ -175,6 +160,7 @@ cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
[解决cgo问题进入](https://doc.go-admin.dev/zh-CN/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
:::
#### 初始化数据库,以及服务启动
@@ -234,83 +220,43 @@ env GOOS=linux GOARCH=amd64 go build main.go
### UI交互端启动说明
```bash
# 安装 pnpm(若未安装)
npm install -g pnpm
# 安装依赖
pnpm install
npm install
# 国内网络可指定镜像源加速
pnpm install --registry=https://registry.npmmirror.com
# 建议不要直接使用 cnpm 安装依赖,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题
npm install --registry=https://registry.npm.taobao.org
# 启动服务
pnpm dev
npm run dev
```
## 🎬 在线体验
> admin / 123456
演示地址:[http://www.go-admin.dev](http://www.go-admin.dev/#/login)
## 📨 互动
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" 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>
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
</tr>
<tr>
<td>微信</td>
<td>公众号🔥🔥🔥</td>
<td><a target="_blank" href="https://qm.qq.com/cgi-bin/qm/qr?k=I8ZMqsExqCHpyu8SL4rbya700rBBXYLO&jump_from=webapi"><img border="0" src="//pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流甲号" title="go-admin技术交流甲号"></a></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>
<td>哔哩哔哩🔥🔥🔥</td>
</tr>
</table>
## 💎 贡献者
## 💎 主要成员
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<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 开源证书支持
@@ -320,20 +266,16 @@ pnpm dev
## 🤝 特别感谢
1. [ant-design](https://github.com/ant-design/ant-design)
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
2. [arco-design](https://github.com/arco-design/arco-design)
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
4. [gin](https://github.com/gin-gonic/gin)
5. [casbin](https://github.com/casbin/casbin)
6. [spf13/viper](https://github.com/spf13/viper)
7. [gorm](https://github.com/jinzhu/gorm)
8. [gin-swagger](https://github.com/swaggo/gin-swagger)
9. [jwt-go](https://github.com/dgrijalva/jwt-go)
10. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
11. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
12. [form-generator](https://github.com/JakHuang/form-generator)
1. [chengxiao](https://github.com/chengxiao)
2. [gin](https://github.com/gin-gonic/gin)
2. [casbin](https://github.com/casbin/casbin)
2. [spf13/viper](https://github.com/spf13/viper)
2. [gorm](https://github.com/jinzhu/gorm)
2. [gin-swagger](https://github.com/swaggo/gin-swagger)
2. [jwt-go](https://github.com/dgrijalva/jwt-go)
2. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
2. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
2. [form-generator](https://github.com/JakHuang/form-generator)
## 🤟 打赏
@@ -349,4 +291,4 @@ pnpm dev
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
Copyright (c) 2024 wenjianzhang
Copyright (c) 2020 wenjianzhang
+21 -86
View File
@@ -1,7 +1,7 @@
# go-admin
<img align="right" width="320" src="https://raw.githubusercontent.com/wenjianzhang/image/203c5930b9ed08d5cf2fcb4516b85e412f8e0e60/img/go-admin.svg">
<img align="right" width="320" src="https://raw.githubusercontent.com/wenjianzhang/image/a44d60756c9fdedbd70f6bff076a31cbf314936a/img/go-admin.svg">
[![Build Status](https://github.com/wenjianzhang/go-admin/workflows/build/badge.svg)](https://github.com/go-admin-team/go-admin)
@@ -10,22 +10,14 @@
English | [简体中文](https://github.com/go-admin-team/go-admin/blob/master/README.Zh-cn.md)
The front-end and back-end separation authority management system based on Gin + Vue + Element UI OR Arco Design is extremely simple to initialize the system. You only need to modify the database connection in the configuration file. The system supports multi-instruction operations. Migration instructions can make it easier to initialize database information. Service instructions It's easy to start the api service.
The front-end and back-end separation authority management system based on Gin + Vue + Element UI is extremely simple to initialize the system. You only need to modify the database connection in the configuration file. The system supports multi-instruction operations. Migration instructions can make it easier to initialize database information. Service instructions It's easy to start the api service.
[documentation](https://www.go-admin.dev)
[documentation](https://doc.go-admin.dev)
[Front-end project](https://github.com/go-admin-team/go-admin-ui)
[Video tutorial](https://space.bilibili.com/565616721/channel/detail?cid=125737)
## 🎬 Online Demo
Element Plus vue3 demo:[https://vue.go-admin.pro](https://vue.go-admin.pro/#/login)
> 账号 / 密码: admin / 123456
antd demo (go-admin-pro):[https://antd.go-admin.pro](https://antd.go-admin.pro/)
> 账号 / 密码: admin / 123456
>
## ✨ Feature
- Follow RESTful API design specifications
@@ -102,14 +94,6 @@ At the same time, a series of tutorials including videos and documents are provi
## 📦 Local development
### Environmental requirements
go 1.26.5
nodejs: v22+ (v24 LTS recommended)
package manager: pnpm v9+ (the UI project uses pnpm)
### Development directory creation
```bash
@@ -140,22 +124,19 @@ git clone https://github.com/go-admin-team/go-admin-ui.git
# Enter the go-admin backend project
cd ./go-admin
# Update dependencies
go mod tidy
# Compile the project
go build
# Change setting
# File path go-admin/config/settings.yml
vi ./config/settings.yml
vi ./config/setting.yml
# 1. Modify the database information in the configuration file
# Note: The corresponding configuration data under settings.database
# 2. Confirm the log path
```
:::tip ⚠️Note that this problem will occur if CGO is not installed in the windows10+ environment;
:::tip ⚠️Note that this problem will occur if CGO is not installed in the windows environment;
```bash
E:\go-admin>go build
@@ -226,79 +207,38 @@ env GOOS=linux GOARCH=amd64 go build main.go
### UI interactive terminal startup instructions
```bash
# Install pnpm if you don't have it
npm install -g pnpm
# Installation dependencies
pnpm install
npm install # or cnpm install
# Start service
pnpm dev
npm run dev
```
## 🎬 Online Demo
> admin / 123456
演示地址:[http://www.go-admin.dev](http://www.go-admin.dev/#/login)
## 📨 Interactive
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
</tr>
<tr>
<td>Wechat</td>
<td>Wechat公众号🔥🔥🔥</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>
<td>bilibili🔥🔥🔥</td>
</tr>
</table>
## 💎 Contributors
## 💎 Members
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
<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>
@@ -310,11 +250,7 @@ The `go-admin` project has always been developed in the GoLand integrated develo
## 🤝 Thanks
1. [ant-design](https://github.com/ant-design/ant-design)
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
2. [arco-design](https://github.com/arco-design/arco-design)
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
1. [chengxiao](https://github.com/chengxiao)
2. [gin](https://github.com/gin-gonic/gin)
2. [casbin](https://github.com/casbin/casbin)
2. [spf13/viper](https://github.com/spf13/viper)
@@ -332,11 +268,10 @@ The `go-admin` project has always been developed in the GoLand integrated develo
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
## 🤝 Link
- [Go developer growth roadmap](http://www.golangroadmap.com/)
- [mss-boot-io](https://docs.mss-boot-io.top/)
[Go developer growth roadmap](http://www.golangroadmap.com/)
## 🔑 License
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
Copyright (c) 2022 wenjianzhang
Copyright (c) 2020 wenjianzhang
+3 -3
View File
@@ -17,17 +17,17 @@ type System struct {
// @Success 200 {object} response.Response{data=string,id=string,msg=string} "{"code": 200, "data": [...]}"
// @Router /api/v1/captcha [get]
func (e System) GenerateCaptchaHandler(c *gin.Context) {
if err := e.MakeContext(c).Errors; err != nil {
err := e.MakeContext(c).Errors
if err != nil {
e.Error(500, err, "服务初始化失败!")
return
}
id, b64s, answer, err := captcha.DriverDigitFunc()
id, b64s, err := captcha.DriverDigitFunc()
if err != nil {
e.Logger.Errorf("DriverDigitFunc error, %s", err.Error())
e.Error(500, err, "验证码获取失败")
return
}
e.Logger.Infof("DriverDigitFunc answer: %s", answer)
e.Custom(gin.H{
"code": 200,
"data": b64s,
+6 -7
View File
@@ -11,14 +11,13 @@ const INDEX = `
<meta charset="utf-8">
<title>GO-ADMIN欢迎您</title>
<style>
html,body{
margin:0;
padding:0;
height:100%;
overflow-y:hidden;
body{
margin:0;
padding:0;
overflow-y:hidden
}
</style>
<script src="https://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
window.onerror=function(){return true;}
$(function(){
@@ -29,7 +28,7 @@ $(function(){
</script>
</head>
<body>
<iframe id="iframe" frameborder="0" src="https://www.go-admin.pro" style="width:100%;height:100%;"></iframe>
<iframe id="iframe" frameborder="0" src="https://doc.go-admin.dev" style="width:100%;"></iframe>
</body>
</html>
`
+2 -2
View File
@@ -198,7 +198,7 @@ func (e SysConfig) Get2SysApp(c *gin.Context) {
return
}
// 控制只读前台的数据
req.IsFrontend = "1"
req.IsFrontend = 1
list := make([]models.SysConfig, 0)
err = s.GetWithKeyList(&req, &list)
if err != nil {
@@ -310,4 +310,4 @@ func (e SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
return
}
e.OK(resp, s.Msg)
}
}
+2 -2
View File
@@ -187,7 +187,7 @@ func (e SysDept) Get2Tree(c *gin.Context) {
req := dto.SysDeptGetPageReq{}
err := e.MakeContext(c).
MakeOrm().
Bind(&req, binding.Form).
Bind(&req,binding.Form).
MakeService(&s.Service).
Errors
if err != nil {
@@ -235,4 +235,4 @@ func (e SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
"depts": result,
"checkedKeys": menuIds,
}, "")
}
}
+40 -2
View File
@@ -202,6 +202,44 @@ func (e SysMenu) GetMenuRole(c *gin.Context) {
e.OK(result, "")
}
//// GetMenuIDS 获取角色对应的菜单id数组
//// @Summary 获取角色对应的菜单id数组,设置角色权限使用
//// @Description 获取JSON
//// @Tags 菜单
//// @Param id path int true "id"
//// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
//// @Router /api/v1/menuids/{id} [get]
//// @Security Bearer
//func (e SysMenu) GetMenuIDS(c *gin.Context) {
// s := new(service.SysMenu)
// r := service.SysRole{}
// m := dto.SysRoleByName{}
// err := e.MakeContext(c).
// MakeOrm().
// Bind(&m, binding.JSON).
// MakeService(&s.Service).
// MakeService(&r.Service).
// Errors
// if err != nil {
// e.Logger.Error(err)
// e.Error(500, err, err.Error())
// return
// }
// var data models.SysRole
// err = r.GetWithName(&m, &data).Error
//
// //data.RoleName = c.GetString("role")
// //data.UpdateBy = user.GetUserId(c)
// //result, err := data.GetIDS(s.Orm)
//
// if err != nil {
// e.Logger.Errorf("GetIDS error, %s", err.Error())
// e.Error(500, err, "获取失败")
// return
// }
// e.OK(result, "")
//}
// GetMenuTreeSelect 根据角色ID查询菜单下拉树结构
// @Summary 角色修改使用的菜单列表
// @Description 获取JSON
@@ -215,7 +253,7 @@ func (e SysMenu) GetMenuRole(c *gin.Context) {
func (e SysMenu) GetMenuTreeSelect(c *gin.Context) {
m := service.SysMenu{}
r := service.SysRole{}
req := dto.SelectRole{}
req :=dto.SelectRole{}
err := e.MakeContext(c).
MakeOrm().
MakeService(&m.Service).
@@ -246,4 +284,4 @@ func (e SysMenu) GetMenuTreeSelect(c *gin.Context) {
"menus": result,
"checkedKeys": menuIds,
}, "获取成功")
}
}
+4 -17
View File
@@ -2,7 +2,6 @@ package apis
import (
"fmt"
"go-admin/common/global"
"net/http"
"github.com/gin-gonic/gin/binding"
@@ -122,19 +121,14 @@ func (e SysRole) Insert(c *gin.Context) {
if req.Status == "" {
req.Status = "2"
}
cb := sdk.Runtime.GetCasbinByTenant(c.Request.Host)
cb := sdk.Runtime.GetCasbinKey(c.Request.Host)
err = s.Insert(&req, cb)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "创建失败,"+err.Error())
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "创建失败,"+err.Error())
return
}
e.OK(req.GetId(), "创建成功")
}
@@ -161,7 +155,7 @@ func (e SysRole) Update(c *gin.Context) {
e.Error(500, err, err.Error())
return
}
cb := sdk.Runtime.GetCasbinByTenant(c.Request.Host)
cb := sdk.Runtime.GetCasbinKey(c.Request.Host)
req.SetUpdateBy(user.GetUserId(c))
@@ -171,13 +165,6 @@ func (e SysRole) Update(c *gin.Context) {
return
}
_, err = global.LoadPolicy(c)
if err != nil {
e.Logger.Error(err)
e.Error(500, err, "更新失败,"+err.Error())
return
}
e.OK(req.GetId(), "更新成功")
}
@@ -203,7 +190,7 @@ func (e SysRole) Delete(c *gin.Context) {
return
}
cb := sdk.Runtime.GetCasbinByTenant(c.Request.Host)
cb := sdk.Runtime.GetCasbinKey(c.Request.Host)
err = s.Remove(&req, cb)
if err != nil {
e.Logger.Error(err)
+17 -9
View File
@@ -2,8 +2,8 @@ package apis
import (
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/config"
"go-admin/app/admin/models"
"golang.org/x/crypto/bcrypt"
"net/http"
"github.com/gin-gonic/gin"
@@ -312,12 +312,19 @@ func (e SysUser) ResetPwd(c *gin.Context) {
//数据权限检查
p := actions.GetPermissionFromContext(c)
if req.UserId == 1 && config.ApplicationConfig.Mode == "demo" {
req.Password = "123456"
}
err = s.ResetPwd(&req, p)
if err != nil {
e.Logger.Error(err)
return
}
e.OK(req.GetId(), "更新成功")
if req.UserId == 1 && config.ApplicationConfig.Mode == "demo" {
e.OK(req.GetId(), "admin:现在使用的预览环境,休想改掉我!否则会影响其他朋友体验的哦!可以创建其他用户体验该功能!")
} else {
e.OK(req.GetId(), "更新成功")
}
}
// UpdatePwd
@@ -346,19 +353,20 @@ func (e SysUser) UpdatePwd(c *gin.Context) {
// 数据权限检查
p := actions.GetPermissionFromContext(c)
var hash []byte
if hash, err = bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost); err != nil {
req.NewPassword = string(hash)
if user.GetUserId(c) == 1 && config.ApplicationConfig.Mode == "demo" {
req.NewPassword = "123456"
}
err = s.UpdatePwd(user.GetUserId(c), req.OldPassword, req.NewPassword, p)
if err != nil {
e.Logger.Error(err)
e.Error(http.StatusForbidden, err, "密码修改失败")
return
}
e.OK(nil, "密码修改成功")
if user.GetUserId(c) == 1 && config.ApplicationConfig.Mode == "demo" {
e.OK(nil, "admin:现在使用的预览环境,休想改掉我!否则会影响其他朋友体验的哦!可以创建其他用户体验该功能!")
} else {
e.OK(nil, "密码修改成功")
}
}
// GetProfile
@@ -450,7 +458,7 @@ func (e SysUser) GetInfo(c *gin.Context) {
if sysUser.Avatar != "" {
mp["avatar"] = sysUser.Avatar
}
mp["userName"] = sysUser.Username
mp["userName"] = sysUser.NickName
mp["userId"] = sysUser.UserId
mp["deptId"] = sysUser.DeptId
mp["name"] = sysUser.NickName
+8 -8
View File
@@ -1,14 +1,14 @@
package models
//sys_casbin_rule
type CasbinRule struct {
ID uint `gorm:"primaryKey;autoIncrement"`
Ptype string `gorm:"size:512;uniqueIndex:unique_index"`
V0 string `gorm:"size:512;uniqueIndex:unique_index"`
V1 string `gorm:"size:512;uniqueIndex:unique_index"`
V2 string `gorm:"size:512;uniqueIndex:unique_index"`
V3 string `gorm:"size:512;uniqueIndex:unique_index"`
V4 string `gorm:"size:512;uniqueIndex:unique_index"`
V5 string `gorm:"size:512;uniqueIndex:unique_index"`
PType string `json:"p_type" gorm:"size:100;"`
V0 string `json:"v0" gorm:"size:100;"`
V1 string `json:"v1" gorm:"size:100;"`
V2 string `json:"v2" gorm:"size:100;"`
V3 string `json:"v3" gorm:"size:100;"`
V4 string `json:"v4" gorm:"size:100;"`
V5 string `json:"v5" gorm:"size:100;"`
}
func (CasbinRule) TableName() string {
+1 -1
View File
@@ -31,7 +31,7 @@ func ExecSql(db *gorm.DB, filePath string) error {
fmt.Println(sqlList[i])
continue
}
sql := strings.Replace(sqlList[i]+";", "\n", "", -1)
sql := strings.Replace(sqlList[i]+";", "\n", "", 0)
sql = strings.TrimSpace(sql)
if err = db.Exec(sql).Error; err != nil {
log.Printf("error sql: %s", sql)
+11
View File
@@ -0,0 +1,11 @@
package models
import (
"time"
)
type BaseModel struct {
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
}
+4 -4
View File
@@ -27,7 +27,7 @@ type SysApi struct {
models.ControlBy
}
func (*SysApi) TableName() string {
func (SysApi) TableName() string {
return "sys_api"
}
@@ -44,17 +44,17 @@ func SaveSysApi(message storage.Messager) (err error) {
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
err = fmt.Errorf("json Marshal error, %v", err.Error())
fmt.Errorf("json Marshal error, %s", err.Error())
return err
}
var l runtime.Routers
err = json.Unmarshal(rb, &l)
if err != nil {
err = fmt.Errorf("json Unmarshal error, %s", err.Error())
fmt.Errorf("json Unmarshal error, %s", err.Error())
return err
}
dbList := sdk.Runtime.GetAllDb()
dbList := sdk.Runtime.GetDb()
for _, d := range dbList {
for _, v := range l.List {
if v.HttpMethod != "HEAD" ||
+2 -2
View File
@@ -10,13 +10,13 @@ type SysConfig struct {
ConfigKey string `json:"configKey" gorm:"size:128;comment:ConfigKey"` //
ConfigValue string `json:"configValue" gorm:"size:255;comment:ConfigValue"` //
ConfigType string `json:"configType" gorm:"size:64;comment:ConfigType"`
IsFrontend string `json:"isFrontend" gorm:"size:64;comment:是否前台"` //
IsFrontend int `json:"isFrontend" gorm:"size:64;comment:是否前台"` //
Remark string `json:"remark" gorm:"size:128;comment:Remark"` //
models.ControlBy
models.ModelTime
}
func (*SysConfig) TableName() string {
func (SysConfig) TableName() string {
return "sys_config"
}
+2 -2
View File
@@ -7,7 +7,7 @@ type SysDept struct {
ParentId int `json:"parentId" gorm:""` //上级部门
DeptPath string `json:"deptPath" gorm:"size:255;"` //
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
Sort int `json:"sort" gorm:"size:4;"` //排序
Sort int `json:"sort" gorm:"size:4;"` //排序
Leader string `json:"leader" gorm:"size:128;"` //负责人
Phone string `json:"phone" gorm:"size:11;"` //手机
Email string `json:"email" gorm:"size:64;"` //邮箱
@@ -19,7 +19,7 @@ type SysDept struct {
Children []SysDept `json:"children" gorm:"-"`
}
func (*SysDept) TableName() string {
func (SysDept) TableName() string {
return "sys_dept"
}
+1 -1
View File
@@ -20,7 +20,7 @@ type SysDictData struct {
models.ModelTime
}
func (*SysDictData) TableName() string {
func (SysDictData) TableName() string {
return "sys_dict_data"
}
+1 -1
View File
@@ -14,7 +14,7 @@ type SysDictType struct {
models.ModelTime
}
func (*SysDictType) TableName() string {
func (SysDictType) TableName() string {
return "sys_dict_type"
}
+2 -2
View File
@@ -29,7 +29,7 @@ type SysLoginLog struct {
models.ControlBy
}
func (*SysLoginLog) TableName() string {
func (SysLoginLog) TableName() string {
return "sys_login_log"
}
@@ -45,7 +45,7 @@ func (e *SysLoginLog) GetId() interface{} {
// SaveLoginLog 从队列中获取登录日志
func SaveLoginLog(message storage.Messager) (err error) {
//准备db
db := sdk.Runtime.GetDbByTenant(message.GetPrefix())
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())
+2 -8
View File
@@ -30,13 +30,7 @@ type SysMenu struct {
models.ModelTime
}
type SysMenuSlice []SysMenu
func (x SysMenuSlice) Len() int { return len(x) }
func (x SysMenuSlice) Less(i, j int) bool { return x[i].Sort < x[j].Sort }
func (x SysMenuSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (*SysMenu) TableName() string {
func (SysMenu) TableName() string {
return "sys_menu"
}
@@ -47,4 +41,4 @@ func (e *SysMenu) Generate() models.ActiveRecord {
func (e *SysMenu) GetId() interface{} {
return e.MenuId
}
}
+5 -5
View File
@@ -18,15 +18,15 @@ type SysOperaLog struct {
BusinessType string `json:"businessType" gorm:"size:128;comment:操作类型"`
BusinessTypes string `json:"businessTypes" gorm:"size:128;comment:BusinessTypes"`
Method string `json:"method" gorm:"size:128;comment:函数"`
RequestMethod string `json:"requestMethod" gorm:"size:128;comment:请求方式 GET POST PUT DELETE"`
RequestMethod string `json:"requestMethod" gorm:"size:128;comment:请求方式"`
OperatorType string `json:"operatorType" gorm:"size:128;comment:操作类型"`
OperName string `json:"operName" gorm:"size:128;comment:操作者"`
DeptName string `json:"deptName" gorm:"size:128;comment:部门名称"`
OperUrl string `json:"operUrl" gorm:"size:255;comment:访问地址"`
OperIp string `json:"operIp" gorm:"size:128;comment:客户端ip"`
OperLocation string `json:"operLocation" gorm:"size:128;comment:访问位置"`
OperParam string `json:"operParam" gorm:"text;comment:请求参数"`
Status string `json:"status" gorm:"size:4;comment:操作状态 1:正常 2:关闭"`
OperParam string `json:"operParam" gorm:"size:255;comment:请求参数"`
Status string `json:"status" gorm:"size:4;comment:操作状态"`
OperTime time.Time `json:"operTime" gorm:"comment:操作时间"`
JsonResult string `json:"jsonResult" gorm:"size:255;comment:返回数据"`
Remark string `json:"remark" gorm:"size:255;comment:备注"`
@@ -37,7 +37,7 @@ type SysOperaLog struct {
models.ControlBy
}
func (*SysOperaLog) TableName() string {
func (SysOperaLog) TableName() string {
return "sys_opera_log"
}
@@ -53,7 +53,7 @@ func (e *SysOperaLog) GetId() interface{} {
// SaveOperaLog 从队列中获取操作日志
func SaveOperaLog(message storage.Messager) (err error) {
//准备db
db := sdk.Runtime.GetDbByTenant(message.GetPrefix())
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())
+2 -2
View File
@@ -16,7 +16,7 @@ type SysPost struct {
Params string `gorm:"-" json:"params"`
}
func (*SysPost) TableName() string {
func (SysPost) TableName() string {
return "sys_post"
}
@@ -27,4 +27,4 @@ func (e *SysPost) Generate() models.ActiveRecord {
func (e *SysPost) GetId() interface{} {
return e.PostId
}
}
+15 -15
View File
@@ -3,25 +3,25 @@ package models
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;"` // 状态 1禁用 2正常
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:"-"`
SysDept []SysDept `json:"sysDept" gorm:"many2many:sys_role_dept;foreignKey:RoleId;joinForeignKey:role_id;references:DeptId;joinReferences:dept_id;"`
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:"-"`
SysDept []SysDept `json:"sysDept" gorm:"many2many:sys_role_dept;foreignKey:RoleId;joinForeignKey:role_id;references:DeptId;joinReferences:dept_id;"`
SysMenu *[]SysMenu `json:"sysMenu" gorm:"many2many:sys_role_menu;foreignKey:RoleId;joinForeignKey:role_id;references:MenuId;joinReferences:menu_id;"`
models.ControlBy
models.ModelTime
}
func (*SysRole) TableName() string {
func (SysRole) TableName() string {
return "sys_role"
}
@@ -32,4 +32,4 @@ func (e *SysRole) Generate() models.ActiveRecord {
func (e *SysRole) GetId() interface{} {
return e.RoleId
}
}
+2 -2
View File
@@ -29,7 +29,7 @@ type SysUser struct {
models.ModelTime
}
func (*SysUser) TableName() string {
func (SysUser) TableName() string {
return "sys_user"
}
@@ -42,7 +42,7 @@ func (e *SysUser) GetId() interface{} {
return e.UserId
}
// Encrypt 加密
//加密
func (e *SysUser) Encrypt() (err error) {
if e.Password == "" {
return
+2 -1
View File
@@ -12,6 +12,7 @@ var (
routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
)
// 路由示例
func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
// 无需认证的路由
@@ -38,4 +39,4 @@ func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddle
for _, f := range routerCheckRole {
f(v1, authMiddleware)
}
}
}
+7 -16
View File
@@ -1,21 +1,19 @@
package router
import (
"github.com/go-admin-team/go-admin-core/sdk/config"
"go-admin/app/admin/apis"
"mime"
"github.com/go-admin-team/go-admin-core/sdk/config"
"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"
swaggerfiles "github.com/swaggo/files"
"github.com/swaggo/gin-swagger/swaggerFiles"
"go-admin/common/middleware"
"go-admin/common/middleware/handler"
_ "go-admin/docs/admin"
_ "go-admin/docs"
)
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
@@ -56,11 +54,11 @@ func sysStaticFileRouter(r *gin.RouterGroup) {
}
func sysSwaggerRouter(r *gin.RouterGroup) {
r.GET("/swagger/admin/*any", ginSwagger.WrapHandler(swaggerfiles.NewHandler(), ginSwagger.InstanceName("admin")))
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
wss := r.Group("").Use(authMiddleware.MiddlewareFunc())
wss:=r.Group("").Use(authMiddleware.MiddlewareFunc())
{
wss.GET("/ws/:id/:channel", ws.WebsocketManager.WsClient)
wss.GET("/wslogout/:id/:channel", ws.WebsocketManager.UnWsClient)
@@ -69,15 +67,8 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
v1 := r.Group("/api/v1")
{
v1.POST("/login", authMiddleware.LoginHandler)
// GET /api/v1/refresh_token 已移除,原因见 issue #820:
// 该接口用业务 token 即可换取新 token,而续期上限 MaxRefresh 依据的
// orig_iat 在每次续期时被一并重置,上限永远无法到达 —— token 一旦泄
// 露即等同于永久访问权。它此前还位于 CasbinExclude 中,任何角色的已
// 登录用户都能调用,不受权限约束。
//
// 官方前端从未调用该接口(store 中的 refreshToken action 无人 dispatch),
// 移除不影响正常使用。若确需无感续期,应在 go-admin-core 中区分
// access token 与 refresh token 后重新实现,而非沿用此路由。
// Refresh time can be longer than token timeout
v1.GET("/refresh_token", authMiddleware.RefreshHandler)
}
registerBaseRouter(v1, authMiddleware)
}
+3 -2
View File
@@ -11,9 +11,8 @@ type SysApiGetPageReq struct {
dto.Pagination `search:"-"`
Title string `form:"title" search:"type:contains;column:title;table:sys_api" comment:"标题"`
Path string `form:"path" search:"type:contains;column:path;table:sys_api" comment:"地址"`
Action string `form:"action" search:"type:exact;column:action;table:sys_api" comment:"请求方式"`
Action string `form:"action" search:"type:exact;column:action;table:sys_api" comment:"类型"`
ParentId string `form:"parentId" search:"type:exact;column:parent_id;table:sys_api" comment:"按钮id"`
Type string `form:"type" search:"-" comment:"类型"`
SysApiOrder
}
@@ -85,6 +84,7 @@ func (s *SysApiGetReq) GetId() interface{} {
return s.Id
}
// SysApiDeleteReq 功能删除请求参数
type SysApiDeleteReq struct {
Ids []int `json:"ids"`
@@ -93,3 +93,4 @@ type SysApiDeleteReq struct {
func (s *SysApiDeleteReq) GetId() interface{} {
return s.Ids
}
+3 -3
View File
@@ -12,7 +12,7 @@ type SysConfigGetPageReq struct {
ConfigName string `form:"configName" search:"type:contains;column:config_name;table:sys_config"`
ConfigKey string `form:"configKey" search:"type:contains;column:config_key;table:sys_config"`
ConfigType string `form:"configType" search:"type:exact;column:config_type;table:sys_config"`
IsFrontend string `form:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config"`
IsFrontend int `form:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config"`
SysConfigOrder
}
@@ -29,7 +29,7 @@ func (m *SysConfigGetPageReq) GetNeedSearch() interface{} {
}
type SysConfigGetToSysAppReq struct {
IsFrontend string `form:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config"`
IsFrontend int `form:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config"`
}
func (m *SysConfigGetToSysAppReq) GetNeedSearch() interface{} {
@@ -43,7 +43,7 @@ type SysConfigControl struct {
ConfigKey string `uri:"configKey" json:"configKey" comment:""`
ConfigValue string `json:"configValue" comment:""`
ConfigType string `json:"configType" comment:""`
IsFrontend string `json:"isFrontend"`
IsFrontend int `json:"isFrontend"`
Remark string `json:"remark" comment:""`
common.ControlBy
}
+4 -9
View File
@@ -8,21 +8,16 @@ import (
common "go-admin/common/models"
)
const (
OperaStatusEnabel = "1" // 状态-正常
OperaStatusDisable = "2" // 状态-关闭
)
type SysOperaLogGetPageReq struct {
dto.Pagination `search:"-"`
Title string `form:"title" search:"type:contains;column:title;table:sys_opera_log" comment:"操作模块"`
Method string `form:"method" search:"type:contains;column:method;table:sys_opera_log" comment:"函数"`
RequestMethod string `form:"requestMethod" search:"type:contains;column:request_method;table:sys_opera_log" comment:"请求方式: GET POST PUT DELETE"`
RequestMethod string `form:"requestMethod" search:"type:contains;column:request_method;table:sys_opera_log" comment:"请求方式"`
OperUrl string `form:"operUrl" search:"type:contains;column:oper_url;table:sys_opera_log" comment:"访问地址"`
OperIp string `form:"operIp" search:"type:exact;column:oper_ip;table:sys_opera_log" comment:"客户端ip"`
Status int `form:"status" search:"type:exact;column:status;table:sys_opera_log" comment:"状态 1:正常 2:关闭"`
BeginTime string `form:"beginTime" search:"type:gte;column:created_at;table:sys_opera_log" comment:"创建时间"`
EndTime string `form:"endTime" search:"type:lte;column:created_at;table:sys_opera_log" comment:"更新时间"`
Status int `form:"status" search:"type:exact;column:status;table:sys_opera_log" comment:"状态"`
BeginTime string `form:"beginTime" search:"type:gte;column:ctime;table:sys_opera_log" comment:"创建时间"`
EndTime string `form:"endTime" search:"type:lte;column:ctime;table:sys_opera_log" comment:"创建时间"`
SysOperaLogOrder
}
+1 -1
View File
@@ -36,7 +36,7 @@ func (m *SysRoleGetPageReq) GetNeedSearch() interface{} {
type SysRoleInsertReq struct {
RoleId int `uri:"id" comment:"角色编码"` // 角色编码
RoleName string `form:"roleName" comment:"角色名称"` // 角色名称
Status string `form:"status" comment:"状态"` // 状态 1禁用 2正常
Status string `form:"status" comment:"状态"` // 状态
RoleKey string `form:"roleKey" comment:"角色代码"` // 角色代码
RoleSort int `form:"roleSort" comment:"角色排序"` // 角色排序
Flag string `form:"flag" comment:"标记"` // 标记
+1 -2
View File
@@ -121,7 +121,6 @@ func (s *SysUserInsertReq) Generate(model *models.SysUser) {
model.PostId = s.PostId
model.Remark = s.Remark
model.Status = s.Status
model.CreateBy = s.CreateBy
}
func (s *SysUserInsertReq) GetId() interface{} {
@@ -186,4 +185,4 @@ func (s *SysUserById) GenerateM() (common.ActiveRecord, error) {
type PassWord struct {
NewPassword string `json:"newPassword" vd:"len($)>0"`
OldPassword string `json:"oldPassword" vd:"len($)>0"`
}
}
+11 -22
View File
@@ -6,11 +6,12 @@ import (
"github.com/go-admin-team/go-admin-core/sdk/runtime"
"github.com/go-admin-team/go-admin-core/sdk/service"
"gorm.io/gorm"
"go-admin/app/admin/models"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
cDto "go-admin/common/dto"
"go-admin/common/global"
)
type SysApi struct {
@@ -22,25 +23,13 @@ func (e *SysApi) GetPage(c *dto.SysApiGetPageReq, p *actions.DataPermission, lis
var err error
var data models.SysApi
orm := e.Orm.Debug().Model(&data).
err = e.Orm.Debug().Model(&data).
Scopes(
cDto.MakeCondition(c.GetNeedSearch()),
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
actions.Permission(data.TableName(), p),
)
if c.Type != "" {
qType := c.Type
if qType == "暂无" {
qType = ""
}
if global.Driver == "postgres" {
orm = orm.Where("type = ?", qType)
} else {
orm = orm.Where("`type` = ?", qType)
}
}
err = orm.Find(list).Limit(-1).Offset(-1).
).
Find(list).Limit(-1).Offset(-1).
Count(count).Error
if err != nil {
e.Log.Errorf("Service GetSysApiPage error:%s", err)
@@ -56,15 +45,15 @@ func (e *SysApi) Get(d *dto.SysApiGetReq, p *actions.DataPermission, model *mode
Scopes(
actions.Permission(data.TableName(), p),
).
FirstOrInit(model, d.GetId()).Error
if err != nil {
e.Log.Errorf("db error:%s", err)
First(model, d.GetId()).Error
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
err = errors.New("查看对象不存在或无权查看")
e.Log.Errorf("Service GetSysApi error:%s", err)
_ = e.AddError(err)
return e
}
if model.Id == 0 {
err = errors.New("查看对象不存在或无权查看")
e.Log.Errorf("Service GetSysApi error: %s", err)
if err != nil {
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
return e
}
+20 -30
View File
@@ -8,6 +8,7 @@ import (
cDto "go-admin/common/dto"
"github.com/go-admin-team/go-admin-core/sdk/service"
"gorm.io/gorm"
)
type SysConfig struct {
@@ -16,14 +17,13 @@ type SysConfig struct {
// GetPage 获取SysConfig列表
func (e *SysConfig) GetPage(c *dto.SysConfigGetPageReq, list *[]models.SysConfig, count *int64) error {
err := e.Orm.
if err := e.Orm.
Scopes(
cDto.MakeCondition(c.GetNeedSearch()),
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
).
Find(list).Limit(-1).Offset(-1).
Count(count).Error
if err != nil {
Count(count).Error; err != nil {
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
return err
}
@@ -32,18 +32,14 @@ func (e *SysConfig) GetPage(c *dto.SysConfigGetPageReq, list *[]models.SysConfig
// Get 获取SysConfig对象
func (e *SysConfig) Get(d *dto.SysConfigGetReq, model *models.SysConfig) error {
err := e.Orm.
FirstOrInit(model, d.GetId()).
Error
if err != nil {
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
err := e.Orm.First(model, d.GetId()).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
err = errors.New("查看对象不存在或无权查看")
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
return err
}
if model.Id == 0 {
err = errors.New("查看对象不存在或无权查看")
e.Log.Errorf("Service GetSysApi error: %s", err)
_ = e.AddError(err)
if err != nil {
e.Log.Errorf("Service GetSysConfig error:%s", err)
return err
}
return nil
@@ -54,8 +50,7 @@ func (e *SysConfig) Insert(c *dto.SysConfigControl) error {
var err error
var data models.SysConfig
c.Generate(&data)
err = e.Orm.Create(&data).Error
if err != nil {
if err = e.Orm.Create(&data).Error; err != nil {
e.Log.Errorf("Service InsertSysConfig error:%s", err)
return err
}
@@ -90,8 +85,7 @@ func (e *SysConfig) SetSysConfig(c *[]dto.GetSetSysConfigReq) error {
if model.Id != 0 {
req.Generate(&model)
db := e.Orm.Save(&model)
err = db.Error
if err != nil {
if err = db.Error; err != nil {
e.Log.Errorf("Service SetSysConfig error:%s", err)
return err
}
@@ -107,9 +101,8 @@ func (e *SysConfig) GetForSet(c *[]dto.GetSetSysConfigReq) error {
var err error
var data models.SysConfig
err = e.Orm.Model(&data).
Find(c).Error
if err != nil {
if err = e.Orm.Model(&data).
Find(c).Error; err != nil {
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
return err
}
@@ -141,27 +134,25 @@ func (e *SysConfig) UpdateForSet(c *[]dto.GetSetSysConfigReq) error {
// Remove 删除SysConfig
func (e *SysConfig) Remove(d *dto.SysConfigDeleteReq) error {
var err error
var data models.SysConfig
db := e.Orm.Delete(&data, d.Ids)
if err = db.Error; err != nil {
if db.Error != nil {
err := db.Error
e.Log.Errorf("Service RemoveSysConfig error:%s", err)
return err
}
if db.RowsAffected == 0 {
err = errors.New("无权删除该数据")
return err
return errors.New("无权删除该数据")
}
return nil
}
// GetWithKey 根据Key获取SysConfig
func (e *SysConfig) GetWithKey(c *dto.SysConfigByKeyReq, resp *dto.GetSysConfigByKEYForServiceResp) error {
var err error
var data models.SysConfig
err = e.Orm.Table(data.TableName()).Where("config_key = ?", c.ConfigKey).First(resp).Error
if err != nil {
if err := e.Orm.Table(data.TableName()).Where("config_key = ?",
c.ConfigKey).First(resp).Error; err != nil {
e.Log.Errorf("At Service GetSysConfigByKEY Error:%s", err)
return err
}
@@ -170,12 +161,11 @@ func (e *SysConfig) GetWithKey(c *dto.SysConfigByKeyReq, resp *dto.GetSysConfigB
}
func (e *SysConfig) GetWithKeyList(c *dto.SysConfigGetToSysAppReq, list *[]models.SysConfig) error {
err := e.Orm.
if err := e.Orm.
Scopes(
cDto.MakeCondition(c.GetNeedSearch()),
).
Find(list).Error
if err != nil {
Find(list).Error; err != nil {
e.Log.Errorf("Service GetSysConfigByKey error:%s", err)
return err
}
+23 -22
View File
@@ -7,6 +7,8 @@ import (
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/service/dto"
cDto "go-admin/common/dto"
@@ -39,18 +41,16 @@ func (e *SysDept) Get(d *dto.SysDeptGetReq, model *models.SysDept) error {
var err error
var data models.SysDept
err = e.Orm.Model(&data).
FirstOrInit(model, d.GetId()).
Error
if err != nil {
db := e.Orm.Model(&data).
First(model, d.GetId())
err = db.Error
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
err = errors.New("查看对象不存在或无权查看")
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
return err
}
if model.DeptId == 0 {
err = errors.New("查看对象不存在或无权查看")
e.Log.Errorf("Service GetSysApi error: %s", err)
_ = e.AddError(err)
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
return nil
@@ -84,7 +84,7 @@ func (e *SysDept) Insert(c *dto.SysDeptInsertReq) error {
}
var mp = map[string]string{}
mp["dept_path"] = deptPath
if err = tx.Model(&data).Update("dept_path", deptPath).Error; err != nil {
if err := tx.Model(&data).Update("dept_path", deptPath).Error; err != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -116,7 +116,7 @@ func (e *SysDept) Update(c *dto.SysDeptUpdateReq) error {
}
model.DeptPath = deptPath
db := tx.Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("UpdateSysDept error:%s", err)
return err
}
@@ -132,7 +132,8 @@ func (e *SysDept) Remove(d *dto.SysDeptDeleteReq) error {
var data models.SysDept
db := e.Orm.Model(&data).Delete(&data, d.GetId())
if err = db.Error; err != nil {
if db.Error != nil {
err = db.Error
e.Log.Errorf("Delete error: %s", err)
return err
}
@@ -183,16 +184,16 @@ func (e *SysDept) SetDeptTree(c *dto.SysDeptGetPageReq) (m []dto.DeptLabel, err
// Call 递归构造组织数据
func deptTreeCall(deptList *[]models.SysDept, dept dto.DeptLabel) dto.DeptLabel {
list := *deptList
childrenList := make([]dto.DeptLabel, 0)
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 := deptTreeCall(deptList, mi)
childrenList = append(childrenList, ms)
min = append(min, ms)
}
dept.Children = childrenList
dept.Children = min
return dept
}
@@ -212,7 +213,7 @@ func (e *SysDept) SetDeptPage(c *dto.SysDeptGetPageReq) (m []models.SysDept, err
func (e *SysDept) deptPageCall(deptlist *[]models.SysDept, menu models.SysDept) models.SysDept {
list := *deptlist
childrenList := make([]models.SysDept, 0)
min := make([]models.SysDept, 0)
for j := 0; j < len(list); j++ {
if menu.DeptId != list[j].ParentId {
continue
@@ -230,13 +231,13 @@ func (e *SysDept) deptPageCall(deptlist *[]models.SysDept, menu models.SysDept)
mi.CreatedAt = list[j].CreatedAt
mi.Children = []models.SysDept{}
ms := e.deptPageCall(deptlist, mi)
childrenList = append(childrenList, ms)
min = append(min, ms)
}
menu.Children = childrenList
menu.Children = min
return menu
}
// GetWithRoleId 获取角色的部门ID集合
// GetRoleDeptId 获取角色的部门ID集合
func (e *SysDept) GetWithRoleId(roleId int) ([]int, error) {
deptIds := make([]int, 0)
deptList := make([]dto.DeptIdList, 0)
@@ -280,15 +281,15 @@ func (e *SysDept) SetDeptLabel() (m []dto.DeptLabel, err error) {
func deptLabelCall(deptList *[]models.SysDept, dept dto.DeptLabel) dto.DeptLabel {
list := *deptList
var mi dto.DeptLabel
childrenList := make([]dto.DeptLabel, 0)
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 := deptLabelCall(deptList, mi)
childrenList = append(childrenList, ms)
min = append(min, ms)
}
dept.Children = childrenList
dept.Children = min
return dept
}
+3 -2
View File
@@ -47,7 +47,7 @@ func (e *SysDictData) Get(d *dto.SysDictDataGetReq, model *models.SysDictData) e
e.Log.Errorf("db error: %s", err)
return err
}
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error: %s", err)
return err
}
@@ -91,7 +91,8 @@ func (e *SysDictData) Remove(c *dto.SysDictDataDeleteReq) error {
var data models.SysDictData
db := e.Orm.Delete(&data, c.GetId())
if err = db.Error; err != nil {
if db.Error != nil {
err = db.Error
e.Log.Errorf("Delete error: %s", err)
return err
}
+6 -11
View File
@@ -3,7 +3,6 @@ package service
import (
"errors"
"fmt"
"github.com/go-admin-team/go-admin-core/sdk/service"
"gorm.io/gorm"
@@ -46,7 +45,7 @@ func (e *SysDictType) Get(d *dto.SysDictTypeGetReq, model *models.SysDictType) e
e.Log.Errorf("db error: %s", err)
return err
}
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error: %s", err)
return err
}
@@ -59,14 +58,9 @@ func (e *SysDictType) Insert(c *dto.SysDictTypeInsertReq) error {
var data models.SysDictType
c.Generate(&data)
var count int64
// The error was dropped, so a query that failed left count at zero and the
// insert went ahead as though the name were free.
if err = e.Orm.Model(&data).Where("dict_type = ?", data.DictType).Count(&count).Error; err != nil {
e.Log.Errorf("db error: %s", err)
return err
}
e.Orm.Model(&data).Where("dict_type = ?", data.DictType).Count(&count)
if count > 0 {
return fmt.Errorf("当前字典类型[%s]已经存在!", data.DictType)
return errors.New(fmt.Sprintf("当前字典类型[%s]已经存在!", data.DictType))
}
err = e.Orm.Create(&data).Error
if err != nil {
@@ -83,7 +77,7 @@ func (e *SysDictType) Update(c *dto.SysDictTypeUpdateReq) error {
e.Orm.First(&model, c.GetId())
c.Generate(&model)
db := e.Orm.Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error: %s", err)
return err
}
@@ -100,7 +94,8 @@ func (e *SysDictType) Remove(d *dto.SysDictTypeDeleteReq) error {
var data models.SysDictType
db := e.Orm.Delete(&data, d.GetId())
if err = db.Error; err != nil {
if db.Error != nil {
err = db.Error
e.Log.Errorf("Delete error: %s", err)
return err
}
+3 -2
View File
@@ -44,7 +44,7 @@ func (e *SysLoginLog) Get(d *dto.SysLoginLogGetReq, model *models.SysLoginLog) e
e.Log.Errorf("db error:%s", err)
return err
}
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -57,7 +57,8 @@ func (e *SysLoginLog) Remove(c *dto.SysLoginLogDeleteReq) error {
var data models.SysLoginLog
db := e.Orm.Delete(&data, c.GetId())
if err = db.Error; err != nil {
if db.Error != nil {
err = db.Error
e.Log.Errorf("Delete error: %s", err)
return err
}
+47 -98
View File
@@ -1,12 +1,8 @@
package service
import (
"fmt"
"sort"
"strings"
"errors"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/pkg/errors"
"gorm.io/gorm"
"go-admin/app/admin/models"
@@ -90,46 +86,21 @@ func (e *SysMenu) Insert(c *dto.SysMenuInsertReq) *SysMenu {
var err error
var data models.SysMenu
c.Generate(&data)
tx := e.Orm.Debug().Begin()
defer func() {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}()
err = tx.Where("id in ?", c.Apis).Find(&data.SysApi).Error
err = e.Orm.Create(&data).Error
if err != nil {
tx.Rollback()
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
}
err = tx.Create(&data).Error
if err != nil {
tx.Rollback()
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
}
c.MenuId = data.MenuId
err = e.initPaths(tx, &data)
if err != nil {
tx.Rollback()
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
}
tx.Commit()
return e
}
func (e *SysMenu) initPaths(tx *gorm.DB, menu *models.SysMenu) error {
func (e *SysMenu) initPaths(menu *models.SysMenu) error {
var err error
var data models.SysMenu
parentMenu := new(models.SysMenu)
if menu.ParentId != 0 {
err = tx.Model(&data).First(parentMenu, menu.ParentId).Error
if err != nil {
return err
}
e.Orm.Model(&data).First(parentMenu, menu.ParentId)
if parentMenu.Paths == "" {
err = errors.New("父级paths异常,请尝试对当前节点父级菜单进行更新操作!")
return err
@@ -138,7 +109,7 @@ func (e *SysMenu) initPaths(tx *gorm.DB, menu *models.SysMenu) error {
} else {
menu.Paths = "/0/" + pkg.IntToString(menu.MenuId)
}
err = tx.Model(&data).Where("menu_id = ?", menu.MenuId).Update("paths", menu.Paths).Error
e.Orm.Model(&data).Where("menu_id = ?", menu.MenuId).Update("paths", menu.Paths)
return err
}
@@ -156,7 +127,6 @@ func (e *SysMenu) Update(c *dto.SysMenuUpdateReq) *SysMenu {
var alist = make([]models.SysApi, 0)
var model = models.SysMenu{}
tx.Preload("SysApi").First(&model, c.GetId())
oldPath := model.Paths
tx.Where("id in ?", c.Apis).Find(&alist)
err = tx.Model(&model).Association("SysApi").Delete(model.SysApi)
if err != nil {
@@ -167,7 +137,7 @@ func (e *SysMenu) Update(c *dto.SysMenuUpdateReq) *SysMenu {
c.Generate(&model)
model.SysApi = alist
db := tx.Model(&model).Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
return e
@@ -176,12 +146,6 @@ func (e *SysMenu) Update(c *dto.SysMenuUpdateReq) *SysMenu {
_ = e.AddError(errors.New("无权更新该数据"))
return e
}
var menuList []models.SysMenu
tx.Where("paths like ?", oldPath+"%").Find(&menuList)
for _, v := range menuList {
v.Paths = strings.Replace(v.Paths, oldPath, model.Paths, 1)
tx.Model(&v).Update("paths", v.Paths)
}
return e
}
@@ -191,7 +155,8 @@ func (e *SysMenu) Remove(d *dto.SysMenuDeleteReq) *SysMenu {
var data models.SysMenu
db := e.Orm.Model(&data).Delete(&data, d.Ids)
if err = db.Error; err != nil {
if db.Error != nil {
err = db.Error
e.Log.Errorf("Delete error: %s", err)
_ = e.AddError(err)
}
@@ -341,40 +306,6 @@ func menuCall(menuList *[]models.SysMenu, menu models.SysMenu) models.SysMenu {
return menu
}
func menuDistinct(menuList []models.SysMenu) (result []models.SysMenu) {
distinctMap := make(map[int]struct{}, len(menuList))
for _, menu := range menuList {
if _, ok := distinctMap[menu.MenuId]; !ok {
distinctMap[menu.MenuId] = struct{}{}
result = append(result, menu)
}
}
return result
}
func recursiveSetMenu(orm *gorm.DB, mIds []int, menus *[]models.SysMenu) error {
if len(mIds) == 0 || menus == nil {
return nil
}
var subMenus []models.SysMenu
err := orm.Where(fmt.Sprintf(" menu_type in ('%s', '%s', '%s') and menu_id in ?",
cModels.Directory, cModels.Menu, cModels.Button), mIds).Order("sort").Find(&subMenus).Error
if err != nil {
return err
}
subIds := make([]int, 0)
for _, menu := range subMenus {
if menu.ParentId != 0 {
subIds = append(subIds, menu.ParentId)
}
if menu.MenuType != cModels.Button {
*menus = append(*menus, menu)
}
}
return recursiveSetMenu(orm, subIds, menus)
}
// SetMenuRole 获取左侧菜单树使用
func (e *SysMenu) SetMenuRole(roleName string) (m []models.SysMenu, err error) {
menus, err := e.getByRoleName(roleName)
@@ -390,37 +321,55 @@ func (e *SysMenu) SetMenuRole(roleName string) (m []models.SysMenu, err error) {
}
func (e *SysMenu) getByRoleName(roleName string) ([]models.SysMenu, error) {
var MenuList []models.SysMenu
var role models.SysRole
var err error
data := make([]models.SysMenu, 0)
if roleName == "admin" {
// The soft-delete condition is GORM's to add: it appends one for the
// model's DeletedAt field on every query. Writing it by hand duplicates
// that and hard-codes what "deleted" looks like — a column that stops
// being nullable turns this clause into one that matches nothing.
err = e.Orm.Where("menu_type in ('M','C')").
Order("sort").
Find(&data).
Error
err = errors.WithStack(err)
var data []models.SysMenu
err = e.Orm.Where(" menu_type in ('M','C')").Order("sort").Find(&data).Error
MenuList = data
} else {
role.RoleKey = roleName
err = e.Orm.Model(&role).Where("role_key = ? ", roleName).Preload("SysMenu").First(&role).Error
buttons := make([]models.SysMenu,0)
err = e.Orm.Debug().Model(&role).Where("role_key = ? ", roleName).Preload("SysMenu", func(db *gorm.DB) *gorm.DB {
return db.Where(" menu_type in ('F')").Order("sort")
}).Find(&role).Error
if role.SysMenu != nil {
mIds := make([]int, 0)
for _, menu := range *role.SysMenu {
mIds = append(mIds, menu.MenuId)
buttons = *role.SysMenu
}
mIds := make([]int, 0)
for _, menu := range buttons {
if menu.ParentId != 0 {
mIds = append(mIds, menu.ParentId)
}
if err := recursiveSetMenu(e.Orm, mIds, &data); err != nil {
return nil, err
}
var dataC []models.SysMenu
err = e.Orm.Where(" menu_type in ('C') and menu_id in ?", mIds).Order("sort").Find(&dataC).Error
if err != nil {
return nil, err
}
for _, datum := range dataC {
MenuList = append(MenuList, datum)
}
cIds := make([]int, 0)
for _, menu := range MenuList {
if menu.ParentId != 0 {
cIds = append(cIds, menu.ParentId)
}
data = menuDistinct(data)
}
var dataM []models.SysMenu
err = e.Orm.Where(" menu_type in ('M') and menu_id in ?", cIds).Order("sort").Find(&dataM).Error
if err != nil {
return nil, err
}
for _, datum := range dataM {
MenuList = append(MenuList, datum)
}
}
sort.Sort(models.SysMenuSlice(data))
return data, err
if err != nil {
e.Log.Errorf("db error:%s", err)
}
return MenuList, err
}
@@ -1,55 +0,0 @@
package service
import (
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-admin/app/admin/models"
)
// The admin branch of getSysMenuByRoleName carried "deleted_at is null" in its
// where clause. GORM adds that condition itself for a model with a DeletedAt
// field, so the clause was a duplicate — and one written in terms of a column
// being null, which stops being true the moment the column stops being
// nullable. This pins the behaviour the clause was there for.
func TestSoftDeletedMenusAreNotReturned(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open: %v", err)
}
if err := db.AutoMigrate(&models.SysMenu{}); err != nil {
t.Fatalf("migrate: %v", err)
}
live := models.SysMenu{MenuName: "live", MenuType: "M"}
gone := models.SysMenu{MenuName: "gone", MenuType: "M"}
if err := db.Create(&live).Error; err != nil {
t.Fatalf("create: %v", err)
}
if err := db.Create(&gone).Error; err != nil {
t.Fatalf("create: %v", err)
}
if err := db.Delete(&gone).Error; err != nil {
t.Fatalf("delete: %v", err)
}
// Through getByRoleName rather than a copy of its query: a test that
// reissues the statement passes whether or not the production line still
// says what it is supposed to, which is what the first version of this
// test did.
e := &SysMenu{}
e.Orm = db
got, err := e.getByRoleName("admin")
if err != nil {
t.Fatalf("getByRoleName: %v", err)
}
if len(got) != 1 {
t.Fatalf("got %d rows, want 1", len(got))
}
if got[0].MenuName != "live" {
t.Errorf("got %q, want the row that was not deleted", got[0].MenuName)
}
}
+5 -4
View File
@@ -47,7 +47,7 @@ func (e *SysPost) Get(d *dto.SysPostGetReq, model *models.SysPost) error {
e.Log.Errorf("db error:%s", err)
return err
}
if err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -75,7 +75,7 @@ func (e *SysPost) Update(c *dto.SysPostUpdateReq) error {
c.Generate(&model)
db := e.Orm.Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -92,7 +92,8 @@ func (e *SysPost) Remove(d *dto.SysPostDeleteReq) error {
var data models.SysPost
db := e.Orm.Model(&data).Delete(&data, d.GetId())
if err = db.Error; err != nil {
if db.Error != nil {
err = db.Error
e.Log.Errorf("Delete error: %s", err)
return err
}
@@ -101,4 +102,4 @@ func (e *SysPost) Remove(d *dto.SysPostDeleteReq) error {
return err
}
return nil
}
}
+22 -31
View File
@@ -6,7 +6,7 @@ import (
"github.com/go-admin-team/go-admin-core/sdk/config"
"gorm.io/gorm/clause"
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v2"
"github.com/go-admin-team/go-admin-core/sdk/service"
"gorm.io/gorm"
@@ -75,7 +75,7 @@ func (e *SysRole) Insert(c *dto.SysRoleInsertReq, cb *casbin.SyncedEnforcer) err
c.Generate(&data)
tx := e.Orm
if config.DatabaseConfig.Driver != "sqlite3" {
tx = e.Orm.Begin()
tx := e.Orm.Begin()
defer func() {
if err != nil {
tx.Rollback()
@@ -113,17 +113,21 @@ func (e *SysRole) Insert(c *dto.SysRoleInsertReq, cb *casbin.SyncedEnforcer) err
}
}
}
if len(polices) <= 0 {
return nil
}
// 写入 sys_casbin_rule 权限表里 当前角色数据的记录
_, err = cb.AddNamedPolicies("p", polices)
if err != nil {
return err
}
//if len(c.MenuIds) > 0 {
// s := SysRoleMenu{}
// s.Orm = e.Orm
// s.Log = e.Log
// err = s.ReloadRule(tx, c.RoleId, c.MenuIds)
// if err != nil {
// e.Log.Errorf("reload casbin rule error, %", err.Error())
// return err
// }
//}
return nil
}
@@ -132,7 +136,7 @@ func (e *SysRole) Update(c *dto.SysRoleUpdateReq, cb *casbin.SyncedEnforcer) err
var err error
tx := e.Orm
if config.DatabaseConfig.Driver != "sqlite3" {
tx = e.Orm.Begin()
tx := e.Orm.Begin()
defer func() {
if err != nil {
tx.Rollback()
@@ -152,10 +156,9 @@ func (e *SysRole) Update(c *dto.SysRoleUpdateReq, cb *casbin.SyncedEnforcer) err
}
c.Generate(&model)
model.SysMenu = &mlist
// 更新关联的数据,使用 FullSaveAssociations 模式
db := tx.Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -163,7 +166,6 @@ func (e *SysRole) Update(c *dto.SysRoleUpdateReq, cb *casbin.SyncedEnforcer) err
return errors.New("无权更新该数据")
}
// 清除 sys_casbin_rule 权限表里 当前角色的所有记录
_, err = cb.RemoveFilteredPolicy(0, model.RoleKey)
if err != nil {
e.Log.Errorf("delete policy error:%s", err)
@@ -180,15 +182,11 @@ func (e *SysRole) Update(c *dto.SysRoleUpdateReq, cb *casbin.SyncedEnforcer) err
}
}
}
if len(polices) <= 0 {
return nil
}
// 写入 sys_casbin_rule 权限表里 当前角色数据的记录
_, err = cb.AddNamedPolicies("p", polices)
if err != nil {
return err
}
return nil
}
@@ -197,7 +195,7 @@ func (e *SysRole) Remove(c *dto.SysRoleDeleteReq, cb *casbin.SyncedEnforcer) err
var err error
tx := e.Orm
if config.DatabaseConfig.Driver != "sqlite3" {
tx = e.Orm.Begin()
tx := e.Orm.Begin()
defer func() {
if err != nil {
tx.Rollback()
@@ -208,10 +206,9 @@ func (e *SysRole) Remove(c *dto.SysRoleDeleteReq, cb *casbin.SyncedEnforcer) err
}
var model = models.SysRole{}
tx.Preload("SysMenu").Preload("SysDept").First(&model, c.GetId())
//删除 SysRole 时,同时删除角色所有 关联其它表 记录 (SysMenu 和 SysMenu)
db := tx.Select(clause.Associations).Delete(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -219,7 +216,6 @@ func (e *SysRole) Remove(c *dto.SysRoleDeleteReq, cb *casbin.SyncedEnforcer) err
return errors.New("无权更新该数据")
}
// 清除 sys_casbin_rule 权限表里 当前角色的所有记录
_, _ = cb.RemoveFilteredPolicy(0, model.RoleKey)
return nil
@@ -244,7 +240,7 @@ func (e *SysRole) UpdateDataScope(c *dto.RoleDataScopeReq) *SysRole {
var err error
tx := e.Orm
if config.DatabaseConfig.Driver != "sqlite3" {
tx = e.Orm.Begin()
tx := e.Orm.Begin()
defer func() {
if err != nil {
tx.Rollback()
@@ -257,7 +253,6 @@ func (e *SysRole) UpdateDataScope(c *dto.RoleDataScopeReq) *SysRole {
var model = models.SysRole{}
tx.Preload("SysDept").First(&model, c.RoleId)
tx.Where("dept_id in ?", c.DeptIds).Find(&dlist)
// 删除SysRole 和 SysDept 的关联关系
err = tx.Model(&model).Association("SysDept").Delete(model.SysDept)
if err != nil {
e.Log.Errorf("delete SysDept error:%s", err)
@@ -266,9 +261,8 @@ func (e *SysRole) UpdateDataScope(c *dto.RoleDataScopeReq) *SysRole {
}
c.Generate(&model)
model.SysDept = dlist
// 更新关联的数据,使用 FullSaveAssociations 模式
db := tx.Model(&model).Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
_ = e.AddError(err)
return e
@@ -285,7 +279,7 @@ func (e *SysRole) UpdateStatus(c *dto.UpdateStatusReq) error {
var err error
tx := e.Orm
if config.DatabaseConfig.Driver != "sqlite3" {
tx = e.Orm.Begin()
tx := e.Orm.Begin()
defer func() {
if err != nil {
tx.Rollback()
@@ -297,9 +291,8 @@ func (e *SysRole) UpdateStatus(c *dto.UpdateStatusReq) error {
var model = models.SysRole{}
tx.First(&model, c.GetId())
c.Generate(&model)
// 更新关联的数据,使用 FullSaveAssociations 模式
db := tx.Session(&gorm.Session{FullSaveAssociations: true}).Debug().Save(&model)
if err = db.Error; err != nil {
if db.Error != nil {
e.Log.Errorf("db error:%s", err)
return err
}
@@ -344,9 +337,7 @@ func (e *SysRole) GetById(roleId int) ([]string, error) {
}
l := *model.SysMenu
for i := 0; i < len(l); i++ {
if l[i].Permission != "" {
permissions = append(permissions, l[i].Permission)
}
permissions = append(permissions, l[i].Permission)
}
return permissions, nil
}
+1 -3
View File
@@ -233,9 +233,7 @@ func (e *SysUser) UpdatePwd(id int, oldPassword, newPassword string, p *actions.
return err
}
c.Password = newPassword
db := e.Orm.Model(c).Where("user_id = ?", id).
Select("Password", "Salt").
Updates(c)
db := e.Orm.Model(c).Where("user_id = ?", id).Select("Password", "Salt").Updates(c)
if err = db.Error; err != nil {
e.Log.Errorf("db error: %s", err)
return err
-37
View File
@@ -1,37 +0,0 @@
package models
import (
"go-admin/common/models"
)
// DemoProduct 示例模型
//
// 内嵌 ControlBy 与 ModelTime 后,创建人/更新人与时间戳由框架自动维护;
// 数据权限(actions.Permission)正是按 create_by 过滤,缺少 ControlBy 会使其失效。
type DemoProduct struct {
models.Model
Name string `json:"name" gorm:"size:128;comment:名称"`
Code string `json:"code" gorm:"size:64;comment:编码"`
Price float64 `json:"price" gorm:"comment:单价"`
Status string `json:"status" gorm:"size:4;comment:状态"`
Remark string `json:"remark" gorm:"size:255;comment:备注"`
models.ControlBy
models.ModelTime
}
func (DemoProduct) TableName() string {
return "demo_product"
}
// Generate 返回副本,供通用 Action 使用。
// 必须返回新实例:Action 在并发请求间复用同一个模型指针,就地返回会串数据。
func (e *DemoProduct) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *DemoProduct) GetId() interface{} {
return e.Id
}
-49
View File
@@ -1,49 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/demo/models"
"go-admin/app/demo/service/dto"
"go-admin/common/actions"
"go-admin/common/middleware"
)
// 路由通过 init 自注册,无需在任何中心文件登记。
// 新建应用时用 `go run main.go app -n <名称>` 生成骨架,
// 它会同时产出 cmd/api/<名称>.go 完成注册。
func init() {
routerCheckRole = append(routerCheckRole, registerDemoProductRouter)
}
// registerDemoProductRouter 标准 CRUD 的推荐写法。
//
// 五个通用 Action 覆盖了增删改查的全部样板逻辑——参数绑定、数据权限过滤、
// 操作人注入、分页、错误响应,因此本模块没有 apis 与 service 文件。
//
// 仅当业务逻辑超出单表 CRUD(如跨表事务、外部调用、复杂校验)时,才需要
// 自行编写 Handler 与 Service,写法参照 app/admin/apis/sys_post.go。
func registerDemoProductRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r := v1.Group("/demo-product").
Use(authMiddleware.MiddlewareFunc()). // JWT 认证
Use(middleware.AuthCheckRole()) // Casbin 鉴权
{
m := &models.DemoProduct{}
// actions.PermissionAction() 注入数据权限上下文,
// 列表与详情缺少它会绕过 DataScope 过滤
r.GET("", actions.PermissionAction(), actions.IndexAction(m, new(dto.DemoProductSearch), func() interface{} {
list := make([]models.DemoProduct, 0)
return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.DemoProductById), func() interface{} {
return &models.DemoProduct{}
}))
r.POST("", actions.CreateAction(new(dto.DemoProductControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.DemoProductControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.DemoProductById)))
}
}
-74
View File
@@ -1,74 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
_ "github.com/gin-gonic/gin"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
// "github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
common "go-admin/common/middleware"
"os"
)
var (
routerNoCheckRole = make([]func(*gin.RouterGroup), 0)
routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
)
// InitRouter 路由初始化
func InitRouter() {
var r *gin.Engine
h := sdk.Runtime.GetEngine()
if h == nil {
h = gin.New()
sdk.Runtime.SetEngine(h)
}
switch h.(type) {
case *gin.Engine:
r = h.(*gin.Engine)
default:
log.Fatal("not support other engine")
os.Exit(-1)
}
// the jwt middleware
authMiddleware, err := common.AuthInit()
if err != nil {
log.Fatalf("JWT Init Error, %s", err.Error())
}
// 注册业务路由
InitBusinessRouter(r, authMiddleware)
}
func InitBusinessRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
// 无需认证的路由
noCheckRoleRouter(r)
// 需要认证的路由
checkRoleRouter(r, authMiddleware)
return r
}
// noCheckRoleRouter 无需认证的路由
func noCheckRoleRouter(r *gin.Engine) {
// 可根据业务需求来设置接口版本
v := r.Group("/api/v1")
for _, f := range routerNoCheckRole {
f(v)
}
}
// checkRoleRouter 需要认证的路由
func checkRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
// 可根据业务需求来设置接口版本
v := r.Group("/api/v1")
for _, f := range routerCheckRole {
f(v, authMiddleware)
}
}
-96
View File
@@ -1,96 +0,0 @@
package dto
import (
"github.com/gin-gonic/gin"
"go-admin/app/demo/models"
"go-admin/common/dto"
common "go-admin/common/models"
)
// DemoProductSearch 列表查询条件
//
// search tag 决定 MakeCondition 拼出的 WHERE:
//
// exact 精确匹配 / icontains 忽略大小写模糊 / gte 大于等于 …
//
// 未打 search tag 的字段不参与查询,可避免无意间开放过滤维度。
type DemoProductSearch struct {
dto.Pagination `search:"-"`
Name string `form:"name" search:"type:icontains;column:name;table:demo_product"`
Code string `form:"code" search:"type:exact;column:code;table:demo_product"`
Status string `form:"status" search:"type:exact;column:status;table:demo_product"`
DemoProductOrder
}
// DemoProductOrder 排序字段单独成组,避免与查询字段混在一起
type DemoProductOrder struct {
CreatedAtOrder string `form:"createdAtOrder" search:"type:order;column:created_at;table:demo_product"`
}
func (m *DemoProductSearch) GetNeedSearch() interface{} { return *m }
func (m *DemoProductSearch) Bind(ctx *gin.Context) error {
return ctx.ShouldBind(m)
}
func (m *DemoProductSearch) Generate() dto.Index {
o := *m
return &o
}
// DemoProductControl 新增与修改共用的入参
//
// 通用 Action(Create / Update)通过 GenerateM 拿到落库对象,
// 因此这里不直接暴露 Model,字段校验用 validate tag 声明。
type DemoProductControl struct {
Id int `json:"id" comment:"主键"`
Name string `json:"name" comment:"名称" validate:"required"`
Code string `json:"code" comment:"编码" validate:"required"`
Price float64 `json:"price" comment:"单价" validate:"gte=0"`
Status string `json:"status" comment:"状态"`
Remark string `json:"remark" comment:"备注"`
}
func (s *DemoProductControl) Bind(ctx *gin.Context) error {
return ctx.ShouldBind(s)
}
func (s *DemoProductControl) Generate() dto.Control {
o := *s
return &o
}
func (s *DemoProductControl) GetId() interface{} { return s.Id }
// GenerateM 组装落库对象。CreateBy / UpdateBy 由通用 Action 在此之后注入,
// 此处不要手动赋值。
func (s *DemoProductControl) GenerateM() (common.ActiveRecord, error) {
return &models.DemoProduct{
Model: common.Model{Id: s.Id},
Name: s.Name,
Code: s.Code,
Price: s.Price,
Status: s.Status,
Remark: s.Remark,
}, nil
}
// DemoProductById 详情与删除共用,支持单个 id 与批量 ids
type DemoProductById struct {
dto.ObjectById
}
// Bind 与 GetId 由内嵌的 dto.ObjectById 提供:它已处理好 uri 绑定、
// DELETE 时的批量 ids 合并与参数校验,无需在此重复实现。
func (s *DemoProductById) Generate() dto.Control {
o := *s
return &o
}
func (s *DemoProductById) GenerateM() (common.ActiveRecord, error) {
return &models.DemoProduct{}, nil
}
-91
View File
@@ -1,91 +0,0 @@
package dto
import (
"testing"
"go-admin/app/demo/models"
"go-admin/common/dto"
common "go-admin/common/models"
)
// 通用 Action 依赖 DTO 与 Model 实现一组接口。这些约束在编译期无法完全覆盖
// (接口是在路由注册处才被要求的),因此用测试锁定,避免改动后在运行时才暴露。
func TestImplementsIndexInterface(t *testing.T) {
var _ dto.Index = (*DemoProductSearch)(nil)
}
func TestImplementsControlInterface(t *testing.T) {
var _ dto.Control = (*DemoProductControl)(nil)
var _ dto.Control = (*DemoProductById)(nil)
}
func TestModelImplementsActiveRecord(t *testing.T) {
var _ common.ActiveRecord = (*models.DemoProduct)(nil)
}
// Generate 必须返回副本:通用 Action 在并发请求间复用同一个实例,
// 就地返回会导致请求之间串数据。
func TestGenerateReturnsCopy(t *testing.T) {
src := &DemoProductControl{Id: 1, Name: "原始"}
got := src.Generate().(*DemoProductControl)
if got == src {
t.Fatal("Generate 返回了同一指针,应返回副本")
}
got.Name = "被修改"
if src.Name != "原始" {
t.Errorf("修改副本影响了原对象:src.Name = %q", src.Name)
}
}
func TestSearchGenerateReturnsCopy(t *testing.T) {
src := &DemoProductSearch{Name: "原始"}
got := src.Generate().(*DemoProductSearch)
if got == src {
t.Fatal("Generate 返回了同一指针,应返回副本")
}
got.Name = "被修改"
if src.Name != "原始" {
t.Errorf("修改副本影响了原对象:src.Name = %q", src.Name)
}
}
func TestModelGenerateReturnsCopy(t *testing.T) {
src := &models.DemoProduct{Name: "原始"}
got := src.Generate().(*models.DemoProduct)
if got == src {
t.Fatal("Generate 返回了同一指针,应返回副本")
}
got.Name = "被修改"
if src.Name != "原始" {
t.Errorf("修改副本影响了原对象:src.Name = %q", src.Name)
}
}
// GenerateM 组装落库对象,主键需正确传递,否则更新会退化成插入。
func TestGenerateMCarriesId(t *testing.T) {
c := &DemoProductControl{Id: 42, Name: "示例", Code: "P-42", Price: 9.9}
m, err := c.GenerateM()
if err != nil {
t.Fatalf("GenerateM 返回错误: %v", err)
}
p, ok := m.(*models.DemoProduct)
if !ok {
t.Fatalf("GenerateM 返回类型错误: %T", m)
}
if p.Id != 42 {
t.Errorf("主键未传递: got %d, want 42", p.Id)
}
if p.Name != "示例" || p.Code != "P-42" || p.Price != 9.9 {
t.Errorf("字段映射有误: %+v", p)
}
}
func TestTableName(t *testing.T) {
if got := (models.DemoProduct{}).TableName(); got != "demo_product" {
t.Errorf("TableName() = %q, want %q", got, "demo_product")
}
}
+2 -2
View File
@@ -29,7 +29,7 @@ func (e SysJob) RemoveJobForService(c *gin.Context) {
return
}
s.Cron = sdk.Runtime.GetCrontabByTenant(c.Request.Host)
s.Cron = sdk.Runtime.GetCrontabKey(c.Request.Host)
err = s.RemoveJob(&v)
if err != nil {
e.Logger.Errorf("RemoveJob error, %s", err.Error())
@@ -58,7 +58,7 @@ func (e SysJob) StartJobForService(c *gin.Context) {
s := service.SysJob{}
s.Orm = db
s.Log = log
s.Cron = sdk.Runtime.GetCrontabByTenant(c.Request.Host)
s.Cron = sdk.Runtime.GetCrontabKey(c.Request.Host)
err = s.StartJob(&v)
if err != nil {
log.Errorf("GetCrontabKey error, %s", err.Error())
+1 -3
View File
@@ -5,17 +5,15 @@ import (
"time"
)
// InitJob
// 需要将定义的struct 添加到字典中;
// 字典 key 可以配置到 自动任务 调用目标 中;
func InitJob() {
jobList = map[string]JobExec{
jobList = map[string]JobsExec{
"ExamplesOne": ExamplesOne{},
// ...
}
}
// ExamplesOne
// 新添加的job 必须按照以下格式定义,并实现Exec函数
type ExamplesOne struct {
}
+16 -16
View File
@@ -6,6 +6,7 @@ import (
"github.com/go-admin-team/go-admin-core/sdk"
models2 "go-admin/app/jobs/models"
"gorm.io/gorm"
"sync"
"time"
"github.com/robfig/cron/v3"
@@ -17,9 +18,8 @@ import (
var timeFormat = "2006-01-02 15:04:05"
var retryCount = 3
var jobList map[string]JobExec
//var lock sync.Mutex
var jobList map[string]JobsExec
var lock sync.Mutex
type JobCore struct {
InvokeTarget string
@@ -30,7 +30,7 @@ type JobCore struct {
Args string
}
// HttpJob 任务类型 http
// 任务类型 http
type HttpJob struct {
JobCore
}
@@ -46,7 +46,7 @@ func (e *ExecJob) Run() {
log.Warn("[Job] ExecJob Run job nil")
return
}
err := CallExec(obj.(JobExec), e.Args)
err := CallExec(obj.(JobsExec), e.Args)
if err != nil {
// 如果失败暂停一段时间重试
fmt.Println(time.Now().Format(timeFormat), " [ERROR] mission failed! ", err)
@@ -59,11 +59,11 @@ func (e *ExecJob) Run() {
//TODO: 待完善部分
//str := time.Now().Format(timeFormat) + " [INFO] JobCore " + string(e.EntryId) + "exec success , spend :" + latencyTime.String()
//ws.SendAll(str)
log.Infof("[Job] JobCore %s exec success , spend :%v", e.Name, latencyTime)
log.Info("[Job] JobCore %s exec success , spend :%v", e.Name, latencyTime)
return
}
// Run http 任务接口
//http 任务接口
func (h *HttpJob) Run() {
startTime := time.Now()
@@ -77,8 +77,8 @@ LOOP:
str, err = pkg.Get(h.InvokeTarget)
if err != nil {
// 如果失败暂停一段时间重试
log.Warnf("[Job] mission failed! %v", err)
log.Warnf("[Job] Retry after the task fails %d seconds! %s \n", (count+1)*5, str)
fmt.Println(time.Now().Format(timeFormat), " [ERROR] mission failed! ", err)
fmt.Printf(time.Now().Format(timeFormat)+" [INFO] Retry after the task fails %d seconds! %s \n", (count+1)*5, str)
time.Sleep(time.Duration(count+1) * 5 * time.Second)
count = count + 1
goto LOOP
@@ -95,19 +95,19 @@ LOOP:
return
}
// Setup 初始化
// 初始化
func Setup(dbs map[string]*gorm.DB) {
fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Starting...")
for k, db := range dbs {
sdk.Runtime.SetCrontabByTenant(k, cronjob.NewWithSeconds())
sdk.Runtime.SetCrontab(k, cronjob.NewWithSeconds())
setup(k, db)
}
}
func setup(key string, db *gorm.DB) {
crontab := sdk.Runtime.GetCrontabByTenant(key)
crontab := sdk.Runtime.GetCrontabKey(key)
sysJob := models2.SysJob{}
jobList := make([]models2.SysJob, 0)
err := sysJob.GetList(db, &jobList)
@@ -152,7 +152,7 @@ func setup(key string, db *gorm.DB) {
select {}
}
// AddJob 添加任务 AddJob(invokeTarget string, jobId int, jobName string, cronExpression string)
// 添加任务 AddJob(invokeTarget string, jobId int, jobName string, cronExpression string)
func AddJob(c *cron.Cron, job Job) (int, error) {
if job == nil {
fmt.Println("unknown")
@@ -171,8 +171,8 @@ func (h *HttpJob) addJob(c *cron.Cron) (int, error) {
return EntryId, nil
}
func (e *ExecJob) addJob(c *cron.Cron) (int, error) {
id, err := c.AddJob(e.CronExpression, e)
func (h *ExecJob) addJob(c *cron.Cron) (int, error) {
id, err := c.AddJob(h.CronExpression, h)
if err != nil {
fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore AddJob error", err)
return 0, err
@@ -181,7 +181,7 @@ func (e *ExecJob) addJob(c *cron.Cron) (int, error) {
return EntryId, nil
}
// Remove 移除任务
// 移除任务
func Remove(c *cron.Cron, entryID int) chan bool {
ch := make(chan bool)
go func() {
+2 -2
View File
@@ -23,7 +23,7 @@ type SysJob struct {
DataScope string `json:"dataScope" gorm:"-"`
}
func (*SysJob) TableName() string {
func (SysJob) TableName() string {
return "sys_job"
}
@@ -48,7 +48,7 @@ func (e *SysJob) GetList(tx *gorm.DB, list interface{}) (err error) {
return tx.Table(e.TableName()).Where("status = ?", 2).Find(list).Error
}
// Update 更新SysJob
// 更新SysJob
func (e *SysJob) Update(tx *gorm.DB, id interface{}) (err error) {
return tx.Table(e.TableName()).Where(id).Updates(&e).Error
}
+2 -2
View File
@@ -7,10 +7,10 @@ type Job interface {
addJob(*cron.Cron) (int, error)
}
type JobExec interface {
type JobsExec interface {
Exec(arg interface{}) error
}
func CallExec(e JobExec, arg interface{}) error {
func CallExec(e JobsExec, arg interface{}) error {
return e.Exec(arg)
}
+84 -77
View File
@@ -44,61 +44,63 @@ type File struct {
func (e File) UploadFile(c *gin.Context) {
e.MakeContext(c)
tag, _ := c.GetPostForm("type")
urlPrefix := fmt.Sprintf("%s://%s/", "http", c.Request.Host)
urlPrefix := fmt.Sprintf("http://%s/", c.Request.Host)
var fileResponse FileResponse
switch tag {
case "1": // 单图
e.handleSingleFile(c, urlPrefix)
var done bool
fileResponse, done = e.singleFile(c, fileResponse, urlPrefix)
if done {
return
}
e.OK(fileResponse, "上传成功")
return
case "2": // 多图
e.handleMultipleFiles(c, urlPrefix)
multipartFile := e.multipleFile(c, urlPrefix)
e.OK(multipartFile, "上传成功")
return
case "3": // base64
e.handleBase64File(c, urlPrefix)
fileResponse = e.baseImg(c, fileResponse, urlPrefix)
e.OK(fileResponse, "上传成功")
default:
e.handleSingleFile(c, urlPrefix)
}
}
func (e File) handleSingleFile(c *gin.Context, urlPrefix string) {
fileResponse, done := e.singleFile(c, FileResponse{}, urlPrefix)
if done {
var done bool
fileResponse, done = e.singleFile(c, fileResponse, urlPrefix)
if done {
return
}
e.OK(fileResponse, "上传成功")
return
}
e.OK(fileResponse, "上传成功")
}
func (e File) handleMultipleFiles(c *gin.Context, urlPrefix string) {
multipartFile := e.multipleFile(c, urlPrefix)
e.OK(multipartFile, "上传成功")
}
func (e File) handleBase64File(c *gin.Context, urlPrefix string) {
fileResponse := e.baseImg(c, FileResponse{}, urlPrefix)
e.OK(fileResponse, "上传成功")
}
func (e File) baseImg(c *gin.Context, fileResponse FileResponse, urlPrefix string) FileResponse {
func (e File) baseImg(c *gin.Context, fileResponse FileResponse, urlPerfix string) FileResponse {
files, _ := c.GetPostForm("file")
file2list := strings.Split(files, ",")
decodedData, _ := base64.StdEncoding.DecodeString(file2list[1])
fileName := uuid.New().String() + ".jpg"
if err := utils.IsNotExistMkDir(path); err != nil {
ddd, _ := base64.StdEncoding.DecodeString(file2list[1])
guid := uuid.New().String()
fileName := guid + ".jpg"
err := utils.IsNotExistMkDir(path)
if err != nil {
e.Error(500, errors.New(""), "初始化文件路径失败")
return fileResponse
}
base64File := path + fileName
_ = ioutil.WriteFile(base64File, decodedData, 0666)
_ = ioutil.WriteFile(base64File, ddd, 0666)
typeStr := strings.Replace(strings.Replace(file2list[0], "data:", "", -1), ";base64", "", -1)
fileResponse = e.buildFileResponse(base64File, urlPrefix, "", typeStr)
fileResponse = FileResponse{
Size: pkg.GetFileSize(base64File),
Path: base64File,
FullPath: urlPerfix + base64File,
Name: "",
Type: typeStr,
}
source, _ := c.GetPostForm("source")
if err := thirdUpload(source, fileName, base64File); err != nil {
err = thirdUpload(source, fileName, base64File)
if err != nil {
e.Error(200, errors.New(""), "上传第三方失败")
return fileResponse
}
if source != "1" {
fileResponse.Path = "/static/uploadfile/" + fileName
fileResponse.FullPath = "/static/uploadfile/" + fileName
@@ -106,76 +108,81 @@ func (e File) baseImg(c *gin.Context, fileResponse FileResponse, urlPrefix strin
return fileResponse
}
func (e File) multipleFile(c *gin.Context, urlPrefix 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
for _, f := range files {
fileName := uuid.New().String() + utils.GetExt(f.Filename)
guid := uuid.New().String()
fileName := guid + utils.GetExt(f.Filename)
if err := utils.IsNotExistMkDir(path); err != nil {
err := utils.IsNotExistMkDir(path)
if err != nil {
e.Error(500, errors.New(""), "初始化文件路径失败")
continue
}
multipartFileName := path + fileName
if err := c.SaveUploadedFile(f, multipartFileName); err != nil {
continue
}
err1 := c.SaveUploadedFile(f, multipartFileName)
fileType, _ := utils.GetType(multipartFileName)
if err := thirdUpload(source, fileName, multipartFileName); err != nil {
e.Error(500, errors.New(""), "上传第三方失败")
continue
if err1 == nil {
err := thirdUpload(source, fileName, multipartFileName)
if err != nil {
e.Error(500, errors.New(""), "上传第三方失败")
} else {
fileResponse := FileResponse{
Size: pkg.GetFileSize(multipartFileName),
Path: multipartFileName,
FullPath: urlPerfix + multipartFileName,
Name: f.Filename,
Type: fileType,
}
if source != "1" {
fileResponse.Path = "/static/uploadfile/" + fileName
fileResponse.FullPath = "/static/uploadfile/" + fileName
}
multipartFile = append(multipartFile, fileResponse)
}
}
fileResponse := e.buildFileResponse(multipartFileName, urlPrefix, f.Filename, fileType)
if source != "1" {
fileResponse.Path = "/static/uploadfile/" + fileName
fileResponse.FullPath = "/static/uploadfile/" + fileName
}
multipartFile = append(multipartFile, fileResponse)
}
return multipartFile
}
func (e File) singleFile(c *gin.Context, fileResponse FileResponse, urlPrefix string) (FileResponse, bool) {
func (e File) singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (FileResponse, bool) {
files, err := c.FormFile("file")
if err != nil {
e.Error(200, errors.New(""), "图片不能为空")
return FileResponse{}, true
}
// 上传文件至指定目录
guid := uuid.New().String()
fileName := uuid.New().String() + utils.GetExt(files.Filename)
if err := utils.IsNotExistMkDir(path); err != nil {
fileName := guid + utils.GetExt(files.Filename)
err = utils.IsNotExistMkDir(path)
if err != nil {
e.Error(500, errors.New(""), "初始化文件路径失败")
return FileResponse{}, true
}
singleFile := path + fileName
if err := c.SaveUploadedFile(files, singleFile); err != nil {
e.Error(500, errors.New(""), "文件保存失败")
return FileResponse{}, true
}
_ = c.SaveUploadedFile(files, singleFile)
fileType, _ := utils.GetType(singleFile)
fileResponse = e.buildFileResponse(singleFile, urlPrefix, files.Filename, fileType)
fileResponse = FileResponse{
Size: pkg.GetFileSize(singleFile),
Path: singleFile,
FullPath: urlPerfix + singleFile,
Name: files.Filename,
Type: fileType,
}
//source, _ := c.GetPostForm("source")
//err = thirdUpload(source, fileName, singleFile)
//if err != nil {
// e.Error(200, errors.New(""), "上传第三方失败")
// return FileResponse{}, true
//}
fileResponse.Path = "/static/uploadfile/" + fileName
fileResponse.FullPath = "/static/uploadfile/" + fileName
return fileResponse, false
}
func (e File) buildFileResponse(filePath, urlPrefix, fileName, fileType string) FileResponse {
return FileResponse{
Size: pkg.GetFileSize(filePath),
Path: filePath,
FullPath: urlPrefix + filePath,
Name: fileName,
Type: fileType,
}
}
func thirdUpload(source string, name string, path string) error {
switch source {
case "2":
@@ -194,4 +201,4 @@ func ossUpload(name string, path string) error {
func qiniuUpload(name string, path string) error {
oss := file_store.ALiYunOSS{}
return oss.UpLoad(name, path)
}
}
+102 -98
View File
@@ -3,6 +3,7 @@ package apis
import (
"fmt"
"github.com/shirou/gopsutil/v3/net"
"regexp"
"runtime"
"strconv"
"strings"
@@ -11,6 +12,7 @@ import (
"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/response"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/host"
@@ -24,9 +26,22 @@ const (
GB = 1024 * MB
)
var excludeNetInterfaces = []string{
"lo", "tun", "docker", "veth", "br-", "vmbr", "vnet", "kube",
}
var (
Version string
expectDiskFsTypes = []string{
"apfs", "ext4", "ext3", "ext2", "f2fs", "reiserfs", "jfs", "btrfs",
"fuseblk", "zfs", "simfs", "ntfs", "fat32", "exfat", "xfs", "fuse.rclone",
}
excludeNetInterfaces = []string{
"lo", "tun", "docker", "veth", "br-", "vmbr", "vnet", "kube",
}
getMacDiskNo = regexp.MustCompile(`\/dev\/disk(\d)s.*`)
)
var (
netInSpeed, netOutSpeed, netInTransfer, netOutTransfer, lastUpdateNetStats uint64
cachedBootTime time.Time
)
type ServerMonitor struct {
api.Api
@@ -34,148 +49,137 @@ type ServerMonitor struct {
// GetHourDiffer 获取相差时间
func GetHourDiffer(startTime, endTime string) int64 {
t1, err1 := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
t2, err2 := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
if err1 != nil || err2 != nil || !t1.Before(t2) {
return 0
var hour int64
t1, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
t2, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
if err == nil && t1.Before(t2) {
diff := t2.Unix() - t1.Unix() //
hour = diff / 3600
return hour
} else {
return hour
}
return (t2.Unix() - t1.Unix()) / 3600
}
// ServerInfo 获取系统信息
// @Summary 系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/server-monitor [get]
// @Security Bearer
func (e ServerMonitor) ServerInfo(c *gin.Context) {
e.Context = c
osInfo := getOSInfo()
memInfo := getMemoryInfo()
swapInfo := getSwapInfo()
cpuInfo := getCPUInfo()
diskInfo := getDiskInfo()
netInfo := getNetworkInfo()
sysInfo, err := host.Info()
osDic := make(map[string]interface{}, 0)
osDic["goOs"] = runtime.GOOS
osDic["arch"] = runtime.GOARCH
osDic["mem"] = runtime.MemProfileRate
osDic["compiler"] = runtime.Compiler
osDic["version"] = runtime.Version()
osDic["numGoroutine"] = runtime.NumGoroutine()
osDic["ip"] = pkg.GetLocaHonst()
osDic["projectDir"] = pkg.GetCurrentPath()
osDic["hostName"] = sysInfo.Hostname
osDic["time"] = time.Now().Format("2006-01-02 15:04:05")
bootTime, _ := host.BootTime()
cachedBootTime := time.Unix(int64(bootTime), 0)
mem, _ := mem.VirtualMemory()
memDic := make(map[string]interface{}, 0)
memDic["used"] = mem.Used / MB
memDic["total"] = mem.Total / MB
e.Custom(gin.H{
"code": 200,
"os": osInfo,
"mem": memInfo,
"cpu": cpuInfo,
"disk": diskInfo,
"net": netInfo,
"swap": swapInfo,
"location": "Aliyun",
"bootTime": GetHourDiffer(cachedBootTime.Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05")),
})
}
fmt.Println("mem", int(mem.Total/mem.Used*100))
memDic["percent"] = pkg.Round(mem.UsedPercent, 2)
func getOSInfo() map[string]interface{} {
sysInfo, _ := host.Info()
return map[string]interface{}{
"goOs": runtime.GOOS,
"arch": runtime.GOARCH,
"mem": runtime.MemProfileRate,
"compiler": runtime.Compiler,
"version": runtime.Version(),
"numGoroutine": runtime.NumGoroutine(),
"ip": pkg.GetLocalHost(),
"projectDir": pkg.GetCurrentPath(),
"hostName": sysInfo.Hostname,
"time": time.Now().Format("2006-01-02 15:04:05"),
}
}
swapDic := make(map[string]interface{}, 0)
swapDic["used"] = mem.SwapTotal - mem.SwapFree
swapDic["total"] = mem.SwapTotal
func getMemoryInfo() map[string]interface{} {
memory, _ := mem.VirtualMemory()
return map[string]interface{}{
"used": memory.Used / MB,
"total": memory.Total / MB,
"percent": pkg.Round(memory.UsedPercent, 2),
}
}
func getSwapInfo() map[string]interface{} {
memory, _ := mem.VirtualMemory()
return map[string]interface{}{
"used": memory.SwapTotal - memory.SwapFree,
"total": memory.SwapTotal,
}
}
func getCPUInfo() map[string]interface{} {
cpuInfo, _ := cpu.Info()
cpuDic := make(map[string]interface{}, 0)
cpuDic["cpuInfo"], _ = cpu.Info()
percent, _ := cpu.Percent(0, false)
cpuNum, _ := cpu.Counts(false)
return map[string]interface{}{
"cpuInfo": cpuInfo,
"percent": pkg.Round(percent[0], 2),
"cpuNum": cpuNum,
}
}
cpuDic["percent"] = pkg.Round(percent[0], 2)
cpuDic["cpuNum"], _ = cpu.Counts(false)
func getDiskInfo() map[string]interface{} {
//服务器磁盘信息
disklist := make([]disk.UsageStat, 0)
//所有分区
var diskTotal, diskUsed, diskUsedPercent float64
diskList := make([]disk.UsageStat, 0)
diskInfo, err := disk.Partitions(true)
if err == nil {
for _, p := range diskInfo {
diskDetail, err := disk.Usage(p.Mountpoint)
if err == nil {
diskDetail.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", diskDetail.UsedPercent), 64)
diskDetail.Total /= MB
diskDetail.Used /= MB
diskDetail.Free /= MB
diskList = append(diskList, *diskDetail)
diskDetail.Total = diskDetail.Total / 1024 / 1024
diskDetail.Used = diskDetail.Used / 1024 / 1024
diskDetail.Free = diskDetail.Free / 1024 / 1024
disklist = append(disklist, *diskDetail)
}
}
}
d, _ := disk.Usage("/")
diskTotal = float64(d.Total / GB)
diskUsed = float64(d.Used / GB)
diskUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", d.UsedPercent), 64)
return map[string]interface{}{
"total": diskTotal,
"used": diskUsed,
"percent": diskUsedPercent,
}
diskDic := make(map[string]interface{}, 0)
diskDic["total"] = diskTotal
diskDic["used"] = diskUsed
diskDic["percent"] = diskUsedPercent
bootTime, _ := host.BootTime()
cachedBootTime = time.Unix(int64(bootTime), 0)
TrackNetworkSpeed()
netDic := make(map[string]interface{}, 0)
netDic["in"] = pkg.Round(float64(netInSpeed/KB), 2)
netDic["out"] = pkg.Round(float64(netOutSpeed/KB), 2)
e.Custom(gin.H{
"code": 200,
"os": osDic,
"mem": memDic,
"cpu": cpuDic,
"disk": diskDic,
"net": netDic,
"swap": swapDic,
"location": "Aliyun",
"bootTime": GetHourDiffer(cachedBootTime.Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05")),
})
}
func getNetworkInfo() map[string]interface{} {
netInSpeed, netOutSpeed := trackNetworkSpeed()
return map[string]interface{}{
"in": pkg.Round(float64(netInSpeed/KB), 2),
"out": pkg.Round(float64(netOutSpeed/KB), 2),
}
}
func trackNetworkSpeed() (uint64, uint64) {
var netInSpeed, netOutSpeed, netInTransfer, netOutTransfer, lastUpdateNetStats uint64
func TrackNetworkSpeed() {
var innerNetInTransfer, innerNetOutTransfer uint64
nc, err := net.IOCounters(true)
if err == nil {
for _, v := range nc {
if isListContainsStr(excludeNetInterfaces, v.Name) {
continue
}
netInTransfer += v.BytesRecv
netOutTransfer += v.BytesSent
innerNetInTransfer += v.BytesRecv
innerNetOutTransfer += v.BytesSent
}
now := uint64(time.Now().Unix())
diff := now - lastUpdateNetStats
if diff > 0 {
netInSpeed = (netInTransfer - netInTransfer) / diff
netOutSpeed = (netOutTransfer - netOutTransfer) / diff
netInSpeed = (innerNetInTransfer - netInTransfer) / diff
fmt.Println("netInSpeed", netInSpeed)
netOutSpeed = (innerNetOutTransfer - netOutTransfer) / diff
fmt.Println("netOutSpeed", netOutSpeed)
}
netInTransfer = innerNetInTransfer
netOutTransfer = innerNetOutTransfer
lastUpdateNetStats = now
}
return netInSpeed, netOutSpeed
}
func isListContainsStr(list []string, str string) bool {
for _, item := range list {
if strings.Contains(str, item) {
for i := 0; i < len(list); i++ {
if strings.Contains(str, list[i]) {
return true
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ import (
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/db/columns/page [get]
func (e Gen) GetDBColumnList(c *gin.Context) {
func (e *Gen) GetDBColumnList(c *gin.Context) {
e.Context = c
log := e.GetLogger()
var data tools.DBColumns
+1 -1
View File
@@ -19,7 +19,7 @@ import (
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/db/tables/page [get]
func (e Gen) GetDBTableList(c *gin.Context) {
func (e *Gen) GetDBTableList(c *gin.Context) {
//var res response.Response
var data tools.DBTables
var err error
+3 -4
View File
@@ -1,8 +1,7 @@
package tools
import (
common "go-admin/common/models"
"go-admin/app/admin/models"
"gorm.io/gorm"
)
@@ -45,10 +44,10 @@ type SysColumns struct {
CreateBy int `gorm:"column:create_by;size:20;" json:"createBy"`
UpdateBy int `gorm:"column:update_By;size:20;" json:"updateBy"`
common.ModelTime
models.BaseModel
}
func (*SysColumns) TableName() string {
func (SysColumns) TableName() string {
return "sys_columns"
}
+5 -1
View File
@@ -5,6 +5,8 @@ import (
"strings"
"gorm.io/gorm"
"go-admin/app/admin/models"
)
type SysTables struct {
@@ -41,9 +43,11 @@ type SysTables struct {
DataScope string `gorm:"-" json:"dataScope"`
Params Params `gorm:"-" json:"params"`
Columns []SysColumns `gorm:"-" json:"columns"`
models.BaseModel
}
func (*SysTables) TableName() string {
func (SysTables) TableName() string {
return "sys_tables"
}
-8
View File
@@ -1,8 +0,0 @@
package api
import "go-admin/app/demo/router"
func init() {
//注册路由 fixme 其他应用的路由,在本目录新建文件放在init方法
AppRouters = append(AppRouters, router.InitRouter)
}
+22 -25
View File
@@ -3,6 +3,7 @@ package api
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
@@ -10,12 +11,11 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/config/source/file"
log "github.com/go-admin-team/go-admin-core/logger"
"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/pkg/errors"
"github.com/go-admin-team/go-admin-core/sdk/runtime"
"github.com/spf13/cobra"
"go-admin/app/admin/models"
@@ -66,14 +66,14 @@ func setup() {
storage.Setup,
)
//注册监听函数
queue := sdk.Runtime.GetQueuePrefix("")
queue := sdk.Runtime.GetMemoryQueue("")
queue.Register(global.LoginLog, models.SaveLoginLog)
queue.Register(global.OperateLog, models.SaveOperaLog)
queue.Register(global.ApiCheck, models.SaveSysApi)
go queue.Run()
usageStr := `starting api server...`
log.Info(usageStr)
log.Println(usageStr)
}
func run() error {
@@ -89,41 +89,41 @@ func run() error {
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", config.ApplicationConfig.Host, config.ApplicationConfig.Port),
Handler: sdk.Runtime.GetEngine(),
ReadTimeout: time.Duration(config.ApplicationConfig.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(config.ApplicationConfig.WriterTimeout) * time.Second,
}
go func() {
jobs.InitJob()
jobs.Setup(sdk.Runtime.GetAllDb())
jobs.Setup(sdk.Runtime.GetDb())
}()
if apiCheck {
var routers = sdk.Runtime.GetRouter()
q := sdk.Runtime.GetQueuePrefix("")
mp := make(map[string]interface{})
q := sdk.Runtime.GetMemoryQueue("")
mp := make(map[string]interface{}, 0)
mp["List"] = routers
message, err := sdk.Runtime.GetStreamMessage("", global.ApiCheck, mp)
if err != nil {
log.Infof("GetStreamMessage error, %s \n", err.Error())
log.Printf("GetStreamMessage error, %s \n", err.Error())
//日志报错错误,不中断请求
} else {
err = q.Append(message)
if err != nil {
log.Infof("Append message error, %s \n", err.Error())
log.Printf("Append message error, %s \n", err.Error())
}
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
go func() {
// 服务连接
if config.SslConfig.Enable {
if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && !errors.Is(err, http.ErrServerClosed) {
if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
log.Fatal("listen: ", err)
}
} else {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal("listen: ", err)
}
}
@@ -131,30 +131,27 @@ func run() error {
fmt.Println(pkg.Red(string(global.LogoContent)))
tip()
fmt.Println(pkg.Green("Server run at:"))
fmt.Printf("- Local: %s://localhost:%d/ \r\n", "http", config.ApplicationConfig.Port)
fmt.Printf("- Network: %s://%s:%d/ \r\n", "http", pkg.GetLocalHost(), config.ApplicationConfig.Port)
fmt.Printf("- Local: http://localhost:%d/ \r\n", config.ApplicationConfig.Port)
fmt.Printf("- Network: http://%s:%d/ \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port)
fmt.Println(pkg.Green("Swagger run at:"))
fmt.Printf("- Local: http://localhost:%d/swagger/admin/index.html \r\n", config.ApplicationConfig.Port)
fmt.Printf("- Network: %s://%s:%d/swagger/admin/index.html \r\n", "http", pkg.GetLocalHost(), config.ApplicationConfig.Port)
fmt.Printf("- Local: http://localhost:%d/swagger/index.html \r\n", config.ApplicationConfig.Port)
fmt.Printf("- Network: http://%s:%d/swagger/index.html \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port)
fmt.Printf("%s Enter Control + C Shutdown Server \r\n", pkg.GetCurrentTimeStr())
// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
quit := make(chan os.Signal, 1)
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
log.Info("Shutdown Server ... ")
fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr())
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Info("Server exiting")
log.Println("Server exiting")
return nil
}
//var Router runtime.Router
var Router runtime.Router
func tip() {
usageStr := `欢迎使用 ` + pkg.Green(`go-admin `+global.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令`
@@ -173,7 +170,7 @@ func initRouter() {
r = h.(*gin.Engine)
default:
log.Fatal("not support other engine")
//os.Exit(-1)
os.Exit(-1)
}
if config.SslConfig.Enable {
r.Use(handler.TlsHandler())
+3 -3
View File
@@ -13,10 +13,10 @@ import (
var (
appName string
StartCmd = &cobra.Command{
Use: "app",
Use: "createapp",
Short: "Create a new app",
Long: "Use when you need to create a new app",
Example: "go-admin app -n admin",
Example: "go-admin createapp -n admin",
Run: func(cmd *cobra.Command, args []string) {
run()
},
@@ -87,4 +87,4 @@ func genFile() error {
err = t2.Execute(&b2, nil)
pkg.FileCreate(b2, appPath+"/router/router.go")
return nil
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ var rootCmd = &cobra.Command{
func tip() {
usageStr := `欢迎使用 ` + pkg.Green(`go-admin `+global.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令`
usageStr1 := `也可以参考 https://doc.go-admin.dev/guide/ksks 的相关内容`
usageStr1 := `也可以参考 https://doc.go-admin.dev/guide/ksks.html 里边的【启动】章节`
fmt.Printf("%s\n", usageStr)
fmt.Printf("%s\n", usageStr1)
}
+8 -9
View File
@@ -1,15 +1,14 @@
package models
// CasbinRule sys_casbin_rule
//sys_casbin_rule
type CasbinRule struct {
ID uint `gorm:"primaryKey;autoIncrement"`
Ptype string `gorm:"size:512;uniqueIndex:unique_index"`
V0 string `gorm:"size:512;uniqueIndex:unique_index"`
V1 string `gorm:"size:512;uniqueIndex:unique_index"`
V2 string `gorm:"size:512;uniqueIndex:unique_index"`
V3 string `gorm:"size:512;uniqueIndex:unique_index"`
V4 string `gorm:"size:512;uniqueIndex:unique_index"`
V5 string `gorm:"size:512;uniqueIndex:unique_index"`
PType string `json:"p_type" gorm:"size:100;"`
V0 string `json:"v0" gorm:"size:100;"`
V1 string `json:"v1" gorm:"size:100;"`
V2 string `json:"v2" gorm:"size:100;"`
V3 string `json:"v3" gorm:"size:100;"`
V4 string `json:"v4" gorm:"size:100;"`
V5 string `json:"v5" gorm:"size:100;"`
}
func (CasbinRule) TableName() string {
-4
View File
@@ -13,10 +13,6 @@ import (
func InitDb(db *gorm.DB) (err error) {
filePath := "config/db.sql"
if global.Driver == "postgres" {
filePath := "config/db.sql"
if err = ExecSql(db, filePath); err != nil {
return err
}
filePath = "config/pg.sql"
err = ExecSql(db, filePath)
} else if global.Driver == "mysql" {
@@ -1,5 +1,6 @@
package models
//sys_role_dept
type SysRoleDept struct {
RoleId int `gorm:"size:11;primaryKey"`
DeptId int `gorm:"size:11;primaryKey"`
@@ -10,15 +10,15 @@ type SysOperaLog struct {
BusinessType string `json:"businessType" gorm:"type:varchar(128);comment:操作类型"`
BusinessTypes string `json:"businessTypes" gorm:"type:varchar(128);comment:BusinessTypes"`
Method string `json:"method" gorm:"type:varchar(128);comment:函数"`
RequestMethod string `json:"requestMethod" gorm:"type:varchar(128);comment:请求方式: GET POST PUT DELETE"`
RequestMethod string `json:"requestMethod" gorm:"type:varchar(128);comment:请求方式"`
OperatorType string `json:"operatorType" gorm:"type:varchar(128);comment:操作类型"`
OperName string `json:"operName" gorm:"type:varchar(128);comment:操作者"`
DeptName string `json:"deptName" gorm:"type:varchar(128);comment:部门名称"`
OperUrl string `json:"operUrl" gorm:"type:varchar(255);comment:访问地址"`
OperIp string `json:"operIp" gorm:"type:varchar(128);comment:客户端ip"`
OperLocation string `json:"operLocation" gorm:"type:varchar(128);comment:访问位置"`
OperParam string `json:"operParam" gorm:"type:text;comment:请求参数"`
Status string `json:"status" gorm:"type:varchar(4);comment:操作状态 1:正常 2:关闭"`
OperParam string `json:"operParam" gorm:"type:varchar(255);comment:请求参数"`
Status string `json:"status" gorm:"type:varchar(4);comment:操作状态"`
OperTime time.Time `json:"operTime" gorm:"type:timestamp;comment:操作时间"`
JsonResult string `json:"jsonResult" gorm:"type:varchar(255);comment:返回数据"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
+1 -1
View File
@@ -24,7 +24,7 @@ type SysUser struct {
ModelTime
}
func (*SysUser) TableName() string {
func (SysUser) TableName() string {
return "sys_user"
}
@@ -1,7 +1,6 @@
package version
import (
"github.com/go-admin-team/go-admin-core/sdk/config"
"runtime"
"go-admin/cmd/migrate/migration"
@@ -18,10 +17,8 @@ func init() {
func _1599190683659Tables(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
if config.DatabaseConfig.Driver == "mysql" {
tx = tx.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")
}
err := tx.Migrator().AutoMigrate(
err := tx.Debug().Migrator().AutoMigrate(
new(models.CasbinRule),
new(models.SysDept),
new(models.SysConfig),
new(models.SysTables),
@@ -1,48 +0,0 @@
package version
import (
"go-admin/cmd/migrate/migration/models"
common "go-admin/common/models"
"gorm.io/gorm"
"runtime"
"strconv"
"go-admin/cmd/migrate/migration"
)
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1653638869132Test)
}
func _1653638869132Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
var list []models.SysMenu
err := tx.Model(&models.SysMenu{}).Order("parent_id,menu_id").Find(&list).Error
if err != nil {
return err
}
for _, v := range list {
if v.ParentId == 0 {
v.Paths = "/0/" + strconv.Itoa(v.MenuId)
} else {
var e models.SysMenu
err = tx.Model(&models.SysMenu{}).Where("menu_id=?", v.ParentId).First(&e).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
continue
}
return err
}
v.Paths = e.Paths + "/" + strconv.Itoa(v.MenuId)
}
err = tx.Model(&v).Update("paths", v.Paths).Error
if err != nil {
return err
}
}
return tx.Create(&common.Migration{
Version: version,
}).Error
})
}
@@ -1,42 +0,0 @@
package version
import (
"runtime"
"gorm.io/gorm"
"go-admin/app/demo/models"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
)
// 示例模块的建表迁移。
//
// 迁移文件名前 13 位是版本号(Unix 毫秒时间戳),框架按文件名升序执行,
// 已执行的版本记录在 sys_migration 表中,不会重复运行。
//
// 本文件放在 version/ 是因为它随框架一起分发;**业务项目自己的迁移应放
// version-local/**,该目录已被 .gitignore 忽略,不会与上游冲突。
//
// 生成新的迁移骨架:go run main.go migrate -c config/settings.yml -g
//
// 注意:已执行过的迁移文件不可再修改——版本号已入表,改动不会重跑。
// 需要调整时新建一个迁移。
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1786700000000DemoProduct)
}
func _1786700000000DemoProduct(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
// 1. 建表
if err := tx.Migrator().AutoMigrate(new(models.DemoProduct)); err != nil {
return err
}
// 2. 初始化数据(可选)。此处留空,示例模块不写入业务数据。
// 3. 记录版本号——必须,否则该迁移每次启动都会重跑
return tx.Create(&common.Migration{Version: version}).Error
})
}
@@ -1,135 +0,0 @@
package version
import (
"runtime"
"strconv"
"gorm.io/gorm"
"go-admin/cmd/migrate/migration"
"go-admin/cmd/migrate/migration/models"
common "go-admin/common/models"
)
// 为 app/demo 模块写入菜单、接口与权限种子数据。
//
// 一个业务模块要在界面上可用,需要四类数据:
//
// 1. sys_api —— 后端路由的登记,Casbin 据此判定权限
// 2. sys_menu —— 侧边栏菜单(目录 M / 菜单 C / 按钮 F)
// 3. sys_menu_api_rule —— 菜单与接口的多对多关联,角色保存时据此生成策略
// 4. casbin_rule —— 实际生效的权限策略
//
// 注意 casbin_rule 才是 adapter 实际使用的表;models.CasbinRule 对应的
// sys_casbin_rule 是历史遗留,其 7 列 size:512 唯一索引在 MySQL 下会超出
// 索引长度限制,不要将其纳入 AutoMigrate。
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1786700001000DemoMenu)
}
const (
demoMenuId = 9000 // 目录:示例模块
demoProductId = 9001 // 菜单:商品管理
demoApiBaseId = 9000 // sys_api 起始 id
adminRoleKey = "admin"
)
func _1786700001000DemoMenu(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
// ---- 1. 接口登记 ----
apis := []models.SysApi{
{Id: demoApiBaseId + 1, Handle: "go-admin/common/actions.IndexAction.func1", Title: "示例商品列表", Path: "/api/v1/demo-product", Type: "SYS", Action: "GET"},
{Id: demoApiBaseId + 2, Handle: "go-admin/common/actions.ViewAction.func1", Title: "示例商品详情", Path: "/api/v1/demo-product/:id", Type: "SYS", Action: "GET"},
{Id: demoApiBaseId + 3, Handle: "go-admin/common/actions.CreateAction.func1", Title: "示例商品新增", Path: "/api/v1/demo-product", Type: "SYS", Action: "POST"},
{Id: demoApiBaseId + 4, Handle: "go-admin/common/actions.UpdateAction.func1", Title: "示例商品修改", Path: "/api/v1/demo-product/:id", Type: "SYS", Action: "PUT"},
{Id: demoApiBaseId + 5, Handle: "go-admin/common/actions.DeleteAction.func1", Title: "示例商品删除", Path: "/api/v1/demo-product", Type: "SYS", Action: "DELETE"},
}
for i := range apis {
if err := upsert(tx, &models.SysApi{}, "id = ?", apis[i].Id, &apis[i]); err != nil {
return err
}
}
// ---- 2. 菜单 ----
// 目录本身不对应页面,component 固定为 Layout
dir := models.SysMenu{
MenuId: demoMenuId, MenuName: "Demo", Title: "示例模块", Icon: "example",
Path: "/demo", Paths: "/0/9000", MenuType: "M", ParentId: 0,
Component: "Layout", Sort: 900, Visible: "0", IsFrame: "1",
}
if err := upsert(tx, &models.SysMenu{}, "menu_id = ?", dir.MenuId, &dir); err != nil {
return err
}
// 菜单的 menu_name 需与前端组件 name 一致,否则 keep-alive 缓存无法命中
page := models.SysMenu{
MenuId: demoProductId, MenuName: "DemoProduct", Title: "商品管理", Icon: "documentation",
Path: "/demo/product", Paths: "/0/9000/9001", MenuType: "C", ParentId: demoMenuId,
Component: "/demo/product/index", Sort: 1, Visible: "0", IsFrame: "1",
SysApi: apis,
}
if err := upsert(tx, &models.SysMenu{}, "menu_id = ?", page.MenuId, &page); err != nil {
return err
}
// 按钮级权限,permission 需与前端 v-permisaction 中的标识一致
buttons := []models.SysMenu{
{MenuId: 9002, MenuName: "DemoProductAdd", Title: "新增", MenuType: "F", ParentId: demoProductId, Permission: "demo:product:add", Sort: 1, Visible: "0", IsFrame: "1"},
{MenuId: 9003, MenuName: "DemoProductEdit", Title: "修改", MenuType: "F", ParentId: demoProductId, Permission: "demo:product:edit", Sort: 2, Visible: "0", IsFrame: "1"},
{MenuId: 9004, MenuName: "DemoProductDel", Title: "删除", MenuType: "F", ParentId: demoProductId, Permission: "demo:product:delete", Sort: 3, Visible: "0", IsFrame: "1"},
}
for i := range buttons {
buttons[i].Paths = "/0/9000/9001/" + strconv.Itoa(buttons[i].MenuId)
if err := upsert(tx, &models.SysMenu{}, "menu_id = ?", buttons[i].MenuId, &buttons[i]); err != nil {
return err
}
}
// ---- 3. 授权给 admin 角色 ----
var role models.SysRole
err := tx.Where("role_key = ?", adminRoleKey).First(&role).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
// 尚未初始化角色数据时跳过授权,不阻断迁移
return tx.Create(&common.Migration{Version: version}).Error
}
return err
}
for _, id := range []int{demoMenuId, demoProductId, 9002, 9003, 9004} {
if err = tx.Exec(
"INSERT INTO sys_role_menu (role_id, menu_id) SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM sys_role_menu WHERE role_id = ? AND menu_id = ?)",
role.RoleId, id, role.RoleId, id,
).Error; err != nil {
return err
}
}
// ---- 4. Casbin 策略 ----
// admin 角色在中间件中直接放行,此处仍写入策略以便复制该角色配置时可继承
for _, a := range apis {
if err = tx.Exec(
"INSERT INTO casbin_rule (ptype, v0, v1, v2, v3, v4, v5) SELECT 'p', ?, ?, ?, '', '', '' WHERE NOT EXISTS (SELECT 1 FROM casbin_rule WHERE ptype='p' AND v0=? AND v1=? AND v2=?)",
role.RoleKey, a.Path, a.Action, role.RoleKey, a.Path, a.Action,
).Error; err != nil {
return err
}
}
return tx.Create(&common.Migration{Version: version}).Error
})
}
// upsert 存在则更新、不存在则插入。迁移可能在已有数据的库上运行,
// 直接 Create 会因主键冲突失败。
func upsert(tx *gorm.DB, model interface{}, where string, id int, value interface{}) error {
var count int64
if err := tx.Model(model).Where(where, id).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return tx.Model(model).Where(where, id).Updates(value).Error
}
return tx.Create(value).Error
}
@@ -1,61 +0,0 @@
package version
import (
"runtime"
"gorm.io/gorm"
"go-admin/cmd/migrate/migration"
"go-admin/cmd/migrate/migration/models"
common "go-admin/common/models"
)
// 清理 GET /api/v1/refresh_token 的残留权限数据。
//
// 该路由已随 issue #820 的修复移除:它允许用业务 token 换取新 token,而续期
// 上限 MaxRefresh 依据的 orig_iat 每次续期都被重置,上限永远无法到达。
//
// 路由虽已删除(请求会返回 404),但已有部署的库中仍残留三类记录:接口登记、
// 菜单与接口的绑定、Casbin 策略。留着会让「接口管理」列出一个不存在的端点,
// 角色配置里也仍可勾选,造成误解。
//
// 按 path 匹配而非固定 id —— 使用者若执行过 `server -a` 重新注册接口,id 会
// 与官方种子数据不同。
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1786700002000RemoveRefreshTokenApi)
}
const refreshTokenPath = "/api/v1/refresh_token"
func _1786700002000RemoveRefreshTokenApi(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
var apiIds []int
if err := tx.Model(&models.SysApi{}).
Where("path = ? AND action = ?", refreshTokenPath, "GET").
Pluck("id", &apiIds).Error; err != nil {
return err
}
if len(apiIds) > 0 {
// 先断开绑定,再删接口本身,避免遗留悬空外键
// 连接表由 GORM many2many 生成,列名为 sys_api_id 而非 api_id
if err := tx.Exec("DELETE FROM sys_menu_api_rule WHERE sys_api_id IN ?", apiIds).Error; err != nil {
return err
}
if err := tx.Where("id IN ?", apiIds).Delete(&models.SysApi{}).Error; err != nil {
return err
}
}
// casbin_rule 才是 adapter 实际使用的表,策略按路径存储,与 sys_api 的
// id 无关,因此即使上面没匹配到接口也要清理
if err := tx.Exec(
"DELETE FROM casbin_rule WHERE ptype = 'p' AND v1 = ?", refreshTokenPath,
).Error; err != nil {
return err
}
return tx.Create(&common.Migration{Version: version}).Error
})
}
@@ -1,218 +0,0 @@
package version
import (
"fmt"
"runtime"
"time"
"gorm.io/gorm"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
)
// Convert deleted_at from a nullable timestamp to a non-null millisecond
// marker, then put a unique index on the three natural keys.
//
// Those keys had no unique index at all. Uniqueness was a SELECT COUNT
// followed by an INSERT, which two concurrent requests both pass.
//
// The index cannot be on the key alone: a soft-deleted row keeps occupying the
// name, so a deleted user's username could never be used again. It has to
// include the delete marker — and the marker has to be non-null, because two
// live rows are (name, NULL) and (name, NULL), and NULL is not equal to NULL.
// An index over a nullable marker permits both rows. It looks like a
// constraint and enforces nothing.
//
// DDL does not roll back on MySQL, so this is written to be re-runnable rather
// than transactional: every step asks whether it has already been taken.
func init() {
_, fileName, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1786700003000SoftDeleteMarker)
}
// Every table whose model embeds common.ModelTime.
var softDeleteTables = []string{
"sys_api", "sys_config", "sys_dept", "sys_dict_data", "sys_dict_type",
"sys_job", "sys_menu", "sys_post", "sys_role", "sys_user", "demo_product",
}
// The keys that gain a constraint, and the column that makes it possible.
var naturalKeys = []struct {
table, column, index string
}{
{"sys_user", "username", "uk_sys_user_username"},
{"sys_role", "role_key", "uk_sys_role_role_key"},
{"sys_dict_type", "dict_type", "uk_sys_dict_type_dict_type"},
}
const tempColumn = "deleted_at_ms"
func _1786700003000SoftDeleteMarker(db *gorm.DB, version string) error {
// Refused before anything is altered: creating the index on a table that
// already holds duplicates fails halfway through, and the operator is left
// guessing which rows to reconcile.
if err := refuseOnDuplicates(db); err != nil {
return err
}
for _, table := range softDeleteTables {
if err := convertDeletedAt(db, table); err != nil {
return fmt.Errorf("%s: %w", table, err)
}
}
for _, k := range naturalKeys {
if err := createUniqueIndex(db, k.table, k.column, k.index); err != nil {
return fmt.Errorf("%s.%s: %w", k.table, k.column, err)
}
}
return db.Create(&common.Migration{Version: version}).Error
}
// refuseOnDuplicates reports the values that would make the index impossible,
// rather than the index failing to build and saying only that it did.
func refuseOnDuplicates(db *gorm.DB) error {
for _, k := range naturalKeys {
if !db.Migrator().HasTable(k.table) {
continue
}
var dupes []string
q := fmt.Sprintf(
"SELECT %s FROM %s WHERE deleted_at IS NULL GROUP BY %s HAVING COUNT(*) > 1",
k.column, k.table, k.column,
)
if !db.Migrator().HasColumn(k.table, "deleted_at") {
// Already converted; live rows carry zero rather than null.
q = fmt.Sprintf(
"SELECT %s FROM %s WHERE deleted_at = 0 GROUP BY %s HAVING COUNT(*) > 1",
k.column, k.table, k.column,
)
}
if err := db.Raw(q).Scan(&dupes).Error; err != nil {
return fmt.Errorf("checking %s.%s for duplicates: %w", k.table, k.column, err)
}
if len(dupes) > 0 {
return fmt.Errorf(
"%s.%s already holds duplicates %v; reconcile them before this migration can add its unique index",
k.table, k.column, dupes,
)
}
}
return nil
}
func convertDeletedAt(db *gorm.DB, table string) error {
m := db.Migrator()
if !m.HasTable(table) {
return nil
}
converted, err := isConverted(db, table)
if err != nil {
return err
}
if converted {
return nil
}
if !m.HasColumn(table, tempColumn) {
if err := db.Exec(addBigIntColumn(db, table, tempColumn)).Error; err != nil {
return fmt.Errorf("adding %s: %w", tempColumn, err)
}
}
// Converted in Go rather than in SQL: turning a timestamp into epoch
// milliseconds is spelled differently by every dialect this supports, and
// the row counts here do not justify four versions of it.
if err := copyTimestamps(db, table); err != nil {
return err
}
if err := db.Exec(dropColumn(db, table, "deleted_at")).Error; err != nil {
return fmt.Errorf("dropping deleted_at: %w", err)
}
if err := db.Exec(renameColumn(db, table, tempColumn, "deleted_at")).Error; err != nil {
return fmt.Errorf("renaming %s: %w", tempColumn, err)
}
return nil
}
// isConverted reports whether deleted_at already holds the marker. A table
// mid-conversion still has both columns, and is finished rather than skipped.
func isConverted(db *gorm.DB, table string) (bool, error) {
types, err := db.Migrator().ColumnTypes(table)
if err != nil {
return false, err
}
for _, c := range types {
if c.Name() != "deleted_at" {
continue
}
if nullable, ok := c.Nullable(); ok && !nullable {
return !db.Migrator().HasColumn(table, tempColumn), nil
}
return false, nil
}
// No such column: nothing to convert.
return true, nil
}
func copyTimestamps(db *gorm.DB, table string) error {
type row struct {
Id int64
DeletedAt *time.Time
}
var rows []row
q := fmt.Sprintf("SELECT id, deleted_at FROM %s WHERE deleted_at IS NOT NULL", table)
if err := db.Raw(q).Scan(&rows).Error; err != nil {
return fmt.Errorf("reading deleted rows: %w", err)
}
for _, r := range rows {
if r.DeletedAt == nil {
continue
}
u := fmt.Sprintf("UPDATE %s SET %s = ? WHERE id = ?", table, tempColumn)
if err := db.Exec(u, r.DeletedAt.UnixMilli(), r.Id).Error; err != nil {
return fmt.Errorf("marking row %d deleted: %w", r.Id, err)
}
}
return nil
}
func createUniqueIndex(db *gorm.DB, table, column, name string) error {
if db.Migrator().HasIndex(table, name) {
return nil
}
return db.Exec(fmt.Sprintf(
"CREATE UNIQUE INDEX %s ON %s (%s, deleted_at)", name, table, column,
)).Error
}
// The three statements every dialect spells differently.
func addBigIntColumn(db *gorm.DB, table, column string) string {
if db.Dialector.Name() == "sqlserver" {
return fmt.Sprintf("ALTER TABLE %s ADD %s BIGINT NOT NULL DEFAULT 0", table, column)
}
return fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s BIGINT NOT NULL DEFAULT 0", table, column)
}
func dropColumn(db *gorm.DB, table, column string) string {
return fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", table, column)
}
func renameColumn(db *gorm.DB, table, from, to string) string {
switch db.Dialector.Name() {
case "sqlserver":
return fmt.Sprintf("EXEC sp_rename '%s.%s', '%s', 'COLUMN'", table, from, to)
case "mysql":
return fmt.Sprintf("ALTER TABLE %s CHANGE %s %s BIGINT NOT NULL DEFAULT 0", table, from, to)
default:
return fmt.Sprintf("ALTER TABLE %s RENAME COLUMN %s TO %s", table, from, to)
}
}
@@ -1,179 +0,0 @@
package version
import (
"testing"
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
// oldUser is the shape of the table before this migration: deleted_at is a
// nullable timestamp, and nothing constrains the username.
type oldUser struct {
Id int64 `gorm:"primaryKey;autoIncrement"`
Username string
DeletedAt *time.Time
}
func (oldUser) TableName() string { return "sys_user" }
func openWithOldSchema(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open: %v", err)
}
if err := db.AutoMigrate(&oldUser{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
}
func TestConvertsDeletedAtAndKeepsWhoWasDeleted(t *testing.T) {
db := openWithOldSchema(t)
gone := time.Now().Add(-time.Hour)
rows := []oldUser{
{Username: "alice"},
{Username: "bob", DeletedAt: &gone},
}
for i := range rows {
if err := db.Create(&rows[i]).Error; err != nil {
t.Fatalf("seed: %v", err)
}
}
if err := convertDeletedAt(db, "sys_user"); err != nil {
t.Fatalf("convert: %v", err)
}
var marks []struct {
Username string
DeletedAt int64
}
if err := db.Raw("SELECT username, deleted_at FROM sys_user ORDER BY id").Scan(&marks).Error; err != nil {
t.Fatalf("read back: %v", err)
}
if len(marks) != 2 {
t.Fatalf("got %d rows, want 2", len(marks))
}
if marks[0].DeletedAt != 0 {
t.Errorf("a live row carries %d, want 0", marks[0].DeletedAt)
}
if want := gone.UnixMilli(); marks[1].DeletedAt != want {
t.Errorf("the deleted row carries %d, want %d: the timestamp was lost", marks[1].DeletedAt, want)
}
}
// Running it twice must be safe: DDL does not roll back on MySQL, so an
// operator whose first attempt failed halfway has nothing to do but run it
// again.
func TestConversionIsRepeatable(t *testing.T) {
db := openWithOldSchema(t)
if err := db.Create(&oldUser{Username: "alice"}).Error; err != nil {
t.Fatalf("seed: %v", err)
}
for i := 0; i < 3; i++ {
if err := convertDeletedAt(db, "sys_user"); err != nil {
t.Fatalf("convert %d: %v", i, err)
}
}
}
// The point of the whole exercise: the constraint has to reject a second live
// row and accept one whose predecessor was deleted.
func TestUniqueIndexBindsLiveRowsOnly(t *testing.T) {
db := openWithOldSchema(t)
if err := db.Create(&oldUser{Username: "alice"}).Error; err != nil {
t.Fatalf("seed: %v", err)
}
if err := convertDeletedAt(db, "sys_user"); err != nil {
t.Fatalf("convert: %v", err)
}
if err := createUniqueIndex(db, "sys_user", "username", "uk_sys_user_username"); err != nil {
t.Fatalf("index: %v", err)
}
t.Run("a second live row is rejected", func(t *testing.T) {
err := db.Exec("INSERT INTO sys_user (username, deleted_at) VALUES ('alice', 0)").Error
if err == nil {
t.Fatal("a duplicate username was accepted")
}
})
t.Run("the name is free once the row is deleted", func(t *testing.T) {
if err := db.Exec("UPDATE sys_user SET deleted_at = ? WHERE username = 'alice'", time.Now().UnixMilli()).Error; err != nil {
t.Fatalf("delete: %v", err)
}
if err := db.Exec("INSERT INTO sys_user (username, deleted_at) VALUES ('alice', 0)").Error; err != nil {
t.Errorf("the name stayed taken after its row was deleted: %v", err)
}
})
t.Run("the same name can be deleted more than once", func(t *testing.T) {
if err := db.Exec("UPDATE sys_user SET deleted_at = ? WHERE deleted_at = 0", time.Now().UnixMilli()+1).Error; err != nil {
t.Errorf("a second deletion collided with the first: %v", err)
}
})
}
// A table that already holds duplicates cannot take the index, and the
// migration says which values rather than letting the index fail.
func TestRefusesWhenDuplicatesAlreadyExist(t *testing.T) {
db := openWithOldSchema(t)
for i := 0; i < 2; i++ {
if err := db.Create(&oldUser{Username: "alice"}).Error; err != nil {
t.Fatalf("seed: %v", err)
}
}
err := refuseOnDuplicates(db)
if err == nil {
t.Fatal("the migration accepted a table that already holds duplicates")
}
if !contains(err.Error(), "alice") {
t.Errorf("the error does not name the value: %v", err)
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (s == sub || len(sub) == 0 || indexOf(s, sub) >= 0)
}
func indexOf(s, sub string) int {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return i
}
}
return -1
}
// Why the column has to change at all, demonstrated rather than argued: the
// same index over the column as it was accepts both live rows, because each
// carries NULL and NULL is not equal to NULL. The constraint exists and binds
// nothing — which is worse than its absence, because it reads as protection.
func TestTheIndexOverANullableMarkerEnforcesNothing(t *testing.T) {
db := openWithOldSchema(t)
if err := db.Exec("CREATE UNIQUE INDEX uk_nullable ON sys_user (username, deleted_at)").Error; err != nil {
t.Fatalf("index: %v", err)
}
for i := 0; i < 2; i++ {
if err := db.Create(&oldUser{Username: "alice"}).Error; err != nil {
t.Fatalf("the nullable marker rejected a duplicate after all, which would make this migration unnecessary: %v", err)
}
}
var live int64
if err := db.Raw("SELECT COUNT(*) FROM sys_user WHERE deleted_at IS NULL").Scan(&live).Error; err != nil {
t.Fatalf("count: %v", err)
}
if live != 2 {
t.Fatalf("got %d live rows, want 2", live)
}
}
+1 -13
View File
@@ -62,19 +62,7 @@ func migrateModel() error {
if host == "" {
host = "*"
}
db := sdk.Runtime.GetDbByTenant(host)
if db == nil {
if len(sdk.Runtime.GetAllDb()) == 1 && host == "*" {
for k, v := range sdk.Runtime.GetAllDb() {
db = v
host = k
break
}
}
}
if db == nil {
return fmt.Errorf("未找到数据库配置")
}
db := sdk.Runtime.GetDbByKey(host)
if config.DatabasesConfig[host].Driver == "mysql" {
//初始化数据库时候用
db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
+1 -1
View File
@@ -46,7 +46,7 @@ func DeleteAction(control dto.Control) gin.HandlerFunc {
db = db.WithContext(c).Scopes(
Permission(object.TableName(), p),
).Where(req.GetId()).Delete(object)
if err = db.Error; err != nil {
if db.Error != nil {
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
response.Error(c, 500, err, "删除失败")
return
+1 -1
View File
@@ -44,7 +44,7 @@ func UpdateAction(control dto.Control) gin.HandlerFunc {
db = db.WithContext(c).Scopes(
Permission(object.TableName(), p),
).Where(req.GetId()).Updates(object)
if err = db.Error; err != nil {
if db.Error != nil {
log.Errorf("MsgID[%s] Update error: %s", msgID, err)
response.Error(c, 500, err, "更新失败")
return
+7 -7
View File
@@ -27,7 +27,7 @@ func (e *Api) AddError(err error) {
e.Errors = err
} else if err != nil {
e.Logger.Error(err)
e.Errors = fmt.Errorf("%v; %w", e.Errors, err)
e.Errors = fmt.Errorf("%v; %w", e.Error, err)
}
}
@@ -39,7 +39,7 @@ func (e *Api) MakeContext(c *gin.Context) *Api {
}
// GetLogger 获取上下文提供的日志
func (e *Api) GetLogger() *logger.Helper {
func (e Api) GetLogger() *logger.Helper {
return api.GetRequestLogger(e.Context)
}
@@ -81,7 +81,7 @@ func (e *Api) Bind(d interface{}, bindings ...binding.Binding) *Api {
}
// GetOrm 获取Orm DB
func (e *Api) GetOrm() (*gorm.DB, error) {
func (e Api) GetOrm() (*gorm.DB, error) {
db, err := pkg.GetOrm(e.Context)
if err != nil {
e.Error(500, err, "数据库连接获取失败")
@@ -115,21 +115,21 @@ func (e *Api) MakeService(c *service.Service) *Api {
}
// Error 通常错误数据处理
func (e *Api) Error(code int, err error, msg string) {
func (e Api) Error(code int, err error, msg string) {
response.Error(e.Context, code, err, msg)
}
// OK 通常成功数据处理
func (e *Api) OK(data interface{}, msg string) {
func (e Api) OK(data interface{}, msg string) {
response.OK(e.Context, data, msg)
}
// PageOK 分页数据处理
func (e *Api) PageOK(result interface{}, count int, pageIndex int, pageSize int, msg string) {
func (e Api) PageOK(result interface{}, count int, pageIndex int, pageSize int, msg string) {
response.PageOK(e.Context, result, count, pageIndex, pageSize, msg)
}
// Custom 兼容函数
func (e *Api) Custom(data gin.H) {
func (e Api) Custom(data gin.H) {
response.Custum(e.Context, data)
}
+3 -3
View File
@@ -58,8 +58,8 @@ func setupSimpleDatabase(host string, c *toolsConfig.Database) {
log.Info(pkg.Green(c.Driver + " connect success !"))
}
e := mycasbin.Setup(db, "")
e := mycasbin.Setup(db, "sys_")
sdk.Runtime.SetDbByTenant(host, db)
sdk.Runtime.SetCasbinByTenant(host, e)
sdk.Runtime.SetDb(host, db)
sdk.Runtime.SetCasbin(host, e)
}
+1
View File
@@ -1,4 +1,5 @@
//go:build !sqlite3
// +build !sqlite3
package database
+11 -7
View File
@@ -13,17 +13,21 @@ type GeneralDelDto struct {
func (g GeneralDelDto) GetIds() []int {
ids := make([]int, 0)
// Id 此前在 else 分支里被重复追加:仅传 Id 时会得到 [5 5],
// 同一条记录被执行两次删除
if g.Id > 0 {
if g.Id != 0 {
ids = append(ids, g.Id)
}
for _, id := range g.Ids {
if id > 0 {
ids = append(ids, id)
if len(g.Ids) > 0 {
for _, id := range g.Ids {
if id > 0 {
ids = append(ids, id)
}
}
} else {
if g.Id > 0 {
ids = append(ids, g.Id)
}
}
if len(ids) == 0 {
if len(ids) <= 0 {
//方式全部删除
ids = append(ids, 0)
}
-32
View File
@@ -1,32 +0,0 @@
package dto
import (
"reflect"
"testing"
)
// GetIds 曾在 else 分支中重复追加 Id:仅传 Id 时返回 [5 5],
// 导致删除接口对同一条记录执行两次。
func TestGeneralDelDtoGetIds(t *testing.T) {
cases := []struct {
name string
dto GeneralDelDto
want []int
}{
{"仅 Id", GeneralDelDto{Id: 5}, []int{5}},
{"仅 Ids", GeneralDelDto{Ids: []int{1, 2}}, []int{1, 2}},
{"Id 与 Ids 并存", GeneralDelDto{Id: 5, Ids: []int{1, 2}}, []int{5, 1, 2}},
{"Ids 含非正数被过滤", GeneralDelDto{Ids: []int{0, -1, 3}}, []int{3}},
{"Id 为 0 视为未传", GeneralDelDto{Id: 0, Ids: []int{7}}, []int{7}},
{"全部为空时回退到 0(全量删除约定)", GeneralDelDto{}, []int{0}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := c.dto.GetIds()
if !reflect.DeepEqual(got, c.want) {
t.Errorf("GetIds() = %v, want %v", got, c.want)
}
})
}
}
+3 -2
View File
@@ -2,10 +2,11 @@ package global
const (
// Version go-admin version info
Version = "2.4.0"
Version = "2.0.11"
)
var (
// Driver 数据库驱动
Source string
Driver string
DBName string
)
+3 -3
View File
@@ -1,7 +1,7 @@
package global
import (
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v2"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
@@ -9,8 +9,8 @@ import (
func LoadPolicy(c *gin.Context) (*casbin.SyncedEnforcer, error) {
log := api.GetRequestLogger(c)
if err := sdk.Runtime.GetCasbinByTenant(c.Request.Host).LoadPolicy(); err == nil {
return sdk.Runtime.GetCasbinByTenant(c.Request.Host), err
if err := sdk.Runtime.GetCasbinKey(c.Request.Host).LoadPolicy(); err == nil {
return sdk.Runtime.GetCasbinKey(c.Request.Host), err
} else {
log.Errorf("casbin rbac_model or policy init error, %s ", err.Error())
return nil, err
+11 -12
View File
@@ -6,23 +6,22 @@ import (
)
func GetClientIP(c *gin.Context) string {
// 优先从 X-Forwarded-For 获取 IP
ClientIP := c.ClientIP()
//fmt.Println("ClientIP:", ClientIP)
RemoteIP, _ := c.RemoteIP()
//fmt.Println("RemoteIP:", RemoteIP)
ip := c.Request.Header.Get("X-Forwarded-For")
if ip == "" || strings.Contains(ip, "127.0.0.1") {
// 如果为空或为本地地址,则尝试从 X-Real-IP 获取
if strings.Contains(ip, "127.0.0.1") || ip == "" {
ip = c.Request.Header.Get("X-real-ip")
}
if ip == "" {
// 如果仍为空,则使用 RemoteIP
ip = c.RemoteIP()
}
if ip == "" || ip == "127.0.0.1" {
// 如果仍为空或为本地地址,则使用 ClientIP
ip = c.ClientIP()
}
if ip == "" {
// 最后兜底为本地地址
ip = "127.0.0.1"
}
if RemoteIP.String() != "127.0.0.1" {
ip = RemoteIP.String()
}
if ClientIP != "127.0.0.1" {
ip = ClientIP
}
return ip
}
+2 -12
View File
@@ -2,8 +2,8 @@ package middleware
import (
"fmt"
"go-admin/common"
"net/http"
"runtime"
"strconv"
"strings"
"time"
@@ -34,24 +34,14 @@ func CustomError(c *gin.Context) {
c.Request.URL,
statusCode,
c.Request.RequestURI,
c.ClientIP(),
common.GetClientIP(c),
p[2],
)
c.JSON(http.StatusOK, gin.H{
"code": statusCode,
"msg": p[2],
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": 500,
"msg": errStr,
})
}
case runtime.Error:
c.JSON(http.StatusOK, gin.H{
"code": 500,
"msg": errStr.Error(),
})
default:
panic(err)
}
+1 -1
View File
@@ -6,6 +6,6 @@ import (
)
func WithContextDb(c *gin.Context) {
c.Set("db", sdk.Runtime.GetDbByTenant(c.Request.Host).WithContext(c))
c.Set("db", sdk.Runtime.GetDbByKey(c.Request.Host).WithContext(c))
c.Next()
}

Some files were not shown because too many files have changed in this diff Show More