github.com/tobgu/qframe@v0.4.0/internal/template/generate.go (about) 1 package template 2 3 import ( 4 "bytes" 5 "io" 6 "text/template" 7 ) 8 9 const HeaderTemplate = ` 10 package {{.pkgName}} 11 12 {{if .imports}} 13 import ( 14 {{ range $_, $imp := .imports }} 15 "{{$imp}}"{{ end }} 16 ) 17 {{end}} 18 19 // Code generated from template/... DO NOT EDIT 20 ` 21 22 type Spec struct { 23 Name string 24 Template string 25 Values map[string]interface{} 26 } 27 28 func render(name, templateStr string, templateData interface{}, dst io.Writer) error { 29 t := template.New(name) 30 t, err := t.Parse(templateStr) 31 if err != nil { 32 return err 33 } 34 35 err = t.Execute(dst, templateData) 36 if err != nil { 37 return err 38 } 39 40 return nil 41 } 42 43 func Generate(pkgName string, specs []Spec, imports []string) (*bytes.Buffer, error) { 44 var buf bytes.Buffer 45 values := map[string]interface{}{"pkgName": pkgName, "imports": imports} 46 renderValues := append([]Spec{{Name: "header", Template: HeaderTemplate, Values: values}}, specs...) 47 for _, v := range renderValues { 48 if err := render(v.Name, v.Template, v.Values, &buf); err != nil { 49 return nil, err 50 } 51 } 52 53 return &buf, nil 54 }