Merge pull request #56 from wenjianzhang/dev

1. 添加js代码模板
2. 添加vue代码模板
1. 使用cmd进行程序配置
1. 调整代码结构
1. 添加token过期时间配置项
1. 修复bug,含搜索条件等
This commit is contained in:
wenjianzhang authored and GitHub committed 2020-05-01 15:01:08 +08:00
commit 95de5a51cc
86 files changed
+2290 -1365

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ temp/
!temp
vendor
config/settings.dev.yml
go-admin
+14
View File
@@ -0,0 +1,14 @@
PROJECT:=go-admin
.PHONY: build
build:
CGO_ENABLED=0 go build -o go-admin main.go
build-sqlite:
go build -tags sqlite3 -o go-admin main.go
#.PHONY: test
#test:
# go test -v ./... -cover
#.PHONY: docker
#docker:
# docker build . -t go-admin:latest
+34 -23
View File
@@ -16,7 +16,7 @@
</p>
[English](./README.en.md) | 简体中文
[English](https://github.com/wenjianzhang/go-admin/blob/master/README.en.md) | 简体中文
##### 基于Gin + Vue + Element UI的前后端分离权限管理系统
@@ -45,6 +45,8 @@
- 表单构建工具
- 多命令模式
- TODO: 单元测试
@@ -71,29 +73,26 @@
settings:
application:
# 项目启动环境
env: dev
# 当 env:demo 时,GET以外的请求操作提示
envmsg: "谢谢您的参与,但为了大家更好的体验,所以本次提交就算了吧!"
# 主机ip 或者域名,默认0.0.0.0
host: 0.0.0.0
# 是否需要初始化数据库结构以及基本数据;true:需要;false:不需要
isinit: false
# log存放路径
logpath: temp/logs/log.log
mode: dev # dev开发环境 test测试环境 prod线上环境;当 mode:demo 时,GET以外的请求操作提示
demomsg: "谢谢您的参与,但为了大家更好的体验,所以本次提交就算了吧!"
host: 0.0.0.0 # 主机ip 或者域名,默认0.0.0.0
# 服务名称
name: go-admin
# 服务端口
port: 8000
readtimeout: 1
writertimeout: 2
log:
# 日志文件存放路径
dir: temp/logs
jwt:
# JWT加密字符串
jwtsecret: go-admin
secret: go-admin
# 过期时间单位:秒
timeout: 3600
database:
# 数据库名称
database: dbname
name: dbname
# 数据库类型
dbtype: mysql
# 数据库地址
@@ -111,7 +110,7 @@ settings:
## 📦 本地开发
首次启动说明
### 首次启动说明
```bash
# 获取代码
@@ -128,29 +127,32 @@ vi ./config/setting.yml (更改isinit和数据库连接)
# 1. 配置文件中修改数据库信息
# 注意: settings.database 下对应的配置数据)
# 2. 确认数据库初始化参数
# 注意: settings.application.isinit 如果是首次启动,请把当前值设置成true,系统会自动初始化数据库结构以及基本的数据信息;
# 3. 确认log路径
# 2. 确认log路径
```
### 初始化数据库,以及服务启动
```
# 首次配置需要初始化数据库资源信息
./go-admin migrate -c config/settings.yml -m dev
# 启动项目,也可以用IDE进行调试
./go-admin
./go-admin server -c config/settings.yml -p 8000 -m dev
```
[在线文档](https://wenjianzhang.github.io/go-admin-site)
文档生成
### 文档生成
```bash
swag init
```
如果没有swag命令 go get安装一下即可
```bash
# 如果没有swag命令 go get安装一下即可
go get -u github.com/swaggo/swag/cmd/swag
```
交叉编译
### 交叉编译
```bash
env GOOS=windows GOARCH=amd64 go build main.go
@@ -167,6 +169,15 @@ env GOOS=linux GOARCH=amd64 go build main.go
## 📈 版本
### 2020-04-23 新功能及优化
1. 添加单服务命令
2. 添加单数据库数据化命令
3. 调整项目结构
3. 部分代码优化
3. 添加根接口
4. 其他已知bug的修复
### 2020-04-13 新功能及优化
1. 数据库初始化方式改为gorm 迁移方式
@@ -212,7 +223,7 @@ env GOOS=linux GOARCH=amd64 go build main.go
</tr>
<tr>
<td>微信</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=1affb445445bd442312fcad9a927007db74a0cd4380bbc08a6c97d2691744869"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流甲号" title="go-admin技术交流甲号"></a>已满</td>
<td>此群已满</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
</tr>
</table>
+16 -17
View File
@@ -4,9 +4,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"net/http"
)
@@ -18,7 +17,7 @@ import (
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/loginloglist [get]
// @Security
func GetLoginLogList(c *gin.Context) {
@@ -29,19 +28,19 @@ func GetLoginLogList(c *gin.Context) {
size := c.Request.FormValue("pageSize")
if size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
index := c.Request.FormValue("pageIndex")
if index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.Username = c.Request.FormValue("username")
data.Status = c.Request.FormValue("status")
data.Ipaddr = c.Request.FormValue("ipaddr")
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
@@ -58,14 +57,14 @@ func GetLoginLogList(c *gin.Context) {
// @Description 获取JSON
// @Tags 登录日志
// @Param infoId path int true "infoId"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/loginlog/{infoId} [get]
// @Security
func GetLoginLog(c *gin.Context) {
var LoginLog models.LoginLog
LoginLog.InfoId, _ = utils.StringToInt(c.Param("infoId"))
LoginLog.InfoId, _ = tools.StringToInt(c.Param("infoId"))
result, err := LoginLog.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
@@ -85,9 +84,9 @@ func GetLoginLog(c *gin.Context) {
func InsertLoginLog(c *gin.Context) {
var data models.LoginLog
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "", 500)
tools.HasError(err, "", 500)
result, err := data.Create()
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -106,9 +105,9 @@ func InsertLoginLog(c *gin.Context) {
func UpdateLoginLog(c *gin.Context) {
var data models.LoginLog
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
result, err := data.Update(data.InfoId)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -123,10 +122,10 @@ func UpdateLoginLog(c *gin.Context) {
// @Router /api/v1/loginlog/{infoId} [delete]
func DeleteLoginLog(c *gin.Context) {
var data models.LoginLog
data.UpdateBy = utils.GetUserIdStr(c)
IDS := utils.IdsStrToIdsIntGroup("infoId", c)
data.UpdateBy = tools.GetUserIdStr(c)
IDS := tools.IdsStrToIdsIntGroup("infoId", c)
_, err := data.BatchDelete(IDS)
pkg.HasError(err, "修改失败", 500)
tools.HasError(err, "修改失败", 500)
var res app.Response
res.Msg = "删除成功"
c.JSON(http.StatusOK, res.ReturnOK())
+14 -15
View File
@@ -4,9 +4,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"net/http"
)
@@ -18,7 +17,7 @@ import (
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/operloglist [get]
// @Security
func GetOperLogList(c *gin.Context) {
@@ -29,19 +28,19 @@ func GetOperLogList(c *gin.Context) {
size := c.Request.FormValue("pageSize")
if size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
index := c.Request.FormValue("pageIndex")
if index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.OperName = c.Request.FormValue("operName")
data.Status = c.Request.FormValue("status")
data.OperIp = c.Request.FormValue("operIp")
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
@@ -59,14 +58,14 @@ func GetOperLogList(c *gin.Context) {
// @Description 获取JSON
// @Tags 登录日志
// @Param infoId path int true "infoId"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/operlog/{infoId} [get]
// @Security
func GetOperLog(c *gin.Context) {
var OperLog models.SysOperLog
OperLog.OperId, _ = utils.StringToInt(c.Param("operId"))
OperLog.OperId, _ = tools.StringToInt(c.Param("operId"))
result, err := OperLog.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -85,9 +84,9 @@ func GetOperLog(c *gin.Context) {
func InsertOperLog(c *gin.Context) {
var data models.SysOperLog
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "", 500)
tools.HasError(err, "", 500)
result, err := data.Create()
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -102,10 +101,10 @@ func InsertOperLog(c *gin.Context) {
// @Router /api/v1/operlog/{operId} [delete]
func DeleteOperLog(c *gin.Context) {
var data models.SysOperLog
data.UpdateBy = utils.GetUserIdStr(c)
IDS := utils.IdsStrToIdsIntGroup("operId", c)
data.UpdateBy = tools.GetUserIdStr(c)
IDS := tools.IdsStrToIdsIntGroup("operId", c)
_, err := data.BatchDelete(IDS)
pkg.HasError(err, "删除失败", 500)
tools.HasError(err, "删除失败", 500)
var res app.Response
res.Msg = "删除成功"
c.JSON(http.StatusOK, res.ReturnOK())
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"go-admin/pkg/app"
"go-admin/tools/app"
"runtime"
)
+4 -4
View File
@@ -2,14 +2,14 @@ package system
import (
"github.com/gin-gonic/gin"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/captcha"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/captcha"
)
func GenerateCaptchaHandler(c *gin.Context) {
id, b64s, err := captcha.DriverDigitFunc()
pkg.HasError(err, "验证码获取失败", 500)
tools.HasError(err, "验证码获取失败", 500)
app.Custum(c, gin.H{
"code": 200,
"data": b64s,
+24 -25
View File
@@ -4,10 +4,9 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/app/msg"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/app/msg"
"net/http"
)
@@ -19,7 +18,7 @@ import (
// @Param configType query string false "configType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/configList [get]
// @Security
func GetConfigList(c *gin.Context) {
@@ -29,19 +28,19 @@ func GetConfigList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.ConfigKey = c.Request.FormValue("configKey")
data.ConfigName = c.Request.FormValue("configName")
data.ConfigType = c.Request.FormValue("configType")
data.DataScope = utils.GetUserIdStr(c)
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
@@ -59,14 +58,14 @@ func GetConfigList(c *gin.Context) {
// @Description 获取JSON
// @Tags 配置
// @Param configId path int true "配置编码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/config/{configId} [get]
// @Security
func GetConfig(c *gin.Context) {
var Config models.SysConfig
Config.ConfigId, _ = utils.StringToInt(c.Param("configId"))
Config.ConfigId, _ = tools.StringToInt(c.Param("configId"))
result, err := Config.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
@@ -78,14 +77,14 @@ func GetConfig(c *gin.Context) {
// @Description 获取JSON
// @Tags 配置
// @Param configKey path int true "configKey"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/configKey/{configKey} [get]
// @Security
func GetConfigByConfigKey(c *gin.Context) {
var Config models.SysConfig
Config.ConfigKey = c.Param("configKey")
result, err := Config.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c, result,result.ConfigValue)
}
@@ -103,10 +102,10 @@ func GetConfigByConfigKey(c *gin.Context) {
func InsertConfig(c *gin.Context) {
var data models.SysConfig
err := c.BindWith(&data, binding.JSON)
data.CreateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", 500)
data.CreateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", 500)
result, err := data.Create()
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.OK(c, result,"")
}
@@ -116,7 +115,7 @@ func InsertConfig(c *gin.Context) {
// @Tags 配置
// @Accept application/json
// @Product application/json
// @Param data body models.Config true "body"
// @Param data body models.SysConfig true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/config [put]
@@ -124,10 +123,10 @@ func InsertConfig(c *gin.Context) {
func UpdateConfig(c *gin.Context) {
var data models.SysConfig
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "数据解析失败", -1)
data.UpdateBy = utils.GetUserIdStr(c)
tools.HasError(err, "数据解析失败", -1)
data.UpdateBy = tools.GetUserIdStr(c)
result, err := data.Update(data.ConfigId)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.OK(c, result,"")
}
@@ -140,10 +139,10 @@ func UpdateConfig(c *gin.Context) {
// @Router /api/v1/config/{configId} [delete]
func DeleteConfig(c *gin.Context) {
var data models.SysConfig
id, err := utils.StringToInt(c.Param("configId"))
data.UpdateBy = utils.GetUserIdStr(c)
id, err := tools.StringToInt(c.Param("configId"))
data.UpdateBy = tools.GetUserIdStr(c)
data.ConfigId = id
_, err = data.Delete()
pkg.HasError(err, "修改失败", 500)
app.OK(c, nil,msg.DeletedSuccess)
tools.HasError(err, "修改失败", 500)
app.OK(c, nil, msg.DeletedSuccess)
}
+28 -29
View File
@@ -4,10 +4,9 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/app/msg"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/app/msg"
)
// @Summary 分页部门列表数据
@@ -16,17 +15,17 @@ import (
// @Param name query string false "name"
// @Param id query string false "id"
// @Param position query string false "position"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/deptList [get]
// @Security
func GetDeptList(c *gin.Context) {
var Dept models.Dept
Dept.DeptName = c.Request.FormValue("deptName")
Dept.Status = c.Request.FormValue("status")
Dept.DeptId, _ = utils.StringToInt(c.Request.FormValue("deptId"))
Dept.DataScope = utils.GetUserIdStr(c)
Dept.DeptId, _ = tools.StringToInt(c.Request.FormValue("deptId"))
Dept.DataScope = tools.GetUserIdStr(c)
result, err := Dept.SetDept(true)
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
}
@@ -34,9 +33,9 @@ func GetDeptTree(c *gin.Context) {
var Dept models.Dept
Dept.DeptName = c.Request.FormValue("deptName")
Dept.Status= c.Request.FormValue("status")
Dept.DeptId, _ = utils.StringToInt(c.Request.FormValue("deptId"))
Dept.DeptId, _ = tools.StringToInt(c.Request.FormValue("deptId"))
result, err := Dept.SetDept(false)
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
}
@@ -45,16 +44,16 @@ func GetDeptTree(c *gin.Context) {
// @Tags 部门
// @Param deptId path string false "deptId"
// @Param position query string false "position"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dept/{deptId} [get]
// @Security
func GetDept(c *gin.Context) {
var Dept models.Dept
Dept.DeptId, _ = utils.StringToInt(c.Param("deptId"))
Dept.DataScope = utils.GetUserIdStr(c)
Dept.DeptId, _ = tools.StringToInt(c.Param("deptId"))
Dept.DataScope = tools.GetUserIdStr(c)
result, err := Dept.Get()
pkg.HasError(err, msg.NotFound, 404)
app.OK(c,result,msg.GetSuccess)
tools.HasError(err, msg.NotFound, 404)
app.OK(c,result, msg.GetSuccess)
}
// @Summary 添加部门
@@ -70,11 +69,11 @@ func GetDept(c *gin.Context) {
func InsertDept(c *gin.Context) {
var data models.Dept
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "", 500)
data.CreateBy = utils.GetUserIdStr(c)
tools.HasError(err, "", 500)
data.CreateBy = tools.GetUserIdStr(c)
result, err := data.Create()
pkg.HasError(err, "", -1)
app.OK(c,result,msg.CreatedSuccess)
tools.HasError(err, "", -1)
app.OK(c,result, msg.CreatedSuccess)
}
// @Summary 修改部门
@@ -91,11 +90,11 @@ func InsertDept(c *gin.Context) {
func UpdateDept(c *gin.Context) {
var data models.Dept
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "", -1)
data.UpdateBy = utils.GetUserIdStr(c)
tools.HasError(err, "", -1)
data.UpdateBy = tools.GetUserIdStr(c)
result, err := data.Update(data.DeptId)
pkg.HasError(err, "", -1)
app.OK(c,result,msg.UpdatedSuccess)
tools.HasError(err, "", -1)
app.OK(c,result, msg.UpdatedSuccess)
}
// @Summary 删除部门
@@ -107,23 +106,23 @@ func UpdateDept(c *gin.Context) {
// @Router /api/v1/dept/{id} [delete]
func DeleteDept(c *gin.Context) {
var data models.Dept
id, err := utils.StringToInt(c.Param("id"))
id, err := tools.StringToInt(c.Param("id"))
_, err = data.Delete(id)
pkg.HasError(err, "删除失败", 500)
app.OK(c,"",msg.DeletedSuccess)
tools.HasError(err, "删除失败", 500)
app.OK(c,"", msg.DeletedSuccess)
}
func GetDeptTreeRoleselect(c *gin.Context) {
var Dept models.Dept
var SysRole models.SysRole
id, err := utils.StringToInt(c.Param("roleId"))
id, err := tools.StringToInt(c.Param("roleId"))
SysRole.RoleId = id
result, err := Dept.SetDeptLable()
pkg.HasError(err, msg.NotFound, -1)
tools.HasError(err, msg.NotFound, -1)
menuIds := make([]int, 0)
if id != 0 {
menuIds, err = SysRole.GetRoleDeptId()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
}
app.Custum(c,gin.H{
"code": 200,
+22 -23
View File
@@ -4,9 +4,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"net/http"
)
@@ -18,7 +17,7 @@ import (
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data/list [get]
// @Security
func GetDictDataList(c *gin.Context) {
@@ -28,21 +27,21 @@ func GetDictDataList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.DictLabel = c.Request.FormValue("dictLabel")
data.Status = c.Request.FormValue("status")
data.DictType = c.Request.FormValue("dictType")
id := c.Request.FormValue("dictCode")
data.DictCode, _ = utils.StringToInt(id)
data.DataScope = utils.GetUserIdStr(c)
data.DictCode, _ = tools.StringToInt(id)
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
@@ -60,15 +59,15 @@ func GetDictDataList(c *gin.Context) {
// @Description 获取JSON
// @Tags 字典数据
// @Param dictCode path int true "字典编码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/data/{dictCode} [get]
// @Security
func GetDictData(c *gin.Context) {
var DictData models.DictData
DictData.DictLabel = c.Request.FormValue("dictLabel")
DictData.DictCode, _ = utils.StringToInt(c.Param("dictCode"))
DictData.DictCode, _ = tools.StringToInt(c.Param("dictCode"))
result, err := DictData.GetByCode()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -78,14 +77,14 @@ func GetDictData(c *gin.Context) {
// @Description 获取JSON
// @Tags 字典数据
// @Param dictType path int true "dictType"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/databyType/{dictType} [get]
// @Security
func GetDictDataByDictType(c *gin.Context) {
var DictData models.DictData
DictData.DictType = c.Param("dictType")
result, err := DictData.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
@@ -105,10 +104,10 @@ func GetDictDataByDictType(c *gin.Context) {
func InsertDictData(c *gin.Context) {
var data models.DictData
err := c.BindWith(&data, binding.JSON)
data.CreateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", 500)
data.CreateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", 500)
result, err := data.Create()
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -127,10 +126,10 @@ func InsertDictData(c *gin.Context) {
func UpdateDictData(c *gin.Context) {
var data models.DictData
err := c.BindWith(&data, binding.JSON)
data.UpdateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", -1)
data.UpdateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", -1)
result, err := data.Update(data.DictCode)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -145,10 +144,10 @@ func UpdateDictData(c *gin.Context) {
// @Router /api/v1/dict/data/{dictCode} [delete]
func DeleteDictData(c *gin.Context) {
var data models.DictData
id, err := utils.StringToInt(c.Param("dictCode"))
data.UpdateBy = utils.GetUserIdStr(c)
id, err := tools.StringToInt(c.Param("dictCode"))
data.UpdateBy = tools.GetUserIdStr(c)
_, err = data.Delete(id)
pkg.HasError(err, "修改失败", 500)
tools.HasError(err, "修改失败", 500)
var res app.Response
res.Msg = "删除成功"
+22 -23
View File
@@ -4,9 +4,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"net/http"
)
@@ -18,7 +17,7 @@ import (
// @Param dictType query string false "dictType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type/list [get]
// @Security
func GetDictTypeList(c *gin.Context) {
@@ -28,20 +27,20 @@ func GetDictTypeList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.DictName = c.Request.FormValue("dictName")
id := c.Request.FormValue("dictId")
data.DictId, _ = utils.StringToInt(id)
data.DictId, _ = tools.StringToInt(id)
data.DictType = c.Request.FormValue("dictType")
data.DataScope = utils.GetUserIdStr(c)
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
@@ -58,15 +57,15 @@ func GetDictTypeList(c *gin.Context) {
// @Description 获取JSON
// @Tags 字典类型
// @Param dictId path int true "字典类型编码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/dict/type/{dictId} [get]
// @Security
func GetDictType(c *gin.Context) {
var DictType models.DictType
DictType.DictName = c.Request.FormValue("dictName")
DictType.DictId, _ = utils.StringToInt(c.Param("dictId"))
DictType.DictId, _ = tools.StringToInt(c.Param("dictId"))
result, err := DictType.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -76,9 +75,9 @@ func GetDictType(c *gin.Context) {
func GetDictTypeOptionSelect(c *gin.Context) {
var DictType models.DictType
DictType.DictName = c.Request.FormValue("dictName")
DictType.DictId, _ = utils.StringToInt(c.Param("dictId"))
DictType.DictId, _ = tools.StringToInt(c.Param("dictId"))
result, err := DictType.GetList()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -97,10 +96,10 @@ func GetDictTypeOptionSelect(c *gin.Context) {
func InsertDictType(c *gin.Context) {
var data models.DictType
err := c.BindWith(&data, binding.JSON)
data.CreateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", 500)
data.CreateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", 500)
result, err := data.Create()
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -119,10 +118,10 @@ func InsertDictType(c *gin.Context) {
func UpdateDictType(c *gin.Context) {
var data models.DictType
err := c.BindWith(&data, binding.JSON)
data.UpdateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", -1)
data.UpdateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", -1)
result, err := data.Update(data.DictId)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
@@ -137,10 +136,10 @@ func UpdateDictType(c *gin.Context) {
// @Router /api/v1/dict/type/{dictId} [delete]
func DeleteDictType(c *gin.Context) {
var data models.DictType
id, err := utils.StringToInt(c.Param("dictId"))
data.UpdateBy = utils.GetUserIdStr(c)
id, err := tools.StringToInt(c.Param("dictId"))
data.UpdateBy = tools.GetUserIdStr(c)
_, err = data.Delete(id)
pkg.HasError(err, "修改失败", 500)
tools.HasError(err, "修改失败", 500)
c.JSON(http.StatusOK, gin.H{
"code": 200,
+40
View File
@@ -0,0 +1,40 @@
package system
import(
"github.com/gin-gonic/gin"
)
const INDEX = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GO-ADMIN欢迎您</title>
<style>
body{
margin:0;
padding:0;
overflow-y:hidden
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
window.onerror=function(){return true;}
$(function(){
headerH = 0;
var h=$(window).height();
$("#iframe").height((h-headerH)+"px");
});
</script>
</head>
<body>
<iframe id="iframe" frameborder="0" src="http://doc.zhangwj.com/go-admin-site/" style="width:100%;"></iframe>
</body>
</html>
`
func HelloWorld(c *gin.Context){
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(200, INDEX)
}
+7 -8
View File
@@ -3,24 +3,23 @@ package system
import (
"github.com/gin-gonic/gin"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
)
func GetInfo(c *gin.Context) {
var roles = make([]string, 1)
roles[0] = utils.GetRoleName(c)
roles[0] = tools.GetRoleName(c)
var permissions = make([]string, 1)
permissions[0] = "*:*:*"
RoleMenu := models.RoleMenu{}
RoleMenu.RoleId = utils.GetRoleId(c)
RoleMenu.RoleId = tools.GetRoleId(c)
var mp = make(map[string]interface{})
mp["roles"] = roles
if utils.GetRoleName(c) == "admin" || utils.GetRoleName(c) == "系统管理员" {
if tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员" {
mp["permissions"] = permissions
} else {
list, _ := RoleMenu.GetPermis()
@@ -28,9 +27,9 @@ func GetInfo(c *gin.Context) {
}
sysuser := models.SysUser{}
sysuser.UserId = utils.GetUserId(c)
sysuser.UserId = tools.GetUserId(c)
user, err := sysuser.Get()
pkg.HasError(err, "", 500)
tools.HasError(err, "", 500)
mp["introduction"] = " am a super administrator"
+34 -33
View File
@@ -4,9 +4,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
)
// @Summary Menu列表数据
@@ -20,11 +19,13 @@ import (
func GetMenuList(c *gin.Context) {
var Menu models.Menu
Menu.MenuName = c.Request.FormValue("menuName")
Menu.DataScope = utils.GetUserIdStr(c)
Menu.Visible = c.Request.FormValue("visible")
Menu.Title = c.Request.FormValue("title")
Menu.DataScope = tools.GetUserIdStr(c)
result, err := Menu.SetMenu()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
app.OK(c, result, "")
}
// @Summary Menu列表数据
@@ -37,26 +38,26 @@ func GetMenuList(c *gin.Context) {
// @Security Bearer
func GetMenu(c *gin.Context) {
var data models.Menu
id, err := utils.StringToInt(c.Param("id"))
id, err := tools.StringToInt(c.Param("id"))
data.MenuId = id
result, err := data.GetByMenuId()
pkg.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c, result, "")
}
func GetMenuTreeRoleselect(c *gin.Context) {
var Menu models.Menu
var SysRole models.SysRole
id, err := utils.StringToInt(c.Param("roleId"))
id, err := tools.StringToInt(c.Param("roleId"))
SysRole.RoleId = id
result, err := Menu.SetMenuLable()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
menuIds := make([]int, 0)
if id != 0 {
menuIds, err = SysRole.GetRoleMeunId()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
}
app.Custum(c,gin.H{
app.Custum(c, gin.H{
"code": 200,
"menus": result,
"checkedKeys": menuIds,
@@ -75,8 +76,8 @@ func GetMenuTreeRoleselect(c *gin.Context) {
func GetMenuTreeelect(c *gin.Context) {
var data models.Menu
result, err := data.SetMenuLable()
pkg.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c, result, "")
}
// @Summary 创建菜单
@@ -97,11 +98,11 @@ func GetMenuTreeelect(c *gin.Context) {
func InsertMenu(c *gin.Context) {
var data models.Menu
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "抱歉未找到相关信息", -1)
data.CreateBy = utils.GetUserIdStr(c)
tools.HasError(err, "抱歉未找到相关信息", -1)
data.CreateBy = tools.GetUserIdStr(c)
result, err := data.Create()
pkg.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c, result, "")
}
// @Summary 修改菜单
@@ -118,11 +119,11 @@ func InsertMenu(c *gin.Context) {
func UpdateMenu(c *gin.Context) {
var data models.Menu
err2 := c.BindWith(&data, binding.JSON)
data.UpdateBy = utils.GetUserIdStr(c)
pkg.HasError(err2, "修改失败", -1)
data.UpdateBy = tools.GetUserIdStr(c)
tools.HasError(err2, "修改失败", -1)
_, err := data.Update(data.MenuId)
pkg.HasError(err, "", 501)
app.OK(c,"","修改成功")
tools.HasError(err, "", 501)
app.OK(c, "", "修改成功")
}
@@ -135,11 +136,11 @@ func UpdateMenu(c *gin.Context) {
// @Router /api/v1/menu/{id} [delete]
func DeleteMenu(c *gin.Context) {
var data models.Menu
id, err := utils.StringToInt(c.Param("id"))
data.UpdateBy = utils.GetUserIdStr(c)
id, err := tools.StringToInt(c.Param("id"))
data.UpdateBy = tools.GetUserIdStr(c)
_, err = data.Delete(id)
pkg.HasError(err, "删除失败", 500)
app.OK(c,"","删除成功")
tools.HasError(err, "删除失败", 500)
app.OK(c, "", "删除成功")
}
// @Summary 根据角色名称获取菜单列表数据(左菜单使用)
@@ -152,9 +153,9 @@ func DeleteMenu(c *gin.Context) {
// @Security Bearer
func GetMenuRole(c *gin.Context) {
var Menu models.Menu
result, err := Menu.SetMenuRole(utils.GetRoleName(c))
pkg.HasError(err, "获取失败", 500)
app.OK(c,result,"")
result, err := Menu.SetMenuRole(tools.GetRoleName(c))
tools.HasError(err, "获取失败", 500)
app.OK(c, result, "")
}
// @Summary 获取角色对应的菜单id数组
@@ -168,8 +169,8 @@ func GetMenuRole(c *gin.Context) {
func GetMenuIDS(c *gin.Context) {
var data models.RoleMenu
data.RoleName = c.GetString("role")
data.UpdateBy = utils.GetUserIdStr(c)
data.UpdateBy = tools.GetUserIdStr(c)
result, err := data.GetIDS()
pkg.HasError(err, "获取失败", 500)
app.OK(c,result,"")
tools.HasError(err, "获取失败", 500)
app.OK(c, result, "")
}
+20 -21
View File
@@ -3,9 +3,8 @@ package system
import (
"github.com/gin-gonic/gin"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
)
// @Summary 职位列表数据
@@ -14,7 +13,7 @@ import (
// @Param name query string false "name"
// @Param id query string false "id"
// @Param position query string false "position"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post [get]
// @Security
func GetPostList(c *gin.Context) {
@@ -24,21 +23,21 @@ func GetPostList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.PostName = c.Request.FormValue("postName")
id := c.Request.FormValue("postId")
data.PostId, _ = utils.StringToInt(id)
data.PostId, _ = tools.StringToInt(id)
data.PostName = c.Request.FormValue("postName")
data.DataScope = utils.GetUserIdStr(c)
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.PageOK(c, result, count, pageIndex, pageSize, "")
}
@@ -46,14 +45,14 @@ func GetPostList(c *gin.Context) {
// @Description 获取JSON
// @Tags 字典数据
// @Param postId path int true "postId"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/post/{postId} [get]
// @Security
func GetPost(c *gin.Context) {
var Post models.Post
Post.PostId, _ = utils.StringToInt(c.Param("postId"))
Post.PostId, _ = tools.StringToInt(c.Param("postId"))
result, err := Post.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c,result,"")
}
@@ -70,10 +69,10 @@ func GetPost(c *gin.Context) {
func InsertPost(c *gin.Context) {
var data models.Post
err := c.Bind(&data)
data.CreateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", 500)
data.CreateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", 500)
result, err := data.Create()
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.OK(c,result,"")
}
@@ -91,10 +90,10 @@ func UpdatePost(c *gin.Context) {
var data models.Post
err := c.Bind(&data)
data.UpdateBy = utils.GetUserIdStr(c)
pkg.HasError(err, "", -1)
data.UpdateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", -1)
result, err := data.Update(data.PostId)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.OK(c,result,"修改成功")
}
@@ -107,9 +106,9 @@ func UpdatePost(c *gin.Context) {
// @Router /api/v1/post/{postId} [delete]
func DeletePost(c *gin.Context) {
var data models.Post
id, err := utils.StringToInt(c.Param("postId"))
data.UpdateBy = utils.GetUserIdStr(c)
id, err := tools.StringToInt(c.Param("postId"))
data.UpdateBy = tools.GetUserIdStr(c)
_, err = data.Delete(id)
pkg.HasError(err, "删除失败", 500)
tools.HasError(err, "删除失败", 500)
app.OK(c,"","删除成功")
}
+26 -27
View File
@@ -4,9 +4,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
)
// @Summary 角色列表数据
@@ -17,7 +16,7 @@ import (
// @Param roleKey query string false "roleKey"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/rolelist [get]
// @Security
func GetRoleList(c *gin.Context) {
@@ -27,19 +26,19 @@ func GetRoleList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.RoleKey = c.Request.FormValue("roleKey")
data.RoleName = c.Request.FormValue("roleName")
data.Status = c.Request.FormValue("status")
data.DataScope = utils.GetUserIdStr(c)
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.PageOK(c, result, count, pageIndex, pageSize, "")
}
@@ -54,11 +53,11 @@ func GetRoleList(c *gin.Context) {
// @Security Bearer
func GetRole(c *gin.Context) {
var Role models.SysRole
Role.RoleId, _ = utils.StringToInt(c.Param("roleId"))
Role.RoleId, _ = tools.StringToInt(c.Param("roleId"))
result, err := Role.Get()
menuIds := make([]int, 0)
menuIds, err = Role.GetRoleMeunId()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
result.MenuIds = menuIds
app.OK(c, result, "")
@@ -69,21 +68,21 @@ func GetRole(c *gin.Context) {
// @Tags 角色/Role
// @Accept application/json
// @Product application/json
// @Param data body models.Config true "data"
// @Param data body models.SysRole true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/role [post]
func InsertRole(c *gin.Context) {
var data models.SysRole
data.CreateBy = utils.GetUserIdStr(c)
data.CreateBy = tools.GetUserIdStr(c)
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "", 500)
tools.HasError(err, "", 500)
id, err := data.Insert()
data.RoleId = id
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
var t models.RoleMenu
_, err = t.Insert(id, data.MenuIds)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.OK(c, data, "添加成功")
}
@@ -98,32 +97,32 @@ func InsertRole(c *gin.Context) {
// @Router /api/v1/role [put]
func UpdateRole(c *gin.Context) {
var data models.SysRole
data.UpdateBy = utils.GetUserIdStr(c)
data.UpdateBy = tools.GetUserIdStr(c)
err := c.Bind(&data)
pkg.HasError(err, "数据解析失败", -1)
tools.HasError(err, "数据解析失败", -1)
result, err := data.Update(data.RoleId)
var t models.RoleMenu
_, err = t.DeleteRoleMenu(data.RoleId)
pkg.HasError(err, "添加失败1", -1)
tools.HasError(err, "添加失败1", -1)
_, err2 := t.Insert(data.RoleId, data.MenuIds)
pkg.HasError(err2, "添加失败2", -1)
tools.HasError(err2, "添加失败2", -1)
app.OK(c, result, "修改成功")
}
func UpdateRoleDataScope(c *gin.Context) {
var data models.SysRole
data.UpdateBy = utils.GetUserIdStr(c)
data.UpdateBy = tools.GetUserIdStr(c)
err := c.Bind(&data)
pkg.HasError(err, "数据解析失败", -1)
tools.HasError(err, "数据解析失败", -1)
result, err := data.Update(data.RoleId)
var t models.SysRoleDept
_, err = t.DeleteRoleDept(data.RoleId)
pkg.HasError(err, "添加失败1", -1)
tools.HasError(err, "添加失败1", -1)
if data.DataScope == "2" {
_, err2 := t.Insert(data.RoleId, data.DeptIds)
pkg.HasError(err2, "添加失败2", -1)
tools.HasError(err2, "添加失败2", -1)
}
app.OK(c, result, "修改成功")
}
@@ -137,13 +136,13 @@ func UpdateRoleDataScope(c *gin.Context) {
// @Router /api/v1/role/{roleId} [delete]
func DeleteRole(c *gin.Context) {
var Role models.SysRole
Role.UpdateBy = utils.GetUserIdStr(c)
Role.UpdateBy = tools.GetUserIdStr(c)
IDS := utils.IdsStrToIdsIntGroup("roleId", c)
IDS := tools.IdsStrToIdsIntGroup("roleId", c)
_, err := Role.BatchDelete(IDS)
pkg.HasError(err, "删除失败1", -1)
tools.HasError(err, "删除失败1", -1)
var t models.RoleMenu
_, err = t.BatchDeleteRoleMenu(IDS)
pkg.HasError(err, "删除失败1", -1)
tools.HasError(err, "删除失败1", -1)
app.OK(c, "", "删除成功")
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"fmt"
"github.com/gin-gonic/gin"
"go-admin/models"
"go-admin/pkg/app"
"go-admin/tools/app"
"net/http"
)
+32 -31
View File
@@ -5,9 +5,8 @@ import (
"github.com/gin-gonic/gin/binding"
"github.com/google/uuid"
"go-admin/models"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
"go-admin/tools"
"go-admin/tools/app"
"log"
)
@@ -27,25 +26,27 @@ func GetSysUserList(c *gin.Context) {
size := c.Request.FormValue("pageSize")
if size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools.StrToInt(err, size)
}
index := c.Request.FormValue("pageIndex")
if index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools.StrToInt(err, index)
}
data.Username = c.Request.FormValue("userName")
data.Status = c.Request.FormValue("status")
data.Phone = c.Request.FormValue("phone")
postId := c.Request.FormValue("postId")
data.PostId, _ = utils.StringToInt(postId)
data.PostId, _ = tools.StringToInt(postId)
deptId := c.Request.FormValue("deptId")
data.DeptId, _ = utils.StringToInt(deptId)
data.DeptId, _ = tools.StringToInt(deptId)
data.DataScope = utils.GetUserIdStr(c)
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools.HasError(err, "", -1)
app.PageOK(c, result, count, pageIndex, pageSize, "")
}
@@ -54,14 +55,14 @@ func GetSysUserList(c *gin.Context) {
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser/{userId} [get]
// @Security
func GetSysUser(c *gin.Context) {
var SysUser models.SysUser
SysUser.UserId, _ = utils.StringToInt(c.Param("userId"))
SysUser.UserId, _ = tools.StringToInt(c.Param("userId"))
result, err := SysUser.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var SysRole models.SysRole
var Post models.Post
roles, err := SysRole.GetList()
@@ -85,15 +86,15 @@ func GetSysUser(c *gin.Context) {
// @Summary 获取当前登录用户
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/user/profile [get]
// @Security
func GetSysUserProfile(c *gin.Context) {
var SysUser models.SysUser
userId := utils.GetUserIdStr(c)
SysUser.UserId, _ = utils.StringToInt(userId)
userId := tools.GetUserIdStr(c)
SysUser.UserId, _ = tools.StringToInt(userId)
result, err := SysUser.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
var SysRole models.SysRole
var Post models.Post
var Dept models.Dept
@@ -125,7 +126,7 @@ func GetSysUserProfile(c *gin.Context) {
// @Summary 获取用户角色和职位
// @Description 获取JSON
// @Tags 用户
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sysUser [get]
// @Security
func GetSysUserInit(c *gin.Context) {
@@ -133,7 +134,7 @@ func GetSysUserInit(c *gin.Context) {
var Post models.Post
roles, err := SysRole.GetList()
posts, err := Post.GetList()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools.HasError(err, "抱歉未找到相关信息", -1)
mp := make(map[string]interface{}, 2)
mp["roles"] = roles
mp["posts"] = posts
@@ -152,11 +153,11 @@ func GetSysUserInit(c *gin.Context) {
func InsertSysUser(c *gin.Context) {
var sysuser models.SysUser
err := c.BindWith(&sysuser, binding.JSON)
pkg.HasError(err, "非法数据格式", 500)
tools.HasError(err, "非法数据格式", 500)
sysuser.CreateBy = utils.GetUserIdStr(c)
sysuser.CreateBy = tools.GetUserIdStr(c)
id, err := sysuser.Insert()
pkg.HasError(err, "添加失败", 500)
tools.HasError(err, "添加失败", 500)
app.OK(c, id, "添加成功")
}
@@ -172,10 +173,10 @@ func InsertSysUser(c *gin.Context) {
func UpdateSysUser(c *gin.Context) {
var data models.SysUser
err := c.BindWith(&data, binding.JSON)
pkg.HasError(err, "数据解析失败", -1)
data.UpdateBy = utils.GetUserIdStr(c)
tools.HasError(err, "数据解析失败", -1)
data.UpdateBy = tools.GetUserIdStr(c)
result, err := data.Update(data.UserId)
pkg.HasError(err, "修改失败", 500)
tools.HasError(err, "修改失败", 500)
app.OK(c, result, "修改成功")
}
@@ -188,10 +189,10 @@ func UpdateSysUser(c *gin.Context) {
// @Router /api/v1/sysuser/{userId} [delete]
func DeleteSysUser(c *gin.Context) {
var data models.SysUser
data.UpdateBy = utils.GetUserIdStr(c)
IDS := utils.IdsStrToIdsIntGroup("userId", c)
data.UpdateBy = tools.GetUserIdStr(c)
IDS := tools.IdsStrToIdsIntGroup("userId", c)
result, err := data.BatchDelete(IDS)
pkg.HasError(err, "删除失败", 500)
tools.HasError(err, "删除失败", 500)
app.OK(c, result, "删除成功")
}
@@ -214,9 +215,9 @@ func InsetSysUserAvatar(c *gin.Context) {
_ = c.SaveUploadedFile(file, filPath)
}
sysuser := models.SysUser{}
sysuser.UserId = utils.GetUserId(c)
sysuser.UserId = tools.GetUserId(c)
sysuser.Avatar = "/" + filPath
sysuser.UpdateBy = utils.GetUserIdStr(c)
sysuser.UpdateBy = tools.GetUserIdStr(c)
sysuser.Update(sysuser.UserId)
app.OK(c, filPath, "修改成功")
}
@@ -224,9 +225,9 @@ func InsetSysUserAvatar(c *gin.Context) {
func SysUserUpdatePwd(c *gin.Context) {
var pwd models.SysUserPwd
err := c.Bind(&pwd)
pkg.HasError(err, "数据解析失败", 500)
tools.HasError(err, "数据解析失败", 500)
sysuser := models.SysUser{}
sysuser.UserId = utils.GetUserId(c)
sysuser.UserId = tools.GetUserId(c)
sysuser.SetPwd(pwd)
app.OK(c, "", "密码修改成功")
}
+7 -7
View File
@@ -3,8 +3,8 @@ package tools
import (
"github.com/gin-gonic/gin"
"go-admin/models/tools"
"go-admin/pkg"
"go-admin/pkg/app"
tools2 "go-admin/tools"
"go-admin/tools/app"
"net/http"
)
@@ -14,7 +14,7 @@ import (
// @Param tableName query string false "tableName / 数据表名称"
// @Param pageSize query int false "pageSize / 页条数"
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/db/columns/page [get]
func GetDBColumnList(c *gin.Context) {
var data tools.DBColumns
@@ -23,17 +23,17 @@ func GetDBColumnList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools2.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools2.StrToInt(err, index)
}
data.TableName = c.Request.FormValue("tableName")
pkg.Assert(data.TableName=="","table name cannot be empty!",500)
tools2.Assert(data.TableName=="","table name cannot be empty!",500)
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
+8 -8
View File
@@ -2,10 +2,10 @@ package tools
import (
"github.com/gin-gonic/gin"
"go-admin/config"
"go-admin/models/tools"
"go-admin/pkg"
"go-admin/pkg/app"
tools2 "go-admin/tools"
"go-admin/tools/app"
config2 "go-admin/tools/config"
"net/http"
)
@@ -15,7 +15,7 @@ import (
// @Param tableName query string false "tableName / 数据表名称"
// @Param pageSize query int false "pageSize / 页条数"
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/db/tables/page [get]
func GetDBTableList(c *gin.Context) {
var res app.Response
@@ -23,23 +23,23 @@ func GetDBTableList(c *gin.Context) {
var err error
var pageSize = 10
var pageIndex = 1
if config.DatabaseConfig.Dbtype=="sqlite3"{
if config2.DatabaseConfig.Dbtype=="sqlite3"{
res.Msg="对不起,sqlite3 暂不支持代码生成!"
c.JSON(http.StatusOK, res.ReturnError(500))
return
}
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools2.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools2.StrToInt(err, index)
}
data.TableName = c.Request.FormValue("tableName")
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
+16 -7
View File
@@ -4,31 +4,40 @@ import (
"bytes"
"github.com/gin-gonic/gin"
"go-admin/models/tools"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
tools2 "go-admin/tools"
"go-admin/tools/app"
"net/http"
"text/template"
)
func Preview(c *gin.Context) {
table := tools.SysTables{}
id, err := utils.StringToInt(c.Param("tableId"))
pkg.HasError(err, "", -1)
id, err := tools2.StringToInt(c.Param("tableId"))
tools2.HasError(err, "", -1)
table.TableId = id
t1, err := template.ParseFiles("template/model.go.template")
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
t2, err := template.ParseFiles("template/api.go.template")
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
t3, err := template.ParseFiles("template/js.go.template")
tools2.HasError(err, "", -1)
t4, err := template.ParseFiles("template/vue.go.template")
tools2.HasError(err, "", -1)
tab, _ := table.Get()
var b1 bytes.Buffer
err = t1.Execute(&b1, tab)
var b2 bytes.Buffer
err = t2.Execute(&b2, tab)
var b3 bytes.Buffer
err = t3.Execute(&b3, tab)
var b4 bytes.Buffer
err = t4.Execute(&b4, tab)
mp := make(map[string]interface{})
mp["template/model.go.template"] = b1.String()
mp["template/api.go.template"] = b2.String()
mp["template/js.go.template"] = b3.String()
mp["template/vue.go.template"] = b4.String()
var res app.Response
res.Data = mp
+23 -24
View File
@@ -3,9 +3,8 @@ package tools
import (
"github.com/gin-gonic/gin"
"go-admin/models/tools"
"go-admin/pkg"
"go-admin/pkg/app"
"go-admin/pkg/utils"
tools2 "go-admin/tools"
"go-admin/tools/app"
"net/http"
"strings"
)
@@ -16,7 +15,7 @@ import (
// @Param tableName query string false "tableName / 数据表名称"
// @Param pageSize query int false "pageSize / 页条数"
// @Param pageIndex query int false "pageIndex / 页码"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys/tables/page [get]
func GetSysTableList(c *gin.Context) {
var data tools.SysTables
@@ -25,16 +24,17 @@ func GetSysTableList(c *gin.Context) {
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize = pkg.StrToInt(err, size)
pageSize = tools2.StrToInt(err, size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex = pkg.StrToInt(err, index)
pageIndex = tools2.StrToInt(err, index)
}
data.TableName = c.Request.FormValue("tableName")
data.TBName = c.Request.FormValue("tableName")
data.TableComment = c.Request.FormValue("tableComment")
result, count, err := data.GetPage(pageSize, pageIndex)
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
@@ -52,14 +52,14 @@ func GetSysTableList(c *gin.Context) {
// @Description 获取JSON
// @Tags 工具 - 生成表
// @Param configKey path int true "configKey"
// @Success 200 {object} models.Response "{"code": 200, "data": [...]}"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys/tables/info/{tableId} [get]
// @Security
func GetSysTables(c *gin.Context) {
var data tools.SysTables
data.TableId, _ = utils.StringToInt(c.Param("tableId"))
data.TableId, _ = tools2.StringToInt(c.Param("tableId"))
result, err := data.Get()
pkg.HasError(err, "抱歉未找到相关信息", -1)
tools2.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
@@ -84,13 +84,13 @@ func InsertSysTable(c *gin.Context) {
var data tools.SysTables
var dbTable tools.DBTables
var dbColumn tools.DBColumns
data.TableName = c.Request.FormValue("tables")
data.CreateBy = utils.GetUserIdStr(c)
data.TBName = c.Request.FormValue("tables")
data.CreateBy = tools2.GetUserIdStr(c)
dbTable.TableName = data.TableName
dbTable.TableName = data.TBName
dbtable, err := dbTable.Get()
dbColumn.TableName = data.TableName
dbColumn.TableName = data.TBName
tablenamelist := strings.Split(dbColumn.TableName, "_")
for i := 0; i < len(tablenamelist); i++ {
strStart := string([]byte(tablenamelist[i])[:1])
@@ -103,7 +103,7 @@ func InsertSysTable(c *gin.Context) {
data.Crud = true
dbcolumn, err := dbColumn.GetList()
data.CreateBy = utils.GetUserIdStr(c)
data.CreateBy = tools2.GetUserIdStr(c)
data.TableComment = dbtable.TableComment
if dbtable.TableComment == "" {
data.TableComment = data.ClassName
@@ -163,7 +163,7 @@ func InsertSysTable(c *gin.Context) {
}
result, err := data.Create()
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
var res app.Response
res.Data = result
@@ -185,10 +185,10 @@ func InsertSysTable(c *gin.Context) {
func UpdateSysTable(c *gin.Context) {
var data tools.SysTables
err := c.Bind(&data)
pkg.HasError(err, "数据解析失败", -1)
data.UpdateBy = utils.GetUserIdStr(c)
tools2.HasError(err, "数据解析失败", -1)
data.UpdateBy = tools2.GetUserIdStr(c)
result, err := data.Update()
pkg.HasError(err, "", -1)
tools2.HasError(err, "", -1)
var res app.Response
res.Data = result
@@ -205,10 +205,9 @@ func UpdateSysTable(c *gin.Context) {
// @Router /api/v1/sys/tables/info/{tableId} [delete]
func DeleteSysTables(c *gin.Context) {
var data tools.SysTables
id, err := utils.StringToInt(c.Param("tableId"))
data.TableId = id
_, err = data.Delete()
pkg.HasError(err, "删除失败", 500)
IDS := tools2.IdsStrToIdsIntGroup("tableId", c)
_, err := data.BatchDelete(IDS)
tools2.HasError(err, "删除失败", 500)
var res app.Response
res.Msg = "删除成功"
c.JSON(http.StatusOK, res.ReturnOK())
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go-admin/database"
"go-admin/router"
"go-admin/tools"
config2 "go-admin/tools/config"
"log"
"net/http"
"os"
"os/signal"
"time"
)
var (
config string
port string
mode string
StartCmd = &cobra.Command{
Use: "server",
Short: "Start API server",
Example: "go-admin server config/settings.yml",
PreRun: func(cmd *cobra.Command, args []string) {
usage()
setup()
},
RunE: func(cmd *cobra.Command, args []string) error {
return run()
},
}
)
func init() {
StartCmd.PersistentFlags().StringVarP(&config, "config", "c", "config/settings.yml", "Start server with provided configuration file")
StartCmd.PersistentFlags().StringVarP(&port, "port", "p", "8000", "Tcp port server listening on")
StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
}
func usage() {
usageStr := `starting api server`
fmt.Printf("%s\n", usageStr)
}
func setup() {
//1. 读取配置
config2.ConfigSetup(config)
//2. 设置日志
tools.InitLogger()
//3. 初始化数据库链接
database.Setup()
//4. 设置gin mode
if viper.GetString("settings.application.mode") == string(tools.ModeProd) {
gin.SetMode(gin.ReleaseMode)
}
}
func run() error {
r := router.InitRouter()
defer database.Eloquent.Close()
srv := &http.Server{
Addr: config2.ApplicationConfig.Host + ":" + config2.ApplicationConfig.Port,
Handler: r,
}
go func() {
// 服务连接
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
log.Println("Server Run ", config2.ApplicationConfig.Host+":"+config2.ApplicationConfig.Port)
log.Println("Enter Control + C Shutdown Server")
// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
return nil
}
+41
View File
@@ -0,0 +1,41 @@
package cmd
import (
"errors"
"github.com/spf13/cobra"
"go-admin/cmd/api"
"go-admin/cmd/migrate"
"log"
"os"
)
var rootCmd = &cobra.Command{
Use: "go-admin",
Short: "-v",
SilenceUsage: true,
DisableAutoGenTag: true,
Long: `go-admin`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires at least one arg")
}
return nil
},
PersistentPreRunE: func(*cobra.Command, []string) error { return nil },
Run: func(cmd *cobra.Command, args []string) {
usageStr := `go-admin 1.0.0 欢迎使用,可以是用 -h 查看命令`
log.Printf("%s\n", usageStr)
},
}
func init() {
rootCmd.AddCommand(api.StartCmd)
rootCmd.AddCommand(migrate.StartCmd)
}
//Execute : apply commands
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(-1)
}
}
+77
View File
@@ -0,0 +1,77 @@
package migrate
import (
"fmt"
"go-admin/database"
orm "go-admin/database"
"go-admin/models"
"go-admin/models/gorm"
tools2 "go-admin/models/tools"
"go-admin/tools"
config2 "go-admin/tools/config"
"log"
"github.com/spf13/cobra"
)
var (
config string
mode string
StartCmd = &cobra.Command{
Use: "migrate",
Short: "migrate from struct to database",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}
)
func init() {
StartCmd.PersistentFlags().StringVarP(&config, "config", "c", "config/settings.yml", "Start server with provided configuration file")
StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
}
func run() {
usage := `start migrate`
fmt.Println(usage)
//1. 读取配置
config2.ConfigSetup(config)
//2. 设置日志
tools.InitLogger()
//3. 初始化数据库链接
database.Setup()
//4. 数据库迁移
_ = gorm.AutoMigrate(orm.Eloquent)
log.Println("数据库结构初始化成功!")
//5. 数据初始化完成
if err := models.InitDb(); err != nil {
log.Fatal("数据库基础数据初始化失败!")
}
usage = `数据库基础数据初始化成功`
fmt.Println(usage)
}
func migrateModel() error {
if config2.DatabaseConfig.Dbtype == "mysql" {
orm.Eloquent = orm.Eloquent.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
}
orm.Eloquent.SingularTable(true)
return orm.Eloquent.AutoMigrate(
new(models.CasbinRule),
new(tools2.SysTables),
new(tools2.SysColumns),
new(models.Dept),
new(models.Menu),
new(models.LoginLog),
new(models.SysOperLog),
new(models.RoleMenu),
new(models.SysRoleDept),
new(models.SysUser),
new(models.SysRole),
new(models.Post),
new(models.DictData),
new(models.SysConfig),
new(models.DictType),
).Error
}
-12
View File
@@ -337,9 +337,6 @@ INSERT INTO `sys_menu` VALUES (46, NULL, '删除用户', NULL, '/api/v1/sysuser/
INSERT INTO `sys_menu` VALUES (50, 'Mangent', '基础信息', 'network', '/mangent', '/0/50', 'M', '无', '', 0, '1', '', 'Layout', 2, '0', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (51, 'Menu', '菜单管理', 'tree-table', 'menu', '/0/2/51', 'C', '无', 'system:sysmenu:list', 2, '1', '', '/menu/index', 3, '0', '1', '1', 0, '2020-04-11 15:52:48', '2020-04-12 11:16:30', NULL);
INSERT INTO `sys_menu` VALUES (52, 'Role', '角色管理', 'peoples', 'role', '/0/2/52', 'C', '无', 'system:sysrole:list', 2, '1', '', '/role/index', 2, '0', '1', '1', 0, '2020-04-11 15:52:48', '2020-04-12 11:16:19', NULL);
INSERT INTO `sys_menu` VALUES (53, 'Doctor', '医生管理', 'pass', 'doctor', '/0/50/53', 'C', '无', '', 50, '1', '', '/doctor/index', 0, '0', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (54, 'Calendar', '排班管理', 'calendar', 'calendar', '/0/50/54', 'C', '无', '', 50, '1', '', '/calendar/index', 0, '0', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (55, 'Menber', '会员管理', 'vip', 'member', '/0/50/55', 'C', '无', '', 50, '1', '', '/member/index', 0, '0', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (56, 'Dept', '部门管理', 'tree', 'dept', '/0/2/56', 'C', '无', 'system:sysdept:list', 2, '0', '', '/dept/index', 4, '0', '1', '1', 0, '2020-04-11 15:52:48', '2020-04-12 11:16:47', NULL);
INSERT INTO `sys_menu` VALUES (57, 'post', '岗位管理', 'pass', 'post', '/0/2/57', 'C', '无', 'system:syspost:list', 2, '0', '', '/post/index', 5, '0', '1', '1', 0, '2020-04-11 15:52:48', '2020-04-12 11:16:53', NULL);
INSERT INTO `sys_menu` VALUES (58, 'Dict', '字典管理', 'education', 'dict', '/0/2/58', 'C', '无', 'system:sysdicttype:list', 2, '0', '', '/dict/index', 6, '0', '1', '1', 0, '2020-04-11 15:52:48', '2020-04-12 11:17:04', NULL);
@@ -382,11 +379,6 @@ INSERT INTO `sys_menu` VALUES (94, NULL, '获取菜单树', 'bug', '/api/v1/menu
INSERT INTO `sys_menu` VALUES (95, NULL, '获取角色菜单', 'bug', '/api/v1/rolemenu', '/0/63/205/95', 'A', 'GET', NULL, 205, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (96, NULL, '创建角色菜单', 'bug', '/api/v1/rolemenu', '/0/63/205/96', 'A', 'POST', NULL, 205, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (97, NULL, '删除用户菜单数据', 'bug', '/api/v1/rolemenu/:id', '/0/63/205/97', 'A', 'DELETE', NULL, 205, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (98, NULL, '医生获取', 'bug', '/api/v1/doctor', '/0/63/208/98', 'A', 'GET', NULL, 208, NULL, NULL, NULL, 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (99, NULL, '创建医生', 'bug', '/api/v1/doctor', '/0/63/208/99', 'A', 'POST', NULL, 208, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (100, NULL, '修改医生', 'bug', '/api/v1/doctor/:id', '/0/63/208/100', 'A', 'PUT', NULL, 208, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (101, NULL, '删除医生', 'bug', '/api/v1/doctor/:id', '/0/63/208/101', 'A', 'DELETE', NULL, 208, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (102, NULL, '添加医生头像', 'bug', '/api/v1/doctor/pic/', '/0/63/208/102', 'A', 'POST', NULL, 208, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (103, NULL, '部门菜单列表', 'bug', '/api/v1/deptList', '/0/63/203/103', 'A', 'GET', NULL, 203, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (104, NULL, '根据id获取部门信息', 'bug', '/api/v1/dept/:id', '/0/63/203/104', 'A', 'GET', NULL, 203, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (105, NULL, '创建部门', 'bug', '/api/v1/dept', '/0/63/203/105', 'A', 'POST', NULL, 203, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
@@ -433,10 +425,6 @@ INSERT INTO `sys_menu` VALUES (203, '', '部门管理', 'tree', '', '/0/63/203',
INSERT INTO `sys_menu` VALUES (204, '', '岗位管理', 'pass', '', '/0/63/204', 'C', '', '', 63, '0', '', '', 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (205, '', '角色菜单管理', 'nested', '', '/0/63/205', 'C', '', '', 63, '0', '', '', 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (206, '', '数据', '', '', '/0/63/69/206', 'C', 'PUT', '', 69, '0', '', '', 2, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (207, '', '会员管理', 'vip', '', '/0/63/207', 'C', 'DELETE', '', 63, '0', '', '', 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (208, '', '医生管理', 'theme', '', '/0/63/208', 'C', '', '', 63, '0', '', '', 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (209, '', '订单管理', 'tab', '', '/0/63/209', 'M', '', '', 63, '0', '', '', 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (210, '', '排班管理', 'calendar', '', '/0/63/210', 'C', 'DELETE', '', 63, '0', '', '', 1, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (211, 'Log', '日志管理', 'log', '/log', '/0/2/211', 'M', '', '', 2, '0', '', '/log/index', 8, '0', '1', '1', 0, '2020-04-11 15:52:48', '2020-04-12 11:15:32', NULL);
INSERT INTO `sys_menu` VALUES (212, 'LoginLog', '登录日志', 'logininfor', '/loginlog', '/0/2/211/212', 'C', '', 'system:sysloginlog:list', 211, '0', '', '/loginlog/index', 1, '0', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
INSERT INTO `sys_menu` VALUES (213, NULL, '获取登录日志', 'bug', '/api/v1/loginloglist', '/0/63/214/213', 'A', 'GET', NULL, 214, NULL, NULL, NULL, 0, '1', '1', '1', 0, '2020-04-11 15:52:48', NULL, NULL);
-75
View File
@@ -1,75 +0,0 @@
p, admin, /api/v1/menulist, GET
p, admin, /api/v1/menu, POST
p, admin, /api/v1/dict/databytype/, GET
p, admin, /api/v1/menu/, PUT
p, admin, /api/v1/menu/, DELETE
p, admin, /api/v1/sysUserList, GET
p, admin, /api/v1/sysUser/:id, GET
p, admin, /api/v1/sysUser/, GET
p, admin, /api/v1/sysUser, POST
p, admin, /api/v1/sysUser, PUT
p, admin, /api/v1/sysUser/:id, DELETE
p, admin, /api/v1/user/profile, GET
p, admin, /api/v1/rolelist, GET
p, admin, /api/v1/role/:id, GET
p, admin, /api/v1/role, POST
p, admin, /api/v1/role, PUT
p, admin, /api/v1/role/:id, DELETE
p, admin, /api/v1/configList, GET
p, admin, /api/v1/config/:id, GET
p, admin, /api/v1/configKey/:id, GET
p, admin, /api/v1/config, POST
p, admin, /api/v1/config/, PUT
p, admin, /api/v1/config/:id, DELETE
p, admin, /api/v1/menurole, GET
p, admin, /api/v1/roleMenuTreeselect/:id, GET
p, admin, /api/v1/menuTreeselect, GET
p, admin, /api/v1/rolemenu, GET
p, admin, /api/v1/rolemenu, POST
p, admin, /api/v1/rolemenu/:id, DELETE
p, admin, /api/v1/doctor, GET
p, admin, /api/v1/doctor, POST
p, admin, /api/v1/doctor/:id, PUT
p, admin, /api/v1/doctor/:id, DELETE
p, admin, /api/v1/doctor/pic/, POST
p, admin, /api/v1/deptList, GET
p, admin, /api/v1/dept/:id, GET
p, admin, /api/v1/dept, POST
p, admin, /api/v1/dept, PUT
p, admin, /api/v1/dept/:id, DELETE
p, admin, /api/v1/dict/datalist, GET
p, admin, /api/v1/dict/data/:id, GET
p, admin, /api/v1/dict/databytype/:id, GET
p, admin, /api/v1/dict/data, POST
p, admin, /api/v1/dict/data/, PUT
p, admin, /api/v1/dict/data/:id, DELETE
p, admin, /api/v1/dict/typelist, GET
p, admin, /api/v1/dict/type/:id, GET
p, admin, /api/v1/dict/type, POST
p, admin, /api/v1/dict/type, PUT
p, admin, /api/v1/dict/type/:id, DELETE
p, admin, /api/v1/postlist, GET
p, admin, /api/v1/post/:id, GET
p, admin, /api/v1/post, POST
p, admin, /api/v1/post, PUT
p, admin, /api/v1/post/:id, DELETE
p, admin, /api/v1/calendar, GET
p, admin, /api/v1/calendar, POST
p, admin, /api/v1/calendar/:id, PUT
p, admin, /api/v1/calendar/:id, DELETE
p, admin, /api/v1/member, GET
p, admin, /api/v1/member, POST
p, admin, /api/v1/member/:id, PUT
p, admin, /api/v1/member/:id, DELETE
p, admin, /api/v1/orders, GET
p, admin, /api/v1/orders/:id, GET
p, admin, /api/v1/orders, POST
p, admin, /api/v1/orders/:id, PUT
p, admin, /api/v1/orders/:id, DELETE
p, admin, /api/v1/menu/:id, GET
p, admin, /api/v1/menu/:id, PUT
p, admin, /api/v1/menuids, GET
p, admin, /api/v1/loginloglist, GET
p, admin, /api/v1/loginlog/:id, DELETE
p, admin, /api/v1/operloglist, GET
p, admin, /api/v1/getinfo, GET
1 p admin /api/v1/menulist GET
2 p admin /api/v1/menu POST
3 p admin /api/v1/dict/databytype/ GET
4 p admin /api/v1/menu/ PUT
5 p admin /api/v1/menu/ DELETE
6 p admin /api/v1/sysUserList GET
7 p admin /api/v1/sysUser/:id GET
8 p admin /api/v1/sysUser/ GET
9 p admin /api/v1/sysUser POST
10 p admin /api/v1/sysUser PUT
11 p admin /api/v1/sysUser/:id DELETE
12 p admin /api/v1/user/profile GET
13 p admin /api/v1/rolelist GET
14 p admin /api/v1/role/:id GET
15 p admin /api/v1/role POST
16 p admin /api/v1/role PUT
17 p admin /api/v1/role/:id DELETE
18 p admin /api/v1/configList GET
19 p admin /api/v1/config/:id GET
20 p admin /api/v1/configKey/:id GET
21 p admin /api/v1/config POST
22 p admin /api/v1/config/ PUT
23 p admin /api/v1/config/:id DELETE
24 p admin /api/v1/menurole GET
25 p admin /api/v1/roleMenuTreeselect/:id GET
26 p admin /api/v1/menuTreeselect GET
27 p admin /api/v1/rolemenu GET
28 p admin /api/v1/rolemenu POST
29 p admin /api/v1/rolemenu/:id DELETE
30 p admin /api/v1/doctor GET
31 p admin /api/v1/doctor POST
32 p admin /api/v1/doctor/:id PUT
33 p admin /api/v1/doctor/:id DELETE
34 p admin /api/v1/doctor/pic/ POST
35 p admin /api/v1/deptList GET
36 p admin /api/v1/dept/:id GET
37 p admin /api/v1/dept POST
38 p admin /api/v1/dept PUT
39 p admin /api/v1/dept/:id DELETE
40 p admin /api/v1/dict/datalist GET
41 p admin /api/v1/dict/data/:id GET
42 p admin /api/v1/dict/databytype/:id GET
43 p admin /api/v1/dict/data POST
44 p admin /api/v1/dict/data/ PUT
45 p admin /api/v1/dict/data/:id DELETE
46 p admin /api/v1/dict/typelist GET
47 p admin /api/v1/dict/type/:id GET
48 p admin /api/v1/dict/type POST
49 p admin /api/v1/dict/type PUT
50 p admin /api/v1/dict/type/:id DELETE
51 p admin /api/v1/postlist GET
52 p admin /api/v1/post/:id GET
53 p admin /api/v1/post POST
54 p admin /api/v1/post PUT
55 p admin /api/v1/post/:id DELETE
56 p admin /api/v1/calendar GET
57 p admin /api/v1/calendar POST
58 p admin /api/v1/calendar/:id PUT
59 p admin /api/v1/calendar/:id DELETE
60 p admin /api/v1/member GET
61 p admin /api/v1/member POST
62 p admin /api/v1/member/:id PUT
63 p admin /api/v1/member/:id DELETE
64 p admin /api/v1/orders GET
65 p admin /api/v1/orders/:id GET
66 p admin /api/v1/orders POST
67 p admin /api/v1/orders/:id PUT
68 p admin /api/v1/orders/:id DELETE
69 p admin /api/v1/menu/:id GET
70 p admin /api/v1/menu/:id PUT
71 p admin /api/v1/menuids GET
72 p admin /api/v1/loginloglist GET
73 p admin /api/v1/loginlog/:id DELETE
74 p admin /api/v1/operloglist GET
75 p admin /api/v1/getinfo GET
+7 -7
View File
@@ -1,21 +1,21 @@
settings:
application:
env: dev
envmsg: "谢谢您的参与,但为了大家更好的体验,所以本次提交就算了吧!\U0001F600\U0001F600\U0001F600"
mode: dev # dev开发环境 test测试环境 prod线上环境
demomsg: "谢谢您的参与,但为了大家更好的体验,所以本次提交就算了吧!\U0001F600\U0001F600\U0001F600"
host: 0.0.0.0
isinit: false
logpath: temp/logs/log.txt
name: testApp
port: 8000
readtimeout: 1
writertimeout: 2
log:
dir: temp/logs
jwt:
secret: go-admin
timeout: 3600
database:
database: goadmin
dbtype: mysql # sqlite3
host: 127.0.0.1 # sqlite3.db
name: goadmindb
dbtype: mysql
host: 127.0.0.1
password: 123456
port: 3306
username: root
+47 -35
View File
@@ -2,71 +2,83 @@ package database
import (
"bytes"
"fmt"
_ "github.com/go-sql-driver/mysql" //加载mysql
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
config2 "go-admin/config"
"go-admin/tools/config"
"log"
"strconv"
)
var Eloquent *gorm.DB
func init() {
var (
DbType string
Host string
Port int
Name string
Username string
Password string
)
dbType := config2.DatabaseConfig.Dbtype
host := config2.DatabaseConfig.Host
port := config2.DatabaseConfig.Port
database := config2.DatabaseConfig.Database
username := config2.DatabaseConfig.Username
password := config2.DatabaseConfig.Password
func Setup() {
if dbType != "mysql" && dbType != "sqlite3" {
fmt.Println("db type unknow")
DbType = config.DatabaseConfig.Dbtype
Host = config.DatabaseConfig.Host
Port = config.DatabaseConfig.Port
Name = config.DatabaseConfig.Name
Username = config.DatabaseConfig.Username
Password = config.DatabaseConfig.Password
if DbType != "mysql" && DbType != "sqlite3" {
log.Println("db type unknow")
}
var err error
var conn bytes.Buffer
conn.WriteString(username)
conn.WriteString(":")
conn.WriteString(password)
conn.WriteString("@tcp(")
conn.WriteString(host)
conn.WriteString(":")
conn.WriteString(strconv.Itoa(port))
conn.WriteString(")")
conn.WriteString("/")
conn.WriteString(database)
conn.WriteString("?charset=utf8&parseTime=True&loc=Local&timeout=1000ms")
conn := GetMysqlConnect()
log.Println(conn.String())
log.Println(conn)
var db Database
if dbType == "mysql" {
if DbType == "mysql" {
db = new(Mysql)
Eloquent, err = db.Open(DbType, conn)
Eloquent, err = db.Open(dbType, conn.String())
} else if dbType == "sqlite3" {
} else if DbType == "sqlite3" {
db = new(SqlLite)
Eloquent, err = db.Open(dbType, host)
Eloquent, err = db.Open(DbType, Host)
} else {
panic("db type unknow")
}
Eloquent.LogMode(true)
if err != nil {
log.Fatalln("%s connect error %v",dbType, err)
log.Fatalf("%s connect error %v", DbType, err)
} else {
log.Println("%s connect success!",dbType)
log.Printf("%s connect success!", DbType)
}
if Eloquent.Error != nil {
log.Fatalln("database error %v", Eloquent.Error)
log.Fatalf("database error %v", Eloquent.Error)
}
Eloquent.LogMode(true)
}
func GetMysqlConnect() string {
var conn bytes.Buffer
conn.WriteString(Username)
conn.WriteString(":")
conn.WriteString(Password)
conn.WriteString("@tcp(")
conn.WriteString(Host)
conn.WriteString(":")
conn.WriteString(strconv.Itoa(Port))
conn.WriteString(")")
conn.WriteString("/")
conn.WriteString(Name)
conn.WriteString("?charset=utf8&parseTime=True&loc=Local&timeout=1000ms")
return conn.String()
}
type Database interface {
+7
View File
@@ -0,0 +1,7 @@
// +build sqlite3
package database
import (
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
+366 -255
View File
File diff suppressed because it is too large. Load diff
+365 -254
View File
File diff suppressed because it is too large. Load diff
+256 -195
View File
@@ -1,37 +1,15 @@
definitions:
models.Config:
app.Response:
properties:
configId:
description: 编码
code:
description: 代码
example: 200
type: integer
configKey:
description: 参数键名
type: string
configName:
description: 参数名称
type: string
configType:
description: 是否系统内置
type: string
configValue:
description: 参数键值
type: string
createBy:
type: string
createTime:
type: string
dataScope:
type: string
isDel:
type: string
params:
type: string
remark:
description: 备注
type: string
updateBy:
type: string
updateTime:
data:
description: 数据集
type: object
msg:
description: 消息
type: string
type: object
models.Dept:
@@ -42,31 +20,29 @@ definitions:
type: array
createBy:
type: string
createTime:
createdAt:
type: string
dataScope:
type: string
deletedAt:
type: string
deptId:
description: 部门编码
example: 1
type: integer
x-description: 标示
deptath:
type: string
deptname:
deptName:
description: 部门名称
type: string
deptPath:
type: string
email:
description: 邮箱
type: string
isDel:
type: string
leader:
description: 负责人
type: string
params:
type: string
parent_id:
parentId:
description: 上级部门
type: integer
phone:
@@ -80,7 +56,7 @@ definitions:
type: string
updateBy:
type: string
updateTime:
updatedAt:
type: string
type: object
models.DictType:
@@ -88,13 +64,13 @@ definitions:
createBy:
description: 创建者
type: string
createTime:
description: 创建时间
createdAt:
type: string
dataScope:
type: string
deletedAt:
type: string
dictId:
example: 1
type: integer
dictName:
description: 字典名称
@@ -102,8 +78,6 @@ definitions:
dictType:
description: 字典类型
type: string
isDel:
type: string
params:
type: string
remark:
@@ -115,8 +89,7 @@ definitions:
updateBy:
description: 更新者
type: string
updateTime:
description: 更新时间
updatedAt:
type: string
type: object
models.Login:
@@ -143,21 +116,19 @@ definitions:
createBy:
description: 创建人
type: string
createTime:
description: 创建时间
createdAt:
type: string
dataScope:
description: 数据
type: string
deletedAt:
type: string
infoId:
description: 主键
type: integer
ipaddr:
description: ip地址
type: string
isDel:
description: 是否删除
type: string
loginLocation:
description: 归属地
type: string
@@ -170,7 +141,6 @@ definitions:
description: 系统
type: string
params:
description: 参数
type: string
platform:
description: 固件
@@ -184,10 +154,9 @@ definitions:
updateBy:
description: 更新者
type: string
updateTime:
description: 更新时间
updatedAt:
type: string
userName:
username:
description: 用户名
type: string
type: object
@@ -205,15 +174,17 @@ definitions:
type: string
createBy:
type: string
createTime:
createdAt:
type: string
dataScope:
type: string
deletedAt:
type: string
icon:
type: string
is_select:
type: boolean
isDel:
isFrame:
type: string
menuId:
type: integer
@@ -241,7 +212,7 @@ definitions:
type: string
updateBy:
type: string
updateTime:
updatedAt:
type: string
visible:
type: string
@@ -250,14 +221,12 @@ definitions:
properties:
createBy:
type: string
createTime:
description: 创建时间
createdAt:
type: string
dataScope:
type: string
isDel:
description: 是否删除
type: integer
deletedAt:
type: string
params:
type: string
postCode:
@@ -265,9 +234,7 @@ definitions:
type: string
postId:
description: 岗位编号
example: 1
type: integer
x-description: 标示
postName:
description: 岗位名称
type: string
@@ -282,21 +249,42 @@ definitions:
type: string
updateBy:
type: string
updateTime:
description: 最后修改时间
updatedAt:
type: string
type: object
models.Response:
models.SysConfig:
properties:
code:
description: 代码
example: 200
configId:
description: 编码
type: integer
data:
description: 数据集
type: object
msg:
description: 错误消息
configKey:
description: 参数键名
type: string
configName:
description: 参数名称
type: string
configType:
description: 是否系统内置
type: string
configValue:
description: 参数键值
type: string
createBy:
type: string
createdAt:
type: string
dataScope:
type: string
deletedAt:
type: string
params:
type: string
remark:
description: 备注
type: string
updateBy:
type: string
updatedAt:
type: string
type: object
models.SysOperLog:
@@ -309,18 +297,16 @@ definitions:
createBy:
description: 创建人
type: string
createTime:
description: 创建时间
createdAt:
type: string
dataScope:
description: 数据
type: string
deletedAt:
type: string
deptName:
description: 部门名称
type: string
isDel:
description: 是否删除
type: string
jsonResult:
description: 返回数据
type: string
@@ -372,11 +358,10 @@ definitions:
updateBy:
description: 更新者
type: string
updateTime:
description: 更新时间
updatedAt:
type: string
userAgent:
description: us
description: ua
type: string
type: object
models.SysRole:
@@ -385,18 +370,18 @@ definitions:
type: boolean
createBy:
type: string
createTime:
createdAt:
type: string
dataScope:
type: string
deletedAt:
type: string
deptIds:
items:
type: integer
type: array
flag:
type: string
isDel:
type: string
menuIds:
items:
type: integer
@@ -422,7 +407,7 @@ definitions:
type: string
updateBy:
type: string
updateTime:
updatedAt:
type: string
type: object
models.SysUser:
@@ -432,19 +417,18 @@ definitions:
type: string
createBy:
type: string
createTime:
description: 创建时间
createdAt:
type: string
dataScope:
type: string
deletedAt:
type: string
deptId:
description: 部门编码
type: integer
email:
description: 邮箱
type: string
isDel:
type: string
nickName:
description: 昵称
type: string
@@ -475,8 +459,7 @@ definitions:
type: string
updateBy:
type: string
updateTime:
description: 修改时间
updatedAt:
type: string
userId:
description: 编码
@@ -506,7 +489,7 @@ paths:
name: data
required: true
schema:
$ref: '#/definitions/models.Config'
$ref: '#/definitions/models.SysConfig'
type: object
responses:
"200":
@@ -547,7 +530,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取配置
@@ -566,7 +549,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取配置
@@ -600,12 +583,60 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 配置列表数据
tags:
- 配置
/api/v1/db/columns/page:
get:
description: 数据库表列分页列表 / database table column page list
parameters:
- description: tableName / 数据表名称
in: query
name: tableName
type: string
- description: pageSize / 页条数
in: query
name: pageSize
type: integer
- description: pageIndex / 页码
in: query
name: pageIndex
type: integer
responses:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/app.Response'
summary: 分页列表数据 / page list data
tags:
- 工具 / Tools
/api/v1/db/tables/page:
get:
description: 数据库表分页列表 / database table page list
parameters:
- description: tableName / 数据表名称
in: query
name: tableName
type: string
- description: pageSize / 页条数
in: query
name: pageSize
type: integer
- description: pageIndex / 页码
in: query
name: pageIndex
type: integer
responses:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/app.Response'
summary: 分页列表数据 / page list data
tags:
- 工具 / Tools
/api/v1/dept:
post:
consumes:
@@ -672,7 +703,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 部门列表数据
@@ -715,7 +746,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 分页部门列表数据
@@ -732,7 +763,7 @@ paths:
name: data
required: true
schema:
$ref: '#/definitions/models.Config'
$ref: '#/definitions/models.DictType'
type: object
responses:
"200":
@@ -741,9 +772,9 @@ paths:
type: string
security:
- Bearer: []
summary: 添加配置
summary: 添加字典数据
tags:
- 配置
- 字典数据
put:
consumes:
- application/json
@@ -795,7 +826,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 通过编码获取字典数据
@@ -829,7 +860,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 字典数据列表
@@ -848,7 +879,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 通过字典类型获取字典数据
@@ -928,7 +959,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 通过字典id获取字典类型
@@ -962,7 +993,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 字典类型列表数据
@@ -1042,7 +1073,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 通过编码获取登录日志
@@ -1076,7 +1107,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 登录日志列表
@@ -1295,7 +1326,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 通过编码获取登录日志
@@ -1346,7 +1377,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 登录日志列表
@@ -1372,7 +1403,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 职位列表数据
@@ -1452,7 +1483,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取字典数据
@@ -1486,7 +1517,7 @@ paths:
name: data
required: true
schema:
$ref: '#/definitions/models.Config'
$ref: '#/definitions/models.SysRole'
type: object
responses:
"200":
@@ -1561,7 +1592,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 角色列表数据
@@ -1585,29 +1616,6 @@ paths:
summary: RoleMenu列表数据
tags:
- 角色菜单
post:
consumes:
- application/x-www-form-urlencoded
description: 获取JSON
parameters:
- description: role_id
in: formData
name: role_id
required: true
type: string
- description: menu_id
in: formData
name: menu_id
required: true
type: string
responses:
"200":
description: '{"code": -1, "message": "添加失败"}'
schema:
type: string
summary: 创建角色菜单
tags:
- 角色菜单
/api/v1/rolemenu/{id}:
delete:
description: 删除数据
@@ -1629,6 +1637,107 @@ paths:
summary: 删除用户菜单数据
tags:
- 角色菜单
/api/v1/sys/tables/info:
post:
consumes:
- application/json
description: 添加表结构
parameters:
- description: tableName / 数据表名称
in: query
name: tables
type: string
responses:
"200":
description: '{"code": -1, "message": "添加失败"}'
schema:
type: string
security:
- Bearer: []
summary: 添加表结构
tags:
- 工具 - 生成表
put:
consumes:
- application/json
description: 修改表结构
parameters:
- description: body
in: body
name: data
required: true
schema:
$ref: '#/definitions/models.Dept'
type: object
responses:
"200":
description: '{"code": -1, "message": "添加失败"}'
schema:
type: string
security:
- Bearer: []
summary: 修改表结构
tags:
- 工具 - 生成表
/api/v1/sys/tables/info/{tableId}:
delete:
description: 删除表结构
parameters:
- description: tableId
in: path
name: tableId
required: true
type: integer
responses:
"200":
description: '{"code": -1, "message": "删除失败"}'
schema:
type: string
summary: 删除表结构
tags:
- 工具 - 生成表
get:
description: 获取JSON
parameters:
- description: configKey
in: path
name: configKey
required: true
type: integer
responses:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取配置
tags:
- 工具 - 生成表
/api/v1/sys/tables/page:
get:
description: 生成表分页列表
parameters:
- description: tableName / 数据表名称
in: query
name: tableName
type: string
- description: pageSize / 页条数
in: query
name: pageSize
type: integer
- description: pageIndex / 页码
in: query
name: pageIndex
type: integer
responses:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/app.Response'
summary: 分页列表数据
tags:
- 工具 - 生成表
/api/v1/sysUser:
get:
description: 获取JSON
@@ -1636,7 +1745,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取用户角色和职位
@@ -1675,7 +1784,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取用户
@@ -1736,30 +1845,6 @@ paths:
summary: 修改用户数据
tags:
- 用户
/api/v1/tables/page:
get:
description: 数据库表分页列表 / database table page list
parameters:
- description: tableName / 数据表名称
in: query
name: tableName
type: string
- description: pageSize / 页条数
in: query
name: pageSize
type: integer
- description: pageIndex / 页码
in: query
name: pageIndex
type: integer
responses:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
summary: 分页列表数据 / page list data
tags:
- 工具 / Tools
/api/v1/user/profile:
get:
description: 获取JSON
@@ -1767,7 +1852,7 @@ paths:
"200":
description: '{"code": 200, "data": [...]}'
schema:
$ref: '#/definitions/models.Response'
$ref: '#/definitions/app.Response'
security:
- "": []
summary: 获取当前登录用户
@@ -1835,15 +1920,7 @@ paths:
- text/html
responses:
"200":
description: 'OK - Load average: 2.39, 2.13, 1.97 | Cores: 2'
schema:
type: string
"429":
description: WARNING
schema:
type: string
"500":
description: CRITICAL
description: OK
schema:
type: string
summary: CPU 使用量
@@ -1890,15 +1967,7 @@ paths:
- text/html
responses:
"200":
description: 'OK - Free space: 455MB (0GB) / 8192MB (8GB) | Used: 5%'
schema:
type: string
"429":
description: WARNING
schema:
type: string
"500":
description: CRITICAL
description: OK
schema:
type: string
summary: OS
@@ -1911,15 +1980,7 @@ paths:
- text/html
responses:
"200":
description: 'OK - Free space: 455MB (0GB) / 8192MB (8GB) | Used: 5%'
schema:
type: string
"429":
description: WARNING
schema:
type: string
"500":
description: CRITICAL
description: OK
schema:
type: string
summary: 内存使用量
+3 -1
View File
@@ -13,7 +13,6 @@ require (
github.com/go-ole/go-ole v1.2.4 // indirect
github.com/go-openapi/spec v0.19.7 // indirect
github.com/go-openapi/swag v0.19.8 // indirect
github.com/go-redis/redis v6.15.7+incompatible
github.com/go-sql-driver/mysql v1.4.1
github.com/golang/protobuf v1.3.2 // indirect
github.com/google/uuid v1.1.1
@@ -21,12 +20,15 @@ require (
github.com/json-iterator/go v1.1.8 // indirect
github.com/mailru/easyjson v0.7.1 // indirect
github.com/mattn/go-isatty v0.0.10 // indirect
github.com/mitchellh/go-homedir v1.1.0
github.com/mojocn/base64Captcha v1.3.1
github.com/mssola/user_agent v0.5.1
github.com/robfig/cron/v3 v3.0.0
github.com/satori/go.uuid v1.2.0
github.com/shirou/gopsutil v2.20.3+incompatible
github.com/sirupsen/logrus v1.2.0
github.com/spf13/cobra v1.0.0
github.com/spf13/pflag v1.0.3
github.com/spf13/viper v1.6.2
github.com/swaggo/gin-swagger v1.2.0
github.com/swaggo/swag v1.6.5
+9 -2
View File
@@ -41,6 +41,7 @@ github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3Ee
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -101,8 +102,6 @@ github.com/go-openapi/swag v0.19.5 h1:lTz6Ys4CmqqCQmZPBlbQENR1/GucA2bzYTE12Pw4tF
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.8 h1:vfK6jLhs7OI4tAXkvkooviaE1JEPcw3mutyegLHHjmk=
github.com/go-openapi/swag v0.19.8/go.mod h1:ao+8BpOPyKdpQz3AOJfbeEVpLmWAvlT1IfTe5McPyhY=
github.com/go-redis/redis v6.15.7+incompatible h1:3skhDh95XQMpnqeqNftPkQD9jL9e5e36z/1SUm6dy1U=
github.com/go-redis/redis v6.15.7+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
@@ -145,6 +144,8 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jinzhu/gorm v1.9.10 h1:HvrsqdhCW78xpJF67g1hMxS6eCToo9PZH4LDB8WKPac=
github.com/jinzhu/gorm v1.9.10/go.mod h1:Kh6hTsSGffh4ui079FHrR5Gg+5D0hgihqDcsDN2BBJY=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
@@ -175,6 +176,7 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4=
github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 h1:2gxZ0XQIU/5z3Z3bUBu+FXuk2pFbkN6tcwi/pjyaDic=
@@ -194,6 +196,8 @@ github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcME
github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -257,10 +261,13 @@ github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8=
github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/spf13/viper v1.6.2 h1:7aKfF+e8/k68gda3LOjo5RxiUqddoFxVq4BKBPrxk5E=
github.com/spf13/viper v1.6.2/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+6 -6
View File
@@ -6,7 +6,7 @@ import (
"github.com/mssola/user_agent"
"go-admin/models"
jwt "go-admin/pkg/jwtauth"
"go-admin/pkg/utils"
"go-admin/tools"
"log"
"net/http"
)
@@ -57,9 +57,9 @@ func Authenticator(c *gin.Context) (interface{}, error) {
ua := user_agent.New(c.Request.UserAgent())
loginlog.Ipaddr = c.ClientIP()
location := utils.GetLocation(c.ClientIP())
location := tools.GetLocation(c.ClientIP())
loginlog.LoginLocation = location
loginlog.LoginTime = utils.GetCurrntTime()
loginlog.LoginTime = tools.GetCurrntTime()
loginlog.Status = "0"
loginlog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
@@ -110,16 +110,16 @@ func LogOut(c *gin.Context) {
var loginlog models.LoginLog
ua := user_agent.New(c.Request.UserAgent())
loginlog.Ipaddr = c.ClientIP()
location := utils.GetLocation(c.ClientIP())
location := tools.GetLocation(c.ClientIP())
loginlog.LoginLocation = location
loginlog.LoginTime = utils.GetCurrntTime()
loginlog.LoginTime = tools.GetCurrntTime()
loginlog.Status = "0"
loginlog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginlog.Browser = browserName + " " + browserVersion
loginlog.Os = ua.OS()
loginlog.Platform = ua.Platform()
loginlog.Username = utils.GetUserName(c)
loginlog.Username = tools.GetUserName(c)
loginlog.Msg = "退出成功"
loginlog.Create()
c.JSON(http.StatusOK, gin.H{
+10
View File
@@ -0,0 +1,10 @@
package handler
import (
"github.com/gin-gonic/gin"
"go-admin/tools/app"
)
func HelloGoAdmin(c *gin.Context) {
app.OK(c,"欢迎使用go-admin 中后台脚手架","")
}
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"go-admin/pkg/app"
"go-admin/tools/app"
"net/http"
"runtime"
"time"
+55 -61
View File
@@ -1,18 +1,7 @@
package main
import (
"context"
"github.com/gin-gonic/gin"
"go-admin/config"
orm "go-admin/database"
"go-admin/models"
"go-admin/models/gorm"
"go-admin/router"
"log"
"net/http"
"os"
"os/signal"
"time"
"go-admin/cmd"
)
// @title go-admin API
@@ -26,54 +15,59 @@ import (
// @in header
// @name Authorization
//func main() {
// configName := "settings"
//
//
// config.InitConfig(configName)
//
// gin.SetMode(gin.DebugMode)
// log.Println(config.DatabaseConfig.Port)
//
// err := gorm.AutoMigrate(orm.Eloquent)
// if err != nil {
// log.Fatalln("数据库初始化失败 err: %v", err)
// }
//
// if config.ApplicationConfig.IsInit {
// if err := models.InitDb(); err != nil {
// log.Fatal("数据库基础数据初始化失败!")
// } else {
// config.SetApplicationIsInit()
// }
// }
//
// r := router.InitRouter()
//
// defer orm.Eloquent.Close()
//
// srv := &http.Server{
// Addr: config.ApplicationConfig.Host + ":" + config.ApplicationConfig.Port,
// Handler: r,
// }
//
// go func() {
// // 服务连接
// if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
// log.Fatalf("listen: %s\n", err)
// }
// }()
// log.Println("Server Run ", config.ApplicationConfig.Host+":"+config.ApplicationConfig.Port)
// log.Println("Enter Control + C Shutdown Server")
// // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
// quit := make(chan os.Signal)
// signal.Notify(quit, os.Interrupt)
// <-quit
// log.Println("Shutdown Server ...")
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
// if err := srv.Shutdown(ctx); err != nil {
// log.Fatal("Server Shutdown:", err)
// }
// log.Println("Server exiting")
//}
func main() {
gin.SetMode(gin.DebugMode)
log.Println(config.DatabaseConfig.Port)
err := gorm.AutoMigrate(orm.Eloquent)
if err != nil {
log.Fatalln("数据库初始化失败 err: %v", err)
}
if config.ApplicationConfig.IsInit {
if err := models.InitDb(); err != nil {
log.Fatal("数据库基础数据初始化失败!")
} else {
config.SetApplicationIsInit()
}
}
r := router.InitRouter()
defer orm.Eloquent.Close()
//if err := r.Run(config.ApplicationConfig.Host + ":" + config.ApplicationConfig.Port); err != nil {
// log.Fatal(err)
//}
srv := &http.Server{
Addr: config.ApplicationConfig.Host + ":" + config.ApplicationConfig.Port,
Handler: r,
}
go func() {
// 服务连接
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
log.Println("Server Run ", config.ApplicationConfig.Host+":"+config.ApplicationConfig.Port)
log.Println("Enter Control + C Shutdown Server")
// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
cmd.Execute()
}
+2 -2
View File
@@ -1,9 +1,9 @@
package middleware
import (
config2 "go-admin/config"
"go-admin/handler"
jwt "go-admin/pkg/jwtauth"
"go-admin/tools/config"
"time"
)
@@ -13,7 +13,7 @@ func AuthInit() (*jwt.GinJWTMiddleware, error) {
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
IdentityKey: config2.ApplicationConfig.JwtSecret,
IdentityKey: config.ApplicationConfig.JwtSecret,
PayloadFunc: handler.PayloadFunc,
IdentityHandler: handler.IdentityHandler,
Authenticator: handler.Authenticator,
+3 -3
View File
@@ -2,20 +2,20 @@ package middleware
import (
"github.com/gin-gonic/gin"
"go-admin/config"
config2 "go-admin/tools/config"
"net/http"
)
func DemoEvn() gin.HandlerFunc {
return func(c *gin.Context) {
if config.ApplicationConfig.Env == "demo" {
if config2.ApplicationConfig.Mode == "demo" {
method := c.Request.Method
if method == "GET" || method == "OPTIONS" || c.Request.RequestURI == "/login" || c.Request.RequestURI == "/api/v1/logout" {
c.Next()
} else {
c.JSON(http.StatusOK, gin.H{
"code": 500,
"msg": config.ApplicationConfig.EnvMsg,
"msg": config2.ApplicationConfig.DemoMsg,
})
c.Abort()
return
+11 -37
View File
@@ -1,13 +1,10 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"go-admin/config"
"go-admin/models"
"go-admin/pkg/utils"
"os"
"go-admin/tools"
"strings"
"time"
)
@@ -18,21 +15,6 @@ var logger = logrus.New()
// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
//写入文件
src, err := os.OpenFile(config.ApplicationConfig.LogPath, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println("err", err)
}
//设置输出
logger.Out = src
//设置日志级别
logger.SetLevel(logrus.DebugLevel)
//设置日志格式
logger.SetFormatter(&logrus.TextFormatter{})
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
@@ -59,24 +41,16 @@ func LoggerToFile() gin.HandlerFunc {
clientIP := c.ClientIP()
// 日志格式
logger.Infof(" %3d %13v %15s %s %s \r\n",
logger.Infof("%s [%s] %3d %13v %15s %s %s \r\n",
startTime.Format("2006-01-02 15:04:05.9999"),
strings.ToUpper(logger.Level.String()),
statusCode,
latencyTime,
clientIP,
reqMethod,
reqUri,
)
logger.Infoln("-")
fmt.Println(
startTime.Format("\n2006-01-02 15:04:05.9999"),
"[INFO]",
reqMethod,
reqUri,
statusCode,
latencyTime,
reqUri,
clientIP,
)
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" {
menu := models.Menu{}
menu.Path = reqUri
@@ -84,9 +58,9 @@ func LoggerToFile() gin.HandlerFunc {
menuList, _ := menu.Get()
sysOperLog := models.SysOperLog{}
sysOperLog.OperIp = clientIP
sysOperLog.OperLocation = utils.GetLocation(clientIP)
sysOperLog.Status = utils.IntToString(statusCode)
sysOperLog.OperName = utils.GetUserName(c)
sysOperLog.OperLocation = tools.GetLocation(clientIP)
sysOperLog.Status = tools.IntToString(statusCode)
sysOperLog.OperName = tools.GetUserName(c)
sysOperLog.RequestMethod = c.Request.Method
sysOperLog.OperUrl = reqUri
if reqUri == "/login" {
@@ -112,9 +86,9 @@ func LoggerToFile() gin.HandlerFunc {
sysOperLog.Title = menuList[0].Title
}
b, _ := c.Get("body")
sysOperLog.OperParam, _ = utils.StructToJsonStr(b)
sysOperLog.CreateBy = utils.GetUserName(c)
sysOperLog.OperTime = utils.GetCurrntTime()
sysOperLog.OperParam, _ = tools.StructToJsonStr(b)
sysOperLog.CreateBy = tools.GetUserName(c)
sysOperLog.OperTime = tools.GetCurrntTime()
sysOperLog.LatencyTime = (latencyTime).String()
sysOperLog.UserAgent = c.Request.UserAgent()
if c.Err() == nil {
+4 -4
View File
@@ -2,10 +2,10 @@ package middleware
import (
"github.com/gin-gonic/gin"
"go-admin/pkg"
mycasbin "go-admin/pkg/casbin"
"go-admin/pkg/jwtauth"
_ "go-admin/pkg/jwtauth"
"go-admin/tools"
"log"
"net/http"
)
@@ -16,18 +16,18 @@ func AuthCheckRole() gin.HandlerFunc {
data, _ := c.Get("JWT_PAYLOAD")
v := data.(jwtauth.MapClaims)
e, err := mycasbin.Casbin()
pkg.HasError(err,"",500)
tools.HasError(err, "", 500)
//检查权限
res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
log.Println("----------------", v["rolekey"], c.Request.URL.Path, c.Request.Method)
pkg.HasError(err,"",500)
tools.HasError(err, "", 500)
if res {
c.Next()
} else {
c.JSON(http.StatusOK, gin.H{
"status": 401,
"code": 401,
"msg": "对不起,您没有该接口访问权限,请联系管理员",
})
c.Abort()
+3 -2
View File
@@ -2,7 +2,8 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
_ "time"
)
type SysConfig struct {
@@ -71,7 +72,7 @@ func (e *SysConfig) GetPage(pageSize int, pageIndex int) ([]SysConfig, int, erro
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_config", table)
var count int
+2 -2
View File
@@ -2,7 +2,7 @@ package models
import (
"github.com/jinzhu/gorm"
"go-admin/pkg/utils"
"go-admin/tools"
)
type DataPermission struct {
@@ -27,7 +27,7 @@ func (e *DataPermission) GetDataScope(tbname string, table *gorm.DB) *gorm.DB {
table = table.Where(tbname+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId)
}
if role.DataScope == "4" {
table = table.Where(tbname+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+utils.IntToString(user.DeptId)+"%")
table = table.Where(tbname+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(user.DeptId)+"%")
}
if role.DataScope == "5" || role.DataScope == "" {
table = table.Where(tbname+".create_by = ?", e.UserId)
+5 -4
View File
@@ -2,7 +2,8 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
_ "time"
)
type Dept struct {
@@ -40,7 +41,7 @@ func (e *Dept) Create() (Dept, error) {
err := result.Error
return doc, err
}
deptPath := "/" + utils.IntToString(e.DeptId)
deptPath := "/" + tools.IntToString(e.DeptId)
if int(e.ParentId) != 0 {
var deptP Dept
orm.Eloquent.Table(e.TableName()).Where("dept_id = ?", e.ParentId).First(&deptP)
@@ -115,7 +116,7 @@ func (e *Dept) GetPage(bl bool) ([]Dept, error) {
if bl {
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_dept", table)
}
@@ -173,7 +174,7 @@ func (e *Dept) Update(id int) (update Dept, err error) {
return
}
deptPath := "/" + utils.IntToString(e.DeptId)
deptPath := "/" + tools.IntToString(e.DeptId)
if int(e.ParentId) != 0 {
var deptP Dept
orm.Eloquent.Table(e.TableName()).Where("dept_id = ?", e.ParentId).First(&deptP)
+2 -2
View File
@@ -2,7 +2,7 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
)
type DictData struct {
@@ -98,7 +98,7 @@ func (e *DictData) GetPage(pageSize int, pageIndex int) ([]DictData, int, error)
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_dict_data", table)
var count int
+2 -2
View File
@@ -2,7 +2,7 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
)
type DictType struct {
@@ -86,7 +86,7 @@ func (e *DictType) GetPage(pageSize int, pageIndex int) ([]DictType, int, error)
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_dict_type", table)
var count int
+2 -2
View File
@@ -2,13 +2,13 @@ package gorm
import (
"github.com/jinzhu/gorm"
"go-admin/config"
"go-admin/models"
"go-admin/models/tools"
config2 "go-admin/tools/config"
)
func AutoMigrate(db *gorm.DB) error {
if config.DatabaseConfig.Dbtype == "mysql" {
if config2.DatabaseConfig.Dbtype == "mysql" {
db = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
}
db.SingularTable(true)
+2 -2
View File
@@ -2,15 +2,15 @@ package models
import (
"fmt"
"go-admin/config"
orm "go-admin/database"
config2 "go-admin/tools/config"
"io/ioutil"
"strings"
)
func InitDb() error {
filePath := "config/db.sql"
if config.DatabaseConfig.Dbtype == "sqlite3" {
if config2.DatabaseConfig.Dbtype == "sqlite3" {
fmt.Println("sqlite3数据库无需初始化!")
return nil
}
+4 -4
View File
@@ -2,7 +2,7 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg"
"go-admin/tools"
"log"
"strings"
)
@@ -19,15 +19,15 @@ func (u *Login) GetUser() (user SysUser, role SysRole, e error) {
e = orm.Eloquent.Table("sys_user").Where("username = ? ", u.Username).Find(&user).Error
if e != nil {
if strings.Contains(e.Error(), "record not found") {
pkg.HasError(e, "账号或密码错误(代码204)", 500)
tools.HasError(e, "账号或密码错误(代码204)", 500)
}
log.Print(e)
return
}
_, e = pkg.CompareHashAndPassword(user.Password, u.Password)
_, e = tools.CompareHashAndPassword(user.Password, u.Password)
if e != nil {
if strings.Contains(e.Error(), "hashedPassword is not the hash of the given password") {
pkg.HasError(e, "账号或密码错误(代码201)", 500)
tools.HasError(e, "账号或密码错误(代码201)", 500)
}
log.Print(e)
return
+10 -4
View File
@@ -3,7 +3,7 @@ package models
import (
"errors"
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
)
type Menu struct {
@@ -248,13 +248,19 @@ func (e *Menu) GetPage() (Menus []Menu, err error) {
if e.MenuName != "" {
table = table.Where("menu_name = ?", e.MenuName)
}
if e.Title != "" {
table = table.Where("title = ?", e.Title)
}
if e.Visible != "" {
table = table.Where("visible = ?", e.Visible)
}
if e.MenuType != "" {
table = table.Where("menu_type = ?", e.MenuType)
}
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_menu", table)
if err = table.Order("sort").Find(&Menus).Error; err != nil {
@@ -285,9 +291,9 @@ func InitPaths(menu *Menu) (err error) {
err = errors.New("父级paths异常,请尝试对当前节点父级菜单进行更新操作!")
return
}
menu.Paths = parentMenu.Paths + "/" + utils.IntToString(menu.MenuId)
menu.Paths = parentMenu.Paths + "/" + tools.IntToString(menu.MenuId)
} else {
menu.Paths = "/0/" + utils.IntToString(menu.MenuId)
menu.Paths = "/0/" + tools.IntToString(menu.MenuId)
}
orm.Eloquent.Table("sys_menu").Where("menu_id = ?", menu.MenuId).Update("paths", menu.Paths)
return
+2 -2
View File
@@ -2,7 +2,7 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
)
type Post struct {
@@ -96,7 +96,7 @@ func (e *Post) GetPage(pageSize int, pageIndex int) ([]Post, int, error) {
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_post", table)
var count int
+2 -2
View File
@@ -2,7 +2,7 @@ package models
import (
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
)
type SysRole struct {
@@ -50,7 +50,7 @@ func (e *SysRole) GetPage(pageSize int, pageIndex int) ([]SysRole, int, error) {
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_role", table)
var count int
+1 -1
View File
@@ -37,7 +37,7 @@ func (rm *SysRoleDept) DeleteRoleDept(roleId int) (bool, error) {
return false, err
}
var role SysRole
if err := orm.Eloquent.Table("sys_role").Where("id = ?", roleId).First(&role).Error; err != nil {
if err := orm.Eloquent.Table("sys_role").Where("role_id = ?", roleId).First(&role).Error; err != nil {
return false, err
}
+2 -2
View File
@@ -3,7 +3,7 @@ package models
import (
"fmt"
orm "go-admin/database"
"go-admin/pkg/utils"
"go-admin/tools"
)
type RoleMenu struct {
@@ -134,7 +134,7 @@ func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
}
func (rm *RoleMenu) Delete(RoleId string, MenuID string) (bool, error) {
rm.RoleId, _ = utils.StringToInt(RoleId)
rm.RoleId, _ = tools.StringToInt(RoleId)
table := orm.Eloquent.Table("sys_role_menu").Where("role_id = ?", RoleId)
if MenuID != "" {
table = table.Where("menu_id = ?", MenuID)
+14 -10
View File
@@ -3,12 +3,10 @@ package models
import (
"errors"
orm "go-admin/database"
"go-admin/pkg"
"go-admin/pkg/utils"
"go-admin/tools"
"golang.org/x/crypto/bcrypt"
"log"
"strings"
"golang.org/x/crypto/bcrypt"
)
// User
@@ -127,21 +125,27 @@ func (e *SysUser) Get() (SysUserView SysUserView, err error) {
func (e *SysUser) GetPage(pageSize int, pageIndex int) ([]SysUserPage, int, error) {
var doc []SysUserPage
table := orm.Eloquent.Select("sys_user.*,sys_dept.dept_name").Table(e.TableName())
table = table.Joins("left join sys_dept on sys_dept.dept_id = sys_user.dept_id")
if e.Username != "" {
table = table.Where("username = ?", e.Username)
}
if e.Status != "" {
table = table.Where("sys_user.status = ?", e.Status)
}
if e.Phone != "" {
table = table.Where("sys_user.phone = ?", e.Phone)
}
if e.DeptId != 0 {
table = table.Where("sys_user.dept_id in (select dept_id from sys_dept where dept_path like ? )", "%"+utils.IntToString(e.DeptId)+"%")
table = table.Where("sys_user.dept_id in (select dept_id from sys_dept where dept_path like ? )", "%"+tools.IntToString(e.DeptId)+"%")
}
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = utils.StringToInt(e.DataScope)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table = dataPermission.GetDataScope("sys_user", table)
var count int
@@ -221,16 +225,16 @@ func (e *SysUser) BatchDelete(id []int) (Result bool, err error) {
func (e *SysUser) SetPwd(pwd SysUserPwd) (Result bool, err error) {
user, _ := e.Get()
_, err = pkg.CompareHashAndPassword(user.Password, pwd.OldPassword)
_, err = tools.CompareHashAndPassword(user.Password, pwd.OldPassword)
if err != nil {
if strings.Contains(err.Error(), "hashedPassword is not the hash of the given password") {
pkg.HasError(err, "密码错误(代码202)", 500)
tools.HasError(err, "密码错误(代码202)", 500)
}
log.Print(err)
return
}
e.Password = pwd.NewPassword
_, err = e.Update(e.UserId)
pkg.HasError(err, "更新密码失败(代码202)", 500)
tools.HasError(err, "更新密码失败(代码202)", 500)
return
}
+3 -3
View File
@@ -2,8 +2,8 @@ package tools
import (
"errors"
"go-admin/config"
orm "go-admin/database"
config2 "go-admin/tools/config"
)
type DBColumns struct {
@@ -25,7 +25,7 @@ func (e *DBColumns) GetPage(pageSize int, pageIndex int) ([]DBColumns, int, erro
var doc []DBColumns
table := orm.Eloquent.Select("*").Table("information_schema.`COLUMNS`")
table = table.Where("table_schema= ? ", config.DatabaseConfig.Database)
table = table.Where("table_schema= ? ", config2.DatabaseConfig.Name)
if e.TableName != "" {
return nil, 0, errors.New("table name cannot be empty!")
@@ -46,7 +46,7 @@ func (e *DBColumns) GetList() ([]DBColumns, error) {
var doc []DBColumns
table := orm.Eloquent.Select("*").Table("information_schema.columns")
table = table.Where("table_schema= ? ", config.DatabaseConfig.Database)
table = table.Where("table_schema= ? ", config2.DatabaseConfig.Name)
if e.TableName == "" {
return nil, errors.New("table name cannot be empty!")
+3 -3
View File
@@ -2,8 +2,8 @@ package tools
import (
"errors"
"go-admin/config"
orm "go-admin/database"
config2 "go-admin/tools/config"
)
type DBTables struct {
@@ -20,7 +20,7 @@ func (e *DBTables) GetPage(pageSize int, pageIndex int) ([]DBTables, int, error)
var doc []DBTables
table := orm.Eloquent.Select("*").Table("information_schema.tables")
table = table.Where("table_schema= ? ", config.DatabaseConfig.Database)
table = table.Where("table_schema= ? ", config2.DatabaseConfig.Name)
if e.TableName != "" {
table = table.Where("TABLE_NAME = ?", e.TableName)
@@ -39,7 +39,7 @@ func (e *DBTables) Get() (DBTables, error) {
var doc DBTables
table := orm.Eloquent.Select("*").Table("information_schema.tables")
table = table.Where("table_schema= ? ", config.DatabaseConfig.Database)
table = table.Where("table_schema= ? ", config2.DatabaseConfig.Name)
if e.TableName == "" {
return doc, errors.New("table name cannot be empty!")
}
+17 -5
View File
@@ -7,7 +7,7 @@ import (
type SysTables struct {
TableId int `gorm:"primary_key;auto_increment" json:"tableId"` //表编码
TableName string `gorm:"type:varchar(255);" json:"tableName"` //表名称
TBName string `gorm:"column:table_name;type:varchar(255);" json:"tableName"` //表名称
TableComment string `gorm:"type:varchar(255);" json:"tableComment"` //表备注
ClassName string `gorm:"type:varchar(255);" json:"className"` //类名
TplCategory string `gorm:"type:varchar(255);" json:"tplCategory"`
@@ -38,6 +38,10 @@ type SysTables struct {
models.BaseModel
}
func (SysTables) TableName() string {
return "sys_tables"
}
type Params struct {
TreeCode string `gorm:"-" json:"treeCode"`
TreeParentCode string `gorm:"-" json:"treeParentCode"`
@@ -49,8 +53,8 @@ func (e *SysTables) GetPage(pageSize int, pageIndex int) ([]SysTables, int, erro
table := orm.Eloquent.Select("*").Table("sys_tables")
if e.TableName != "" {
table = table.Where("table_name = ?", e.TableName)
if e.TBName != "" {
table = table.Where("table_name = ?", e.TBName)
}
if e.TableComment != "" {
table = table.Where("table_comment = ?", e.TableComment)
@@ -70,8 +74,8 @@ func (e *SysTables) Get() (SysTables, error) {
var err error
table := orm.Eloquent.Select("*").Table("sys_tables")
if e.TableName != "" {
table = table.Where("table_name = ?", e.TableName)
if e.TBName != "" {
table = table.Where("table_name = ?", e.TBName)
}
if e.TableId != 0 {
table = table.Where("table_id = ?", e.TableId)
@@ -138,3 +142,11 @@ func (e *SysTables) Delete() (success bool, err error) {
success = true
return
}
func (e *SysTables) BatchDelete(id []int) (Result bool, err error) {
if err = orm.Eloquent.Table(e.TableName()).Where(" table_id in (?)", id).Delete(&SysColumns{}).Error; err != nil {
return
}
Result = true
return
}
+3 -3
View File
@@ -6,14 +6,14 @@ import (
gormadapter "github.com/casbin/gorm-adapter/v2"
"github.com/go-kit/kit/endpoint"
_ "github.com/go-sql-driver/mysql"
"go-admin/config"
"go-admin/pkg/utils"
"go-admin/database"
"go-admin/tools/config"
)
var Em endpoint.Middleware
func Casbin() (*casbin.Enforcer, error) {
conn := config.DatabaseConfig.Username + ":" + config.DatabaseConfig.Password + "@tcp(" + config.DatabaseConfig.Host + ":" + utils.IntToString(config.DatabaseConfig.Port) + ")/" + config.DatabaseConfig.Database
conn := database.GetMysqlConnect()
if config.DatabaseConfig.Dbtype == "sqlite3" {
conn = config.DatabaseConfig.Host
}
+4 -6
View File
@@ -5,7 +5,7 @@ import (
"errors"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"go-admin/config"
config2 "go-admin/tools/config"
"io/ioutil"
"net/http"
"strings"
@@ -283,9 +283,9 @@ func (mw *GinJWTMiddleware) MiddlewareInit() error {
}
mw.Timeout = time.Hour
if config.JwtConfig.Timeout != 0 {
if config2.JwtConfig.Timeout != 0 {
// TODO: token过期时长
mw.Timeout = time.Duration(config.JwtConfig.Timeout) * time.Second
mw.Timeout = time.Duration(config2.JwtConfig.Timeout) * time.Second
}
if mw.TimeFunc == nil {
@@ -391,7 +391,7 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
return
}
if int64(claims["exp"].(float64)) < mw.TimeFunc().Unix() {
mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
mw.unauthorized(c, 6401, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
return
}
@@ -680,8 +680,6 @@ func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) {
if mw.usingPublicKeyAlgo() {
return mw.pubKey, nil
}
// save token string if vaild
c.Set("JWT_TOKEN", token)
return mw.Key, nil
+2
View File
@@ -27,6 +27,7 @@ func InitRouter() *gin.Engine {
r.Use(middleware.RequestId())
r.Use(middleware.DemoEvn())
r.GET("/", system.HelloWorld)
r.Static("/static", "./static")
r.GET("/info", handler.Ping)
@@ -75,6 +76,7 @@ func InitRouter() *gin.Engine {
auth := r.Group("/api/v1")
auth.Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
auth.GET("/deptList", system.GetDeptList)
auth.GET("/deptTree", system.GetDeptTree)
auth.GET("/dept/:deptId", system.GetDept)
+1
View File
@@ -4,6 +4,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/models"
"go-admin/tools/app"
"go-admin/pkg"
"go-admin/utils"
"net/http"
+46
View File
@@ -0,0 +1,46 @@
import request from '@/utils/request'
// 查询参数列表
export function list{{.ClassName}}(query) {
return request({
url: '/api/v1/{{.ModuleName}}List',
method: 'get',
params: query
})
}
// 查询参数详细
export function get{{.ClassName}} ({{.PkJsonField}}) {
return request({
url: '/api/v1/{{.ModuleName}}/' + {{.PkJsonField}},
method: 'get'
})
}
// 新增参数配置
export function add{{.ClassName}}(data) {
return request({
url: '/api/v1/{{.ModuleName}}',
method: 'post',
data: data
})
}
// 修改参数配置
export function update{{.ClassName}}(data) {
return request({
url: '/api/v1/{{.ModuleName}}',
method: 'put',
data: data
})
}
// 删除参数配置
export function del{{.ClassName}}({{.PkJsonField}}) {
return request({
url: '/api/v1/{{.ModuleName}}/' + {{.PkJsonField}},
method: 'delete'
})
}
+271
View File
@@ -0,0 +1,271 @@
<template>
<div class="app-container">
<el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
{{range .Columns}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
<el-form-item label="参数名称" prop="{{.JsonField}}">
<el-input v-model="queryParams.{{.JsonField}}" placeholder="请输入{{.ColumnComment}}" clearable size="small" @keyup.enter.native="handleQuery" />
</el-form-item>
{{end}}
{{- end }}
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:add']"
type="primary"
icon="el-icon-plus"
size="mini"
@click="handleAdd"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:edit']"
type="success"
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:remove']"
type="danger"
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
>删除</el-button>
</el-col>
</el-row>
<el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
{{- range .Columns -}}
{{- $x := .IsList -}}
{{- if ($x) -}}
<el-table-column label="{{.ColumnComment}}" align="center" prop="{{.JsonField}}" :show-overflow-tooltip="true" />
{{- end -}}
{{- end }}
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:edit']"
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
>修改</el-button>
<el-button
v-permisaction="['{{.PackageName}}:{{.ModuleName}}:remove']"
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
>删除</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageIndex"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改参数配置对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px">
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item label="参数名称" prop="configName">
<el-input v-model="form.configName" placeholder="请输入参数名称" />
</el-form-item>
{{ range .Columns }}
{{- $x := .IsInsert -}}
{{- if ($x) -}}
<el-form-item label="{{.ColumnComment}}" prop="{{.JsonField}}">
<el-input v-model="form.{{.JsonField}}" placeholder="{{.ColumnComment}}" />
</el-form-item>
{{ end }}
{{- end }}
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { list{{.ClassName}}, get{{.ClassName}}, del{{.ClassName}}, add{{.ClassName}}, update{{.ClassName}} } from '@/api/system/config'
import { formatJson } from '@/utils'
export default {
name: 'Config',
data() {
return {
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 总条数
total: 0,
// 参数表格数据
configList: [],
// 弹出层标题
title: '',
// 是否显示弹出层
open: false,
// 类型数据字典
typeOptions: [],
// 日期范围
dateRange: [],
// 查询参数
queryParams: {
pageIndex: 1,
pageSize: 10,
{{- range .Columns -}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
{{.JsonField}}: undefined,
{{- end -}}
{{- end }}
},
// 表单参数
form: {},
// 表单校验
rules: {
{{- range .Columns -}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
{{.JsonField}}: [
{ required: true, message: '{{.ColumnComment}}不能为空', trigger: 'blur' }
],
{{ end }}
{{- end -}}
}
}
},
created() {
this.getList()
},
methods: {
/** 查询参数列表 */
getList() {
this.loading = true
list{{.ClassName}}(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
this.{{.ModuleName}}List = response.data.list
this.total = response.data.count
this.loading = false
}
)
}
// 取消按钮
cancel() {
this.open = false
this.reset()
},
// 表单重置
reset() {
this.form = {
{{ range .Columns}}
{{- $x := .IsInsert -}}
{{ if ($x) -}}
{{.JsonField}}: undefined,
{{ end }}
{{- end -}}
}
this.resetForm('form')
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageIndex = 1
this.getList()
},
/** 重置按钮操作 */
resetQuery() {
this.dateRange = []
this.resetForm('queryForm')
this.handleQuery()
},
/** 新增按钮操作 */
handleAdd() {
this.reset()
this.open = true
this.title = '添加{{.TableComment}}'
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.{{.PkJsonField}})
this.single = selection.length !== 1
this.multiple = !selection.length
},
/** 修改按钮操作 */
handleUpdate(row) {
this.reset()
const {{.PkJsonField}} = row.{{.PkJsonField}} || this.ids
get{{.ClassName}}({{.PkJsonField}}).then(response => {
this.form = response.data
this.open = true
this.title = '修改{{.TableComment}}'
})
},
/** 提交按钮 */
submitForm: function() {
this.$refs['form'].validate(valid => {
if (valid) {
if (this.form.{{.PkJsonField}} !== undefined) {
update{{.ClassName}}(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess('修改成功')
this.open = false
this.getList()
} else {
this.msgError(response.msg)
}
})
} else {
add{{.ClassName}}(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess('新增成功')
this.open = false
this.getList()
} else {
this.msgError(response.msg)
}
})
}
}
})
},
/** 删除按钮操作 */
handleDelete(row) {
const Ids = row.{{.PkJsonField}} || this.ids
this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function() {
return del{{.ClassName}}(Ids)
}).then(() => {
this.getList()
this.msgSuccess('删除成功')
}).catch(function() {})
}
}
}
</script>
+1 -1
View File
@@ -81,7 +81,7 @@ func Get{{.ClassName}}(c *gin.Context) {
// @Tags 配置
// @Accept application/json
// @Product application/json
// @Param data body models.Config true "data"
// @Param data body models.{{.ClassName}} true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/data [post]
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -3,30 +3,26 @@ package config
import "github.com/spf13/viper"
type Application struct {
IsInit bool
ReadTimeout int
WriterTimeout int
Host string
Port string
Name string
JwtSecret string
LogPath string
Env string
EnvMsg string
Mode string
DemoMsg string
}
func InitApplication(cfg *viper.Viper) *Application {
return &Application{
IsInit: cfg.GetBool("isInit"),
ReadTimeout: cfg.GetInt("readTimeout"),
WriterTimeout: cfg.GetInt("writerTimeout"),
Host: cfg.GetString("host"),
Port: cfg.GetString("port"),
Name: cfg.GetString("name"),
JwtSecret: cfg.GetString("jwtSecret"),
LogPath: cfg.GetString("logPath"),
Env: cfg.GetString("env"),
EnvMsg: cfg.GetString("envMsg"),
Mode: cfg.GetString("mode"),
DemoMsg: cfg.GetString("demoMsg"),
}
}
+29 -7
View File
@@ -1,20 +1,36 @@
package config
import (
"fmt"
"github.com/spf13/viper"
"io/ioutil"
"log"
"os"
"strings"
)
var cfgDatabase *viper.Viper
var cfgApplication *viper.Viper
var cfgJwt *viper.Viper
var cfgLog *viper.Viper
func init() {
viper.SetConfigName("settings")
viper.AddConfigPath("./config")
err := viper.ReadInConfig()
//func init() {
// InitConfig("settings.dev")
//}
//载入配置文件
func ConfigSetup(path string) {
viper.SetConfigFile(path)
content, err := ioutil.ReadFile(path)
if err != nil {
log.Println(err)
log.Fatal(fmt.Sprintf("Read config file fail: %s", err.Error()))
}
//Replace environment variables
err = viper.ReadConfig(strings.NewReader(os.ExpandEnv(string(content))))
if err != nil {
log.Fatal(fmt.Sprintf("Parse config file fail: %s", err.Error()))
}
cfgDatabase = viper.Sub("settings.database")
@@ -34,13 +50,19 @@ func init() {
panic("config not found settings.jwt")
}
JwtConfig = InitJwt(cfgJwt)
cfgLog = viper.Sub("settings.log")
if cfgLog == nil {
panic("config not found settings.log")
}
LogConfig = InitLog(cfgLog)
}
func SetApplicationIsInit() {
SetConfig("./config","settings.application.isInit", false)
SetConfig("./config", "settings.application.isInit", false)
}
func SetConfig(configPath string,key string,value interface{}){
func SetConfig(configPath string, key string, value interface{}) {
viper.AddConfigPath(configPath)
viper.Set(key, value)
viper.WriteConfig()
@@ -6,7 +6,7 @@ type Database struct {
Dbtype string
Host string
Port int
Database string
Name string
Username string
Password string
}
@@ -16,7 +16,7 @@ func InitDatabase(cfg *viper.Viper) *Database {
Port: cfg.GetInt("port"),
Dbtype: cfg.GetString("dbType"),
Host: cfg.GetString("host"),
Database: cfg.GetString("database"),
Name: cfg.GetString("name"),
Username: cfg.GetString("username"),
Password: cfg.GetString("password"),
}
File renamed without changes.
+15
View File
@@ -0,0 +1,15 @@
package config
import "github.com/spf13/viper"
type Log struct {
Dir string
}
func InitLog(cfg *viper.Viper) *Log {
return &Log{
Dir: cfg.GetString("dir"),
}
}
var LogConfig = new(Log)
+13
View File
@@ -0,0 +1,13 @@
package tools
type (
Mode string
)
const (
ModeDev Mode = "dev" //开发模式
ModeTest Mode = "test" //测试模式
ModeProd Mode = "prod" //生产模式
Mysql = "mysql" //mysql数据库标识
Sqlite = "sqlite" //sqlite
)
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import "strconv"
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import "strconv"
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import "strconv"
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import (
"encoding/json"
+56
View File
@@ -0,0 +1,56 @@
package tools
import (
"errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"os"
"time"
)
func InitLogger() {
switch Mode(viper.GetString("settings.application.mode")) {
case ModeDev, ModeTest:
log.SetOutput(os.Stdout)
log.SetLevel(log.TraceLevel)
case ModeProd:
file, err := os.OpenFile(viper.GetString("logger.dir")+"/api-"+time.Now().Format("2006-01-02")+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC, 0600)
if err != nil {
log.Fatalln("log init failed")
}
var info os.FileInfo
info, err = file.Stat()
if err != nil {
log.Fatal(err)
}
fileWriter := logFileWriter{file, info.Size()}
log.SetOutput(&fileWriter)
log.SetLevel(log.ErrorLevel)
}
log.SetReportCaller(true)
}
type logFileWriter struct {
file *os.File
size int64
}
func (p *logFileWriter) Write(data []byte) (n int, err error) {
if p == nil {
return 0, errors.New("logFileWriter is nil")
}
if p.file == nil {
return 0, errors.New("file not opened")
}
n, e := p.file.Write(data)
p.size += int64(n)
//每天一个文件
if p.file.Name() != viper.GetString("logger.dir")+"/api-"+time.Now().Format("2006-01-02")+".log" {
p.file.Close()
p.file, _ = os.OpenFile(viper.GetString("logger.dir")+"/api-"+time.Now().Format("2006-01-02")+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC, 0600)
p.size = 0
}
return n, e
}
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import (
"encoding/json"
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import (
"github.com/gin-gonic/gin"
+1 -1
View File
@@ -1,4 +1,4 @@
package utils
package tools
import (
"fmt"
+2 -2
View File
@@ -1,4 +1,4 @@
package pkg
package tools
import (
"golang.org/x/crypto/bcrypt"
@@ -33,7 +33,7 @@ func Assert(condition bool, msg string, code ...int) {
if len(code) > 0 {
statusCode = code[0]
}
panic("CustomErroe#" + strconv.Itoa(statusCode) + "#" + msg)
panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
}
}