I am building a CLI to generate code for an homemade API framework (right now to generate the controller part). To do so, I am using template, but I saw that the template is generating nothing (an empty file), when I use words such as package
or func
in the template.
I want to build the following template:
package controllers
{{- range .Methods }}
{{ if eq .Name "Create" }}
func ({{ firstChar $.ModelName }}c {{ title $.ModelName }}Controller) Get{{ title $.ModelName }}(c *gin.Context) {
{{ $.ModelName }}, err := store.Find{{ title $.ModelName }}ById(c, c.Param("id"))
if err != nil {
c.AbortWithError(http.StatusNotFound, helpers.ErrorWithCode("{{ $.ModelName }}_not_found", "The {{ $.ModelName }} does not exist", err))
return
}
c.JSON(http.StatusOK, {{ $.ModelName }})
}
{{ else if eq .Name "Get" }}
{{ else if eq .Name "GetAll" }}
{{ else if eq .Name "Update" }}
{{ else if eq .Name "Delete" }}
{{ end }}
{{- end }}
Do you have any idea of how to make template working?
It's now working, I just add template.Must
before template.New
and it's now working like a charm.
path := filepath.Join("templates", "controller.tmpl")
body, _ := ioutil.ReadFile(path)
tmpl := template.Must(template.New("model").Funcs(funcMap).Parse(string(body)))
var buf bytes.Buffer
err := tmpl.Execute(&buf, selectedMethods)
utils.Check(err)
src, _ := format.Source(buf.Bytes())