automatically convert yaml, json, toml etc. file into go file with struct.
go install github.com/xylonx/config2go@latest
config2go -s ${sourceConfig} -t ${targetConfig} -p ${package} -t ${tags}
for more information, run config2go -h
.
the flow can be divided into 3 main parts:
- parser: input anything you want, and output the Node tree
type Node struct {
// inner node properties
// the tag key of the node
TagKey string
// the struct field name
FieldName string
// the node type: string, bool, int64, float64, Slice, Map and so on
Type reflect.Kind
// sort with alphabeta
Child []Node
}
type Parser interface {
ParseToNodeTree() (*Node, error)
}
the Tag key is used to generate tags while the field key is used to generate the struct Field with UpperCamel.
don't worry about it, config2go will convert camel case, snake case and kebab case into UpperCamel case😃
- define how tag works
type TagFunc func(tagKey string) (tags string)
it receive the tagKey define in Node
below, and output the whole tags (include ` symbol).
I provider 2 embedded tagFunc:
- AppendAllFields
// defined in converter package
var AppendAllFields = func(tags []string) TagFunc
// use
converter.NewConverter(parser, converter.AppendAllFields([]string{"json", "yaml"}))
it add tags for all expose struct field.
the output is like below:
Name string `json:"name" yaml:"name" `
- noopTagFunc
converter.NewConverter(parser, converter.noopTagFunc)
it add no tags for struct field.
the output is like below:
Name string ``
- new Converter and Convert
converter := converter.NewConverter(parser, <TagFunc>)
converter.Convert(<targetPackage>, <targetFile>)
now, the generated source code will write into <targetFile>
- yaml
application:
host: 0.0.0.0
port: 8080
read_timeout: 5
write_timeout: 5
users:
- username: Alice
password: p@ssw0rd
- username: Bob
password: P@ssw0rd
ids:
- A
- B
- C
- source code
/*
Code generated by config2go(https://github.com/xylonx/config2go)
DON EDIT!
*/
package config
type Setting struct {
Application struct {
Host string `mapstructure:"host" json:"host" yaml:"host" `
Port int64 `mapstructure:"port" json:"port" yaml:"port" `
ReadTimeout int64 `mapstructure:"read_timeout" json:"read_timeout" yaml:"read_timeout" `
WriteTimeout int64 `mapstructure:"write_timeout" json:"write_timeout" yaml:"write_timeout" `
} `mapstructure:"application" json:"application" yaml:"application" `
Ids []string `mapstructure:"ids" json:"ids" yaml:"ids" `
Users []struct {
Password string `mapstructure:"password" json:"password" yaml:"password" `
Username string `mapstructure:"username" json:"username" yaml:"username" `
} `mapstructure:"users" json:"users" yaml:"users" `
}