Simple Workflow
Bogdan Dinu edited this page Feb 13, 2020
·
2 revisions
Having the following declaration in one of your project's packages:
//go:generate stroo -type=SimpleTestData -output=easy_gen.go -template=./../templates/simple_example.tmpl
type SimpleTestData struct {
Name string
Phone string
}
and the example.tmpl
template defined as following:
{{ if declare "Print" }}{{ end }}{{/* pass kind of methods we're going to generate */}}
{{/* the main template */}}
{{ define "Print" }}
{{- with . }}
func (st {{ .Kind }}) Print() string {
var sb strings.Builder
{{ range .Fields -}}
{{ if .IsString -}}
sb.WriteString("{{.Prefix}}{{.Name}}="+{{ if .IsPointer }}*{{ end }}st.{{.Prefix}}{{.Name}}+"\n")
{{ else }}{{/* a good practice to signal developers unhandled cases via TODO */}}
// TODO : unhandled field {{.Kind }}
{{ end }}
{{ end }}
return sb.String()
}
{{ end }}
{{ end }}
{{/* extract the selected type indicated by params */}}
{{ $main := structByKey .SelectedType }}
{{/* using with ensures that is not nil*/}}
{{- with $main -}}
{{/* we apply the defined template */}}
{{ template "Print" . }}
{{ end }}
Running go generate
in that folder will produce a file named easy_gen.go
which will look like this:
// Generated on Thu Feb 13 15:00:07 by Stroo [https://github.com/badu/stroo]
// Do NOT bother with altering it by hand : use the tool
// Arguments at the time of generation:
// -debugPrint=false -output=easy_gen.go -serve=false -target= -template=./../templates/simple_example.tmpl -testMode=false -type=SimpleTestData
func (st SimpleTestData) Print() string {
var sb strings.Builder
sb.WriteString("Name=" + st.Name + "\n")
sb.WriteString("Phone=" + st.Phone + "\n")
return sb.String()
}