├── model.go ├── column.go ├── Readme.md └── controller.go /model.go: -------------------------------------------------------------------------------- 1 | package gii 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | type Options struct { 10 | name string 11 | path string 12 | column []column 13 | packet map[string]string 14 | namespace string 15 | modelsNamespace string 16 | } 17 | func createModel(options Options) { 18 | 19 | content := `package ` 20 | if options.namespace == ""{ 21 | content += "models" 22 | }else { 23 | content += options.namespace 24 | } 25 | 26 | content +=` 27 | 28 | import ( 29 | "github.com/astaxie/beego/orm"` 30 | 31 | for _,v := range options.packet { 32 | content += "\n "+`"`+v+`"` 33 | } 34 | content += "\n" + `)` 35 | content += "\n\n" +`type ` + options.name + ` struct {` 36 | 37 | for _,vlues := range options.column { 38 | 39 | content += "\n" + ` `+ vlues.name + ` ` + vlues.value 40 | } 41 | 42 | content += "\n}\n" 43 | content += ` 44 | func init() { 45 | // 需要在init中注册定义的model 46 | orm.RegisterModel(new(` + options.name + `)) 47 | }` 48 | 49 | //fmt.Printf("%s",content) 50 | dir, _ := os.Getwd() 51 | if options.path == "" { 52 | options.path = "/models" 53 | } 54 | path := dir + options.path + `/` + options.name + ".go" 55 | 56 | 57 | outputFile, outputError := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) 58 | if outputError != nil { 59 | fmt.Printf("An error occurred with file opening or creation\n") 60 | return 61 | } 62 | defer outputFile.Close() 63 | 64 | outputWriter := bufio.NewWriter(outputFile) 65 | outputWriter.WriteString(content) 66 | outputWriter.Flush() 67 | 68 | } 69 | -------------------------------------------------------------------------------- /column.go: -------------------------------------------------------------------------------- 1 | package gii 2 | 3 | import ( 4 | "database/sql" 5 | _ "github.com/go-sql-driver/mysql" 6 | "strings" 7 | ) 8 | 9 | type column struct { 10 | name string 11 | value string 12 | } 13 | 14 | func Column(soure,table,path string){ 15 | 16 | //db, err := sql.Open("mysql", "root:2014gaokao@tcp(172.16.230.140)/abc") 17 | db, err := sql.Open("mysql", soure) 18 | 19 | if err != nil { 20 | panic(err.Error()) 21 | } 22 | defer db.Close() 23 | 24 | result, err := db.Query("select * from "+table+" limit 1") 25 | 26 | if err != nil { 27 | panic(err.Error()) 28 | } 29 | 30 | types, _ := result.ColumnTypes() 31 | 32 | columnArr := []column{} 33 | packet := make(map[string]string) 34 | for _ ,v:= range types { 35 | 36 | name := v.Name()//字段名称 37 | typeName := v.DatabaseTypeName()//字段类型 38 | typeName = strings.ToLower(typeName) 39 | 40 | if typeName == "datetime" { 41 | if name == "created" || name == "updated" { 42 | typeName = `time.Time ` + "`orm:\"auto_now_add;type(datetime)\"`" 43 | }else if name == "Updated" { 44 | typeName = `time.Time ` + "`orm:\"auto_now;type(datetime)\"`" 45 | }else { 46 | typeName = `time.Time ` + "`orm:\"type(datetime)\"`" 47 | } 48 | packet["time"] = "time" 49 | }else if typeName == "varchar" || typeName == "char" { 50 | typeName = "string" 51 | }else if typeName == "text" || typeName == "longtext" { 52 | typeName = `string ` + "`orm:\"type(text)\"`" 53 | }else if typeName == "decimal" { 54 | typeName = "float64" 55 | }else if typeName == "int" {}else { 56 | typeName = "string" 57 | } 58 | 59 | 60 | split := strings.Split(name, "_") 61 | 62 | var key string 63 | for _,item := range split{ 64 | key += strings.Title(item) 65 | } 66 | 67 | columnArr = append(columnArr,column{key,typeName}) 68 | 69 | } 70 | modelName := strings.Title(table[0:1])+table[1:] 71 | options := Options{path: "/models", column: columnArr,name:modelName,packet:packet} 72 | 73 | createModel(options) 74 | options = Options{name:table,path:path,namespace:path} 75 | createController(options) 76 | } 77 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | ## Gii beego 自动化代码生成 2 | 3 | #### 1.介绍 4 | Gii 是一个为了协助快速开发 beego 项目而创建的项目,通过 Gii 您可以很容易地为你已存在的数据表在你指定的目录创建 Model 以及 Controller 。它基于 beego 为你写好created ,update,put,已及 delete 等操作方法。 5 | > 注意不能完全依靠 Gii 为你生成的东西,你需要检查一下再进行使用。 6 | 7 | #### 2.安装 8 | 9 | 您可以通过如下的方式安装 bee 工具: 10 | 11 | ``` 12 | go get github.com/1920853199/go-gii 13 | ``` 14 | #### 3.使用 15 | ``` 16 | package main 17 | 18 | import ( 19 | "github.com/1920853199/go-gii" 20 | ) 21 | 22 | func main() { 23 | 24 | source := "xxxx:xxxxxxxx@tcp(127.0.0.1)/abc" 25 | gii.Column(source,"article","") 26 | 27 | //beego.Run() 28 | } 29 | ``` 30 | 31 | 参数介绍 32 | 1. 第一个参数 source :数据库连接信息 33 | 2. 第二个参数 name 数据表名称 34 | 3. 第三个参数 controllerPath 是指定 Controller 生成的路径 35 | 36 | > 直接执行这个文件后会在 beego 项目的目录的 models下生成对应数据表的 model,在 controller 下的指定路径生成控制器 37 | 38 | 结果: 39 | 40 | ![](http://117.50.7.147:8888/static/uploads/2019091715571981.png) 41 | 42 | Controller ```article.go```代码 43 | 44 | ``` 45 | package home 46 | 47 | import ( 48 | "github.com/astaxie/beego" 49 | "github.com/astaxie/beego/orm" 50 | "github.com/astaxie/beego/validation" 51 | ) 52 | 53 | type ArticleController struct { 54 | beego.Controller 55 | } 56 | 57 | func (c *ArticleController) List() { 58 | 59 | 60 | limit, _ := beego.AppConfig.Int64("limit") // 一页的数量 61 | page, _ := c.GetInt64("page", 1) // 页数 62 | offset := (page - 1) * limit // 偏移量 63 | 64 | o := orm.NewOrm() 65 | obj := new(models.Article) 66 | 67 | var data []*models.Article 68 | qs := o.QueryTable(obj) 69 | 70 | // 获取数据 71 | _, err := qs.OrderBy("-id").Limit(limit).Offset(offset).All(&data) 72 | if err != nil { 73 | c.Abort("404") 74 | } 75 | 76 | 77 | /*c.Data["json"]= &data 78 | c.ServeJSON() 79 | c.StopRun()*/ 80 | 81 | 82 | // 统计 83 | count, err := qs.Count() 84 | if err != nil { 85 | c.Abort("404") 86 | } 87 | 88 | c.Data["Data"] = &data 89 | c.Data["Count"] = count 90 | c.Data["Limit"] = limit 91 | c.Data["Page"] = page 92 | } 93 | 94 | func (c *ArticleController) Put() { 95 | id, err := c.GetInt("id", 0) 96 | 97 | if id == 0 { 98 | c.Abort("404") 99 | } 100 | 101 | // 基础数据 102 | o := orm.NewOrm() 103 | obj := new(models.Article) 104 | var data []*models.Article 105 | qs := o.QueryTable(obj) 106 | err = qs.Filter("id", id).One(&data) 107 | if err != nil { 108 | c.Abort("404") 109 | } 110 | c.Data["Data"] = data[0] 111 | 112 | } 113 | 114 | func (c *ArticleController) Update() { 115 | 116 | id, _ := c.GetInt("id", 0) 117 | 118 | 119 | /*c.Data["json"] = c.Input() 120 | c.ServeJSON() 121 | c.StopRun()*/ 122 | 123 | response := make(map[string]interface{}) 124 | 125 | o := orm.NewOrm() 126 | 127 | obj := models.Article{Id: id} 128 | if o.Read(&obj) == nil { 129 | // 需要补充修改的信息 130 | // 如 :obj.Reply = reply 131 | 132 | valid := validation.Validation{} 133 | 134 | // 补充需要验证的信息 135 | // 如:valid.Required(message.Reply, "Reply") 136 | 137 | if valid.HasErrors() { 138 | // 如果有错误信息 139 | -------------------------------------------------------------------------------- /controller.go: -------------------------------------------------------------------------------- 1 | package gii 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | func createController(op Options) { 11 | 12 | op.name = strings.Title(op.name) 13 | content := `package ` 14 | if op.namespace == ""{ 15 | content += `controllers` 16 | }else{ 17 | content += op.namespace 18 | } 19 | 20 | if op.modelsNamespace == "" { 21 | op.modelsNamespace = "models" 22 | } 23 | controllerName := op.modelsNamespace+`.`+op.name 24 | 25 | 26 | 27 | content +=` 28 | 29 | import ( 30 | "github.com/astaxie/beego" 31 | "github.com/astaxie/beego/orm" 32 | "github.com/astaxie/beego/validation" 33 | ) 34 | 35 | type `+op.name+`Controller struct { 36 | beego.Controller 37 | } 38 | 39 | func (c *`+op.name+`Controller) List() { 40 | 41 | 42 | limit, _ := beego.AppConfig.Int64("limit") // 一页的数量 43 | page, _ := c.GetInt64("page", 1) // 页数 44 | offset := (page - 1) * limit // 偏移量 45 | 46 | o := orm.NewOrm() 47 | obj := new(`+controllerName+`) 48 | 49 | var data []*`+controllerName+` 50 | qs := o.QueryTable(obj) 51 | 52 | // 获取数据 53 | _, err := qs.OrderBy("-id").Limit(limit).Offset(offset).All(&data) 54 | if err != nil { 55 | c.Abort("404") 56 | } 57 | 58 | 59 | /*c.Data["json"]= &data 60 | c.ServeJSON() 61 | c.StopRun()*/ 62 | 63 | 64 | // 统计 65 | count, err := qs.Count() 66 | if err != nil { 67 | c.Abort("404") 68 | } 69 | 70 | c.Data["Data"] = &data 71 | c.Data["Count"] = count 72 | c.Data["Limit"] = limit 73 | c.Data["Page"] = page 74 | } 75 | 76 | func (c *`+op.name+`Controller) Put() { 77 | id, err := c.GetInt("id", 0) 78 | 79 | if id == 0 { 80 | c.Abort("404") 81 | } 82 | 83 | // 基础数据 84 | o := orm.NewOrm() 85 | obj := new(`+controllerName+`) 86 | var data []*`+controllerName+` 87 | qs := o.QueryTable(obj) 88 | err = qs.Filter("id", id).One(&data) 89 | if err != nil { 90 | c.Abort("404") 91 | } 92 | c.Data["Data"] = data[0] 93 | 94 | } 95 | 96 | func (c *`+op.name+`Controller) Update() { 97 | 98 | id, _ := c.GetInt("id", 0) 99 | 100 | 101 | /*c.Data["json"] = c.Input() 102 | c.ServeJSON() 103 | c.StopRun()*/ 104 | 105 | response := make(map[string]interface{}) 106 | 107 | o := orm.NewOrm() 108 | 109 | obj := `+controllerName+`{Id: id} 110 | if o.Read(&obj) == nil { 111 | // 需要补充修改的信息 112 | // 如 :obj.Reply = reply 113 | 114 | valid := validation.Validation{} 115 | 116 | // 补充需要验证的信息 117 | // 如:valid.Required(message.Reply, "Reply") 118 | 119 | if valid.HasErrors() { 120 | // 如果有错误信息,证明验证没通过 121 | // 打印错误信息 122 | for _, err := range valid.Errors { 123 | //log.Println(err.Key, err.Message) 124 | response["msg"] = "新增失败!" 125 | response["code"] = 500 126 | response["err"] = err.Key + " " + err.Message 127 | c.Data["json"] = response 128 | c.ServeJSON() 129 | c.StopRun() 130 | } 131 | } 132 | 133 | if _, err := o.Update(&obj); err == nil { 134 | response["msg"] = "修改成功!" 135 | response["code"] = 200 136 | response["id"] = id 137 | } else { 138 | response["msg"] = "修改失败!" 139 | response["code"] = 500 140 | response["err"] = err.Error() 141 | } 142 | } else { 143 | response["msg"] = "修改失败!" 144 | response["code"] = 500 145 | response["err"] = "ID 不能为空!" 146 | } 147 | 148 | c.Data["json"] = response 149 | c.ServeJSON() 150 | c.StopRun() 151 | } 152 | 153 | func (c *`+op.name+`Controller) Delete() { 154 | id, _ := c.GetInt("id", 0) 155 | 156 | response := make(map[string]interface{}) 157 | 158 | o := orm.NewOrm() 159 | obj := `+controllerName+`{Id: id} 160 | 161 | if _, err := o.Delete(&obj); err == nil { 162 | response["msg"] = "删除成功!" 163 | response["code"] = 200 164 | }else{ 165 | response["msg"] = "删除失败!" 166 | response["code"] = 500 167 | response["err"] = err.Error() 168 | } 169 | 170 | c.Data["json"] = response 171 | c.ServeJSON() 172 | c.StopRun() 173 | }` 174 | 175 | 176 | dir, _ := os.Getwd() 177 | if op.path == "" { 178 | op.path = "/controllers" 179 | }else{ 180 | op.path = "/controllers/" + op.path 181 | 182 | if _, err := os.Stat(dir + op.path); os.IsNotExist(err) { 183 | err := os.MkdirAll(dir +op.path, 0711) 184 | if err != nil { 185 | return 186 | } 187 | } 188 | 189 | // check again 190 | if _, err := os.Stat(dir + op.path); os.IsNotExist(err) { 191 | return 192 | } 193 | 194 | } 195 | path := dir + op.path + `/` + strings.ToLower(op.name) + ".go" 196 | 197 | 198 | outputFile, outputError := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) 199 | if outputError != nil { 200 | fmt.Printf("An error occurred with file opening or creation\n") 201 | return 202 | } 203 | defer outputFile.Close() 204 | 205 | outputWriter := bufio.NewWriter(outputFile) 206 | outputWriter.WriteString(content) 207 | outputWriter.Flush() 208 | 209 | } 210 | --------------------------------------------------------------------------------