Sugar for go generate
.
Reads yml data from .go source file and render template with variables.
- Install:
go install github.com/tada-team/bang
- Write line
//go:generate bang $GOFILE:$GOLINE
, and//
-commented yaml content below:
package mypackage
//go:generate bang $GOFILE:$GOLINE
//
// ...yaml...
//
Yaml format is:
template: <go template contents>
vars: <variables for template>
dest: <filename for saving rendered template>
- run
go generate
Template will be rendered and code wil be formatted.
package main
//go:generate bang $GOFILE:$GOLINE
// dest: main_generated.go
// vars:
// package: main
// types:
// - int
// - float64
// template: >
// package {{ .package }}
//
// {{ range $type := .types }}
// func {{ $type }}Sum(a, b {{ $type }}) {{ $type }} {
// return a + b
// }
// {{ end }}
//
Result (main_generated.go
):
// Code generated by Bang.go DO NOT EDIT.
package main
func intSum(a, b int) int {
return a + b
}
func float64Sum(a, b float64) float64 {
return a + b
}
-dest
argument overridesdest
key in yaml-template
argument takestemplate
from given template file-vars
argument takesvars
from given yaml file-verbose
argument adds more output
Example:
package main
//go:generate bang -verbose -dest=main_generated.go -template=main.tpl $GOFILE:$GOLINE
vars.tpl
:
package: main
types:
- int
- float64
main.tpl
:
package {{ .package }}
{{ range $type := .types }}
func {{ $type }}Sum(a, b {{ $type }}) {{ $type }} {
return a + b
}
{{ end }}