optionGen is a tool to generate go Struct option for test, mock or more flexible.
go get -u github.com/xsam/optionGen/cmd/optionGenoptionGen require goimports to format code which is generated. So you may confirm that goimports has been installed
go get golang.org/x/tools/cmd/goimportsTo generate struct option, you need write a function declaration to tell optionGen how to generate. function Name consists of "_" prefix, struct name and "OptionDeclaration" suffix. In this function, just return a variable which type is map[string]interface{}.
The key of the map means option name, and the value of the map should consist of two parts, one for option type(except func type), and the other option default value.
Looks like this:
"sounds": string("Meow")
"food": (*string)(nil)
// function type is special"Walk": func() {
log.Println("Walking")
}A Cat struct option declaration may like this:
func_CatOptionDeclaration() interface{} {
returnmap[string]interface{}{
"sounds": string("Meow"),
}
}Once you finished you declaration. You can add this line in your code
//go:generate optionGenand use go generate command to generate option.
Here is the sample result generate by optionGen
package main
import"log"typeCatOptionsstruct {
soundsstring
}
typeCatOpfunc(option*CatOptions)
funcCatOpWith_sounds(valuestring) CatOp { returnfunc(option*CatOptions) { option.sounds=value } }
func_NewCatOptions() CatOptions {
returnCatOptions{
sounds: "Meow",
}
}To use the generated code. you could add Options struct to your struct
typeCatstruct {
optionsCatOptions
}And write a new function
funcNewCat(option...CatOp) *Cat {
cat:=Cat{
options: _NewCatOptions(),
}
for_, op:=rangeoption {
op(&cat.options)
}
return&cat
}For more example. see the example folder
Enjoy!