togo/struct.go
jolheiser e8a896fbac
Initial commit
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2021-04-08 23:58:22 -05:00

72 lines
1.0 KiB
Go

package togo
import (
_ "embed"
"io"
"text/template"
)
var (
//go:embed struct.tmpl
tmplData string
tmpl = template.Must(template.New("struct").Parse(tmplData))
)
type format int
const (
jsonFormat format = iota
tomlFormat
yamlFormat
)
type GoStruct struct {
Structs []Struct
format format
}
func (g GoStruct) DefaultTagOptions() *TagOptions {
opts := new(TagOptions)
switch g.format {
case jsonFormat:
opts.JSON = true
case tomlFormat:
opts.TOML = true
case yamlFormat:
opts.YAML = true
}
return opts
}
type TagOptions struct {
JSON bool
YAML bool
TOML bool
}
func (p TagOptions) Tags() bool {
return p.JSON || p.YAML || p.TOML
}
func (g GoStruct) Fprint(w io.Writer, opts *TagOptions) error {
if opts == nil {
opts = g.DefaultTagOptions()
}
return tmpl.Execute(w, map[string]interface{}{
"Structs": g.Structs,
"Options": opts,
})
}
type Struct struct {
Name string
Fields []Field
}
type Field struct {
Name string
Type string
Tag string
Comment string
}