Upgrade code generation supports drop-down box merging and dictionary usage

This commit is contained in:
zhangwenjian
2020-06-05 20:43:58 +08:00
parent c0b8199c36
commit 259dec9c94
11 changed files with 273 additions and 177 deletions
+1 -48
View File
@@ -166,51 +166,6 @@ env GOOS=linux GOARCH=amd64 go build main.go
演示地址:[http://www.zhangwj.com](http://www.zhangwj.com/#/login)
## 📈 版本
### 2020-04-23 新功能及优化
1. 添加单服务命令
2. 添加单数据库数据化命令
3. 调整项目结构
3. 部分代码优化
3. 添加根接口
4. 其他已知bug的修复
### 2020-04-13 新功能及优化
1. 数据库初始化方式改为gorm 迁移方式
2. 删除原有创建、修改时间和is_del字段,改用gorm 原生逻辑删除功能
3. 添加服务监控基础指标
3. 框架结构调整
3. 部分代码优化
4. 其他已知bug的修复
### 2020-04-08 新功能及优化
1. 添加sqlite3的支持
1. 数据库字段格式统一
2. 用户新增bug修复
3. 修改数据初始化脚本
4. 验证码改为数字验证
5. 删除redis暂时无用组件
6. 其他已知bug的修复
### 2020-04-01 新功能及优化
1. 代码生成器
2. 代码优化
3. 已知bug修复
#### 2020-03-15 新功能及优化
1. 添加用户头像上传
2. 添加用户密码修改
3. 操作日志页面调整
4. 优化验证码背景色
看到好多体验的朋友验证码错误,所以调整了对比度,方便大家体验!
## 📨 互动
@@ -228,8 +183,6 @@ env GOOS=linux GOARCH=amd64 go build main.go
</table>
## 🤝 特别感谢
[chengxiao](https://github.com/chengxiao)
[gin](https://github.com/gin-gonic/gin)
@@ -250,7 +203,7 @@ env GOOS=linux GOARCH=amd64 go build main.go
## ❤️ 赞助者
zhuqiyun
zhuqiyun LLL狐
## 🔑 License
+9
View File
@@ -14,6 +14,10 @@ func GetInfo(c *gin.Context) {
var permissions = make([]string, 1)
permissions[0] = "*:*:*"
var buttons = make([]string, 1)
buttons[0] = "*:*:*"
RoleMenu := models.RoleMenu{}
RoleMenu.RoleId = tools.GetRoleId(c)
@@ -21,9 +25,11 @@ func GetInfo(c *gin.Context) {
mp["roles"] = roles
if tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员" {
mp["permissions"] = permissions
mp["buttons"] = buttons
} else {
list, _ := RoleMenu.GetPermis()
mp["permissions"] = list
mp["buttons"] = list
}
sysuser := models.SysUser{}
@@ -37,6 +43,9 @@ func GetInfo(c *gin.Context) {
if user.Avatar != "" {
mp["avatar"] = user.Avatar
}
mp["userName"] = user.NickName
mp["userId"] = user.UserId
mp["deptId"] = user.DeptId
mp["name"] = user.NickName
app.OK(c, mp, "")
+5
View File
@@ -23,6 +23,8 @@ func Preview(c *gin.Context) {
tools2.HasError(err, "", -1)
t4, err := template.ParseFiles("template/vue.go.template")
tools2.HasError(err, "", -1)
t5, err := template.ParseFiles("template/router.go.template")
tools2.HasError(err, "", -1)
tab, _ := table.Get()
var b1 bytes.Buffer
err = t1.Execute(&b1, tab)
@@ -32,12 +34,15 @@ func Preview(c *gin.Context) {
err = t3.Execute(&b3, tab)
var b4 bytes.Buffer
err = t4.Execute(&b4, tab)
var b5 bytes.Buffer
err = t5.Execute(&b5, 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()
mp["template/router.go.template"] = b5.String()
var res app.Response
res.Data = mp
+22
View File
@@ -0,0 +1,22 @@
package middleware
import (
"github.com/gin-gonic/gin"
)
func InitMiddleware(r *gin.Engine) {
// 日志处理
r.Use(LoggerToFile())
// 自定义错误处理
r.Use(CustomError)
// NoCache is a middleware function that appends headers
r.Use(NoCache)
// 跨域处理
r.Use(Options)
// Secure is a middleware function that appends security
r.Use(Secure)
// Set X-Request-Id header
r.Use(RequestId())
}
-37
View File
@@ -1,37 +0,0 @@
package router
import (
"github.com/gin-gonic/gin"
"go-admin/pkg/jwtauth"
jwt "go-admin/pkg/jwtauth"
)
// 路由示例
func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
// 无需认证的路由
examplesNoCheckRoleRouter(r)
// 需要认证的路由
examplesCheckRoleRouter(r, authMiddleware)
return r
}
// 无需认证的路由示例
func examplesNoCheckRoleRouter(r *gin.Engine) {
//v1 := r.Group("/api/v1")
//v1.GET("/examples/list", examples.apis)
}
// 需要认证的路由示例
func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
//v1auth := r.Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
//{
// v1auth.GET("/examples/list", examples.apis)
//}
}
+26
View File
@@ -0,0 +1,26 @@
package router
import (
"github.com/gin-gonic/gin"
"go-admin/middleware"
_ "go-admin/pkg/jwtauth"
"go-admin/tools"
)
func InitRouter() *gin.Engine {
r := gin.New()
middleware.InitMiddleware(r)
// the jwt middleware
authMiddleware, err := middleware.AuthInit()
tools.HasError(err, "JWT Init Error", 500)
// 注册系统路由
InitSysRouter(r, authMiddleware)
// 注册业务路由
// TODO: 这里可存放业务路由,里边并无实际路由是有演示代码
InitExamplesRouter(r, authMiddleware)
return r
}
+28 -25
View File
@@ -2,36 +2,39 @@ package router
import (
"github.com/gin-gonic/gin"
"go-admin/middleware"
_ "go-admin/pkg/jwtauth"
"go-admin/tools"
_ "github.com/gin-gonic/gin"
"go-admin/pkg/jwtauth"
jwt "go-admin/pkg/jwtauth"
)
func InitRouter() *gin.Engine {
r := gin.New()
// 日志处理
r.Use(middleware.LoggerToFile())
// 自定义错误处理
r.Use(middleware.CustomError)
// NoCache is a middleware function that appends headers
r.Use(middleware.NoCache)
// 跨域处理
r.Use(middleware.Options)
// Secure is a middleware function that appends security
r.Use(middleware.Secure)
// Set X-Request-Id header
r.Use(middleware.RequestId())
// the jwt middleware
authMiddleware, err := middleware.AuthInit()
tools.HasError(err, "JWT Init Error", 500)
// 注册系统路由
InitSysRouter(r, authMiddleware)
// 路由示例
func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
// 注册业务路由
// TODO: 这里可存放业务路由,里边并无实际路由是有演示代码
InitExamplesRouter(r, authMiddleware)
// 无需认证的路由
examplesNoCheckRoleRouter(r)
// 需要认证的路由
examplesCheckRoleRouter(r, authMiddleware)
return r
}
// 无需认证的路由示例
func examplesNoCheckRoleRouter(r *gin.Engine) {
//v1 := r.Group("/api/v1")
//v1.GET("/examples/list", examples.apis)
}
// 需要认证的路由示例
func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
//v1 := r.Group("/api/v1")
//v1auth := v1.Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
//{
// v1auth.GET("/examples/list", examples.apis)
//}
}
+22 -13
View File
@@ -9,7 +9,13 @@ _ "time"
type {{.ClassName}} struct {
{{ range .Columns -}}
{{$x := .Pk}}
{{if ($x)}}{{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};primary_key"`{{else}}{{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};"`{{end}} // {{.ColumnComment}}
{{- if ($x) }}
{{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};primary_key"` // {{.ColumnComment}}
{{- else if eq .GoField "CreatedAt" -}}
{{- else if eq .GoField "UpdatedAt" -}}
{{- else if eq .GoField "DeletedAt" -}}
{{- else }}
{{.GoField}} {{.GoType}} `json:"{{.JsonField}}" gorm:"type:{{.ColumnType}};"` // {{.ColumnComment}}{{end -}}
{{- end }}
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
@@ -37,14 +43,18 @@ func (e *{{.ClassName}}) Create() ({{.ClassName}}, error) {
func (e *{{.ClassName}}) Get() ({{.ClassName}}, error) {
var doc {{.ClassName}}
table := orm.Eloquent.Table(e.TableName())
{{ range .Columns -}}
{{$z := .IsQuery}}
{{- if ($z) -}}
if e.{{.GoField}} != "" {
table = table.Where("{{.ColumnName}} = ?", e.{{.GoField}})
{{ range .Columns }}
{{$x := .Pk}}
{{- if ($x) }}
if e.{{.GoField}} != {{if eq .GoType "string" -}} "" {{ else if eq .GoType "int" -}} 0 {{- end}} {
table = table.Where("{{.ColumnName}}{{if eq .QueryType "EQ"}} = {{else if eq .QueryType "NE"}} != {{else if eq .QueryType "GT"}} > {{else if eq .QueryType "GTE"}} >= {{else if eq .QueryType "LT"}} < {{else if eq .QueryType "LTE"}} <= {{else if eq .QueryType "LIKE"}} like {{end}}?", {{ if eq .QueryType "LIKE"}}"%"+e.{{.GoField}}+"%"{{else}}e.{{.GoField}}{{end}})
}
{{- else if .IsQuery }}
if e.{{.GoField}} != {{if eq .GoType "string" -}} "" {{ else if eq .GoType "int" -}} 0 {{- end}} {
table = table.Where("{{.ColumnName}}{{if eq .QueryType "EQ"}} = {{else if eq .QueryType "NE"}} != {{else if eq .QueryType "GT"}} > {{else if eq .QueryType "GTE"}} >= {{else if eq .QueryType "LT"}} < {{else if eq .QueryType "LTE"}} <= {{else if eq .QueryType "LIKE"}} like {{end}}?", {{ if eq .QueryType "LIKE"}}"%"+e.{{.GoField}}+"%"{{else}}e.{{.GoField}}{{end}})
}
{{ end -}}
{{ end }}
{{- end }}
if err := table.First(&doc).Error; err != nil {
return doc, err
@@ -57,14 +67,13 @@ func (e *{{.ClassName}}) GetPage(pageSize int, pageIndex int) ([]{{.ClassName}},
var doc []{{.ClassName}}
table := orm.Eloquent.Select("*").Table(e.TableName())
{{ range .Columns -}}
{{$z := .IsQuery}}
{{- if ($z) -}}
if e.{{.GoField}} != "" {
table = table.Where("{{.ColumnName}} = ?", e.{{.GoField}})
{{ range .Columns }}
{{- if .IsQuery }}
if e.{{.GoField}} != {{if eq .GoType "string" -}} "" {{ else if eq .GoType "int" -}} 0 {{- end}} {
table = table.Where("{{.ColumnName}}{{if eq .QueryType "EQ"}} = {{else if eq .QueryType "NE"}} != {{else if eq .QueryType "GT"}} > {{else if eq .QueryType "GTE"}} >= {{else if eq .QueryType "LT"}} < {{else if eq .QueryType "LTE"}} <= {{else if eq .QueryType "LIKE"}} like {{end}}?", {{ if eq .QueryType "LIKE"}}"%"+e.{{.GoField}}+"%"{{else}}e.{{.GoField}}{{end}})
}
{{ end -}}
{{ end }}
{{- end }}
// 数据权限控制(如果不需要数据权限请将此处去掉)
dataPermission := new(DataPermission)
+33
View File
@@ -0,0 +1,33 @@
// 需认证的路由代码
func register{{.ClassName}}Router(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r := v1.Group("/{{.ModuleName}}").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
r.GET("/:{{.PkJsonField}}", {{.ModuleName}}.Get{{.ClassName}})
r.POST("", {{.ModuleName}}.Insert{{.ClassName}})
r.PUT("", {{.ModuleName}}.Update{{.ClassName}})
r.DELETE("/:{{.PkJsonField}}", {{.ModuleName}}.Delete{{.ClassName}})
}
l := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
l.GET("/{{.ModuleName}}List",{{.ModuleName}}.Get{{.ClassName}}List)
}
}
// 无需认证的路由代码
func register{{.ClassName}}Router(v1 *gin.RouterGroup) {
v1.GET("/{{.ModuleName}}List",{{.ModuleName}}.Get{{.ClassName}}List)
r := v1.Group("/{{.ModuleName}}")
{
r.GET("/:{{.PkJsonField}}", {{.ModuleName}}.Get{{.ClassName}})
r.POST("", {{.ModuleName}}.Insert{{.ClassName}})
r.PUT("", {{.ModuleName}}.Update{{.ClassName}})
r.DELETE("/:{{.PkJsonField}}", {{.ModuleName}}.Delete{{.ClassName}})
}
}
+88 -16
View File
@@ -1,3 +1,4 @@
{{$tableComment:=.TableComment}}
<template>
<div class="app-container">
<el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
@@ -5,7 +6,18 @@
{{- $x := .IsQuery -}}
{{- if ($x) -}}
<el-form-item label="{{.ColumnComment}}" prop="{{.JsonField}}">
{{if eq .DictType "" -}}
<el-input v-model="queryParams.{{.JsonField}}" placeholder="请输入{{.ColumnComment}}" clearable size="small" @keyup.enter.native="handleQuery" />
{{- else -}}
<el-select v-model="queryParams.{{.JsonField}}" placeholder="{{$tableComment}}{{.ColumnComment}}" clearable size="small">
<el-option
v-for="dict in {{.JsonField}}Options"
:key="dict.dictValue"
:label="dict.dictLabel"
:value="dict.dictValue"
/>
</el-select>
{{- end}}
</el-form-item>
{{end}}
{{- end }}
@@ -51,9 +63,19 @@
<el-table-column type="selection" width="55" align="center" />
{{- range .Columns -}}
{{- $x := .IsList -}}
{{- if ($x) -}}
{{- if ($x) }}
{{- if ne .DictType "" -}}
<el-table-column label="{{.ColumnComment}}" align="center" prop="{{.JsonField}}" :formatter="{{.JsonField}}Format" width="100">
<template slot-scope="scope">
{{ "{{" }} {{.JsonField}}Format(scope.row) {{"}}"}}
</template>
</el-table-column>
{{- end -}}
{{- if eq .DictType "" -}}
<el-table-column label="{{.ColumnComment}}" align="center" prop="{{.JsonField}}" :show-overflow-tooltip="true" />
{{- end -}}
{{- end }}
{{- end }}
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
@@ -83,16 +105,39 @@
@pagination="getList"
/>
<!-- 添加或修改参数配置对话框 -->
<!-- 添加或修改对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px">
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
{{ range .Columns }}
{{- $x := .IsInsert -}}
{{- if ($x) -}}
{{- if (.Pk) }}
{{- else if eq .GoField "CreatedAt" -}}
{{- else if eq .GoField "UpdatedAt" -}}
{{- else if eq .GoField "DeletedAt" -}}
{{- else if eq .GoField "UpdateBy" -}}
{{- else if eq .GoField "CreateBy" -}}
{{- else }}
<el-form-item label="{{.ColumnComment}}" prop="{{.JsonField}}" >
<el-input v-model="form.{{.JsonField}}" placeholder="{{.ColumnComment}}" />
{{ if eq "input" .HtmlType -}}
<el-input v-model="form.{{.JsonField}}" placeholder="{{.ColumnComment}}" {{if eq .IsEdit "false" -}}:disabled="isEdit" {{- end}}/>
{{- else if eq "select" .HtmlType -}}
<el-select v-model="form.{{.JsonField}}" {{if eq .IsEdit "false" -}} :disabled="isEdit" {{- end }}>
<el-option label="demo1" value="demo1" />
<el-option label="demo2" value="demo2" />
</el-select>
{{- else if eq "radio" .HtmlType -}}
<el-radio-group v-model="form.{{.JsonField}}">
<el-radio
v-for="dict in {{.JsonField}}Options"
:key="dict.dictValue"
:label="dict.dictValue"
>{{"{{"}} dict.dictLabel {{"}}"}}</el-radio>
</el-radio-group>
{{- end }}
</el-form-item>
{{ end }}
{{- end }}
{{- end }}
{{- end }}
</el-form>
<div slot="footer" class="dialog-footer">
@@ -120,35 +165,38 @@
multiple: true,
// 总条数
total: 0,
// 参数表格数据
configList: [],
// 弹出层标题
title: '',
// 是否显示弹出层
open: false,
isEdit: false,
// 类型数据字典
typeOptions: [],
// 日期范围
dateRange: [],
{{range .Columns}}
{{- if ne .DictType "" -}}
{{.JsonField}}Options: [],
{{- end -}}
{{- end }}
// 查询参数
queryParams: {
pageIndex: 1,
pageSize: 10,
{{- range .Columns -}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
{{ range .Columns }}
{{- if (.IsQuery) -}}
{{.JsonField}}:undefined,
{{- end -}}
{{ end -}}
{{- end }}
},
// 表单参数
form: {},
form: {
},
// 表单校验
rules: {
{{- range .Columns -}}
{{- $x := .IsQuery -}}
{{- if ($x) -}}
{{.JsonField}}: [
{{.JsonField}}:
[
{required: true, message: '{{.ColumnComment}}不能为空', trigger: 'blur'}
],
{{ end }}
@@ -158,6 +206,13 @@
},
created() {
this.getList()
{{range .Columns}}
{{- if ne .DictType "" -}}
this.getDicts('{{.DictType}}').then(response => {
this.{{.JsonField}}Options = response.data
})
{{- end -}}
{{- end }}
},
methods: {
/** 查询参数列表 */
@@ -180,13 +235,28 @@
this.form = {
{{ range .Columns}}
{{- $x := .IsInsert -}}
{{ if ($x) -}}
{{- if ($x) -}}
{{- if eq .GoField "CreatedAt" -}}
{{- else if eq .GoField "UpdatedAt" -}}
{{- else if eq .GoField "DeletedAt" -}}
{{- else if eq .GoField "UpdateBy" -}}
{{- else if eq .GoField "CreateBy" -}}
{{- else }}
{{.JsonField}}: undefined,
{{ end }}
{{- end }}
{{- end -}}
{{- end }}
}
this.resetForm('form')
},
{{range .Columns}}
{{- if ne .DictType "" -}}
{{.JsonField}}Format(row) {
return this.selectDictLabel(this.{{.JsonField}}Options, row.{{.JsonField}})
},
{{- end -}}
{{- end }}
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageIndex = 1
@@ -203,6 +273,7 @@
this.reset()
this.open = true
this.title = '添加{{.TableComment}}'
this.isEdit = false
},
// 多选框选中数据
handleSelectionChange(selection) {
@@ -218,6 +289,7 @@
this.form = response.data
this.open = true
this.title = '修改{{.TableComment}}'
this.isEdit = true
})
},
/** 提交按钮 */
+3 -2
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"github.com/gin-gonic/gin"
jwt "go-admin/pkg/jwtauth"
"log"
)
func ExtractClaims(c *gin.Context) jwt.MapClaims {
@@ -20,7 +21,7 @@ func GetUserId(c *gin.Context) int {
if data["identity"] != nil {
return int((data["identity"]).(float64))
}
fmt.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 说明:缺少identity")
log.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 说明:缺少identity")
return 0
}
@@ -29,7 +30,7 @@ func GetUserIdStr(c *gin.Context) string {
if data["identity"] != nil {
return Int64ToString(int64((data["identity"]).(float64)))
}
fmt.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 缺少identity")
log.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 缺少identity")
return ""
}