golang利用模板生成Repository Container

2021-07-22  本文已影响0人  EasyNetCN

Repository数据层一般是通过代码生成器生成的,为了在实际使用过程中,减少初始化过程,减少编码量,可以同样利用利用模板,生成RepositoryContainer,实现Repository的初始化。

直接利用测试运行

type Repository struct {
    Name string
}

type RepositoryContext struct {
    Repositories []Repository
}
func Test_GenerateRepositoryContainer(t *testing.T) {
    files, err1 := os.ReadDir("../repository")

    if err1 != nil {
        fmt.Println("parse file err:", err1)
        return
    }

    repositories := make([]Repository, 0)

    for _, file := range files {
        name := file.Name()

        if strings.HasSuffix(name, "_repository.go") {
            repositories = append(repositories, Repository{Name: UpperCamelCase(name[:len(name)-3])})
        }
    }

    if err := os.Remove("../repository/repository_container.go"); err != nil {
        fmt.Println("remove file err:", err)
        return
    }

    f, err2 := os.OpenFile("../repository/repository_container.go", os.O_CREATE|os.O_WRONLY, 0666)

    defer f.Close()

    if err2 != nil {
        fmt.Println("can not create output file,err:", err2)

        return
    }

    tpl, err3 := template.New("repository-container.tpl").ParseFiles("./repository-container.tpl")

    if err3 != nil {
        fmt.Println("parse file err:", err3)
        return
    }

    if err := tpl.Execute(f, &RepositoryContext{Repositories: repositories}); err != nil {
        fmt.Println("There was an error:", err.Error())
    }
}

func UpperCamelCase(txt string) string {
    sb := new(strings.Builder)

    strs := strings.Split(txt, "_")

    for _, str := range strs {
        sb.WriteString(strings.ToUpper(string(str[0])))
        sb.WriteString(str[1:])
    }

    return sb.String()
}

模板

package repository

import (
    "github.com/kataras/golog"
    "xorm.io/xorm"
)

type RepositoryContainer struct{
    {{range $repository := .Repositories -}}
    {{.Name}} {{.Name}} 
    {{end -}}
}

func NewRepositoryContainer(engine *xorm.Engine, logger *golog.Logger) *RepositoryContainer{
    return &RepositoryContainer{
        {{range $repository := .Repositories -}}
        {{.Name}}: New{{.Name}}(engine, logger),
        {{end -}}
    }
}
上一篇下一篇

猜你喜欢

热点阅读