Просмотр исходного кода

改用模板引擎生成代码

gujiheimao 2 лет назад
Родитель
Сommit
16b8098806
3 измененных файлов с 42 добавлено и 1 удалено
  1. 3 0
      README.md
  2. 22 1
      main.go
  3. 17 0
      tmpl/sturct.go.template

+ 3 - 0
README.md

@@ -0,0 +1,3 @@
+# 模板
+
+`学习路径:https://zhuanlan.zhihu.com/p/688336009`

+ 22 - 1
main.go

@@ -1,8 +1,11 @@
 package main
 
 import (
+	"bufio"
 	"go-create/configs"
 	"go-create/util"
+	"html/template"
+	"os"
 )
 
 func init() {
@@ -16,6 +19,24 @@ func main() {
 	//util.MysqlToDao()
 	//util.MysqlToBaseCRUDRouter()
 	//执行生成,vue
-	util.MysqlToVueApi()
+	//util.MysqlToVueApi()
+	LoadStructTemplate("E:\\project\\kkc\\go-xorm-create\\domain\\DoMain.go")
+}
+
+// LoadStructTemplate 加载结构体生成模板
+func LoadStructTemplate(url string) {
+	os.Truncate(url, 0)
+	file, _ := os.OpenFile(url, os.O_CREATE|os.O_RDWR, 0666)
+	defer file.Close()
+
+	writer := bufio.NewWriter(file)
 
+	tmpl, err := template.ParseFiles("./tmpl/sturct.go.template")
+	if err != nil {
+		panic(err)
+	}
+	err = tmpl.Execute(writer, util.MTables)
+	if err != nil {
+		panic(err)
+	}
 }

+ 17 - 0
tmpl/sturct.go.template

@@ -0,0 +1,17 @@
+package domain
+
+import (
+    "fmt"
+    "time"
+)
+{{range .}}
+// {{.AaBbName}} {{.Comment}}
+type {{.AaBbName}} struct {
+{{range .MColumns}}    {{.AaBbName}} {{.TypeName}} `{{if eq .IsKey false}}xorm:"{{.Name}}"{{end}} json:"{{.AaBbName}}"`
+{{end}}}
+
+func (receiver {{.AaBbName}}) String() string {
+	return fmt.Sprint("{{.AaBbName}}{", {{range .MColumns}}"{{.AaBbName}}:", receiver.{{.AaBbName}},{{end}} "}")
+}
+
+{{end}}