everyone!
My task is to parse command-line argument and fill struct fields. And my function must works with all kinds of arguments - they'll describe in struct tag.
For example:
type CommndLineArguments struct {
Configfile string `required:"false" name:"config" default:"/etc/daemon.conf" description:"Config file"`
Daemon bool `required:"true" name:"daemon" default:"false" description:"Run as daemon"`
}
I use reflect
and flag
packages. Like this:
func GetArguments(variable interface{}) error {
//Check is this a pointer to struct
variableType := reflect.TypeOf(variable)
if variableType.Kind() != reflect.Ptr {
return errors.New(ERR_PASS_BY_VALUE)
} else if variableValue := variableType.Elem(); variableValue.Kind() != reflect.Struct {
return errors.New(ERR_NOT_A_STRUCT)
}
// Parse parameters
variableValue := variableType.Elem()
for i := 0; i < variableValue.NumField(); i++ {
structField := variableValue.Field(i)
fieldName := structField.Name
fieldType := structField.Type
fieldTag := structField.Tag
Now I'm ready to parse arguments.
switch fieldType.Kind() {
case reflect.Bool:
defaultValue, err := strconv.ParseBool(fieldTag.Get("default"))
if err != nil {
return errors.New(ERR_PARSE_ERROR + err.Error())
}
flag.BoolVar(&structField, fieldName, defaultValue, fieldTag.Get("description"))
But I get an error in last line.
./parser.go:42: cannot use &structField (type *reflect.StructField) as type *bool in function argument
My question is how can I set this field correctly?