func (r *Row) Bind(x interface{}, strategy map[string]string) error { for src, dest := range strategy { data, ok := r.data[src] if ok { k, err := reflections.GetFieldKind(x, dest) if err != nil { return err } switch k { case reflect.String: { reflections.SetField(x, dest, data) } case reflect.Int64: { i, err := strconv.ParseInt(data, 10, 64) if err != nil { return err } reflections.SetField(x, dest, i) } case reflect.Ptr: { value, err := reflections.GetField(x, dest) if err != nil { return err } if reflect.TypeOf(value) == typeDec { dec, success := new(inf.Dec).SetString(data) if !success { fmt.Errorf("Could not parse inf.Dec: %s", data) } reflections.SetField(x, dest, dec) } } case reflect.Struct: { value, err := reflections.GetField(x, dest) if err != nil { return err } if reflect.TypeOf(value) == typeTime { date, err := time.ParseInLocation("2006-01-02 15:04:05", data, r.opts.TimeZone) if err != nil { return err } reflections.SetField(x, dest, date) } } } } } return nil }
func (this *CCMomentHandler) LoadModel(moment models.CCMoment) models.Moment { fields, _ := reflections.Fields(&models.Moment{}) //new instance momentModel := models.Moment{} for i := 0; i < len(fields); i++ { has, _ := reflections.HasField(moment, fields[i]) if has == true { fmt.Println("Field Exist------", fields[i]) if fields[i] == "Volunteer_id" { fmt.Println("Volunteer_id Exist------") var userObj CCUserHandler var volunteerObj CCVolunteerHandler var usermodel models.CCUser var volunteerModel models.CCVolunteer value, err := reflections.GetField(moment, fields[i]) if err == nil && value != nil { str, _ := value.(string) volunteerModel, err = volunteerObj.FetchVolunteerForId(str) if err == nil { fmt.Println("volunteer Exist------", volunteerModel) usermodel, err = userObj.FetchUserById(volunteerModel.User_id) fmt.Println("User Exist------", usermodel) if err == nil { responseModel := userObj.LoadModel(usermodel) setError := reflections.SetField(&momentModel, fields[i], responseModel) // err != nil if setError != nil { panic(setError) } } } } } else { value, err := reflections.GetField(moment, fields[i]) if err == nil { fmt.Println("Field Value------", value) setError := reflections.SetField(&momentModel, fields[i], value) // err != nil if setError != nil { panic(setError) } } } } } fmt.Println("Data set to Model --- ", momentModel) return momentModel }
func (this *CCUserHandler) LoadModel(user models.CCUser) models.User { fields, _ := reflections.Fields(&models.User{}) //new instance userModel := models.User{} for i := 0; i < len(fields); i++ { has, _ := reflections.HasField(user, fields[i]) if has == true { fmt.Println("Field Exist------", fields[i]) value, err := reflections.GetField(user, fields[i]) if err == nil { fmt.Println("Field Value------", value) setError := reflections.SetField(&userModel, fields[i], value) // err != nil if setError != nil { panic(setError) } } } } fmt.Println("Data set to Model --- ", userModel) return userModel }
func (this *CCEventHandler) LoadModel(event models.CCEvent) models.Event { fields, _ := reflections.Fields(&models.Event{}) //new instance eventModel := models.Event{} for i := 0; i < len(fields); i++ { has, _ := reflections.HasField(event, fields[i]) if has == true { fmt.Println("Field Exist------", fields[i]) if fields[i] == "Created_by" { var userObj CCUserHandler var usermodel models.CCUser value, err := reflections.GetField(event, fields[i]) if err == nil && value != nil { str, _ := value.(string) usermodel, err = userObj.FetchUserById(str) if err == nil { responseModel := userObj.LoadModel(usermodel) setError := reflections.SetField(&eventModel, fields[i], responseModel) // err != nil if setError != nil { panic(setError) } } } } else { value, err := reflections.GetField(event, fields[i]) if err == nil { fmt.Println("Field Value------", value) setError := reflections.SetField(&eventModel, fields[i], value) // err != nil if setError != nil { panic(setError) } } } } } fmt.Println("Data set to Model --- ", eventModel) return eventModel }
func (D *DayOfWeekCalls) PopulateHoursByDays(results []HourByDaysRecord) { for i := 0; i < len(results); i++ { hourName := fmt.Sprintf("H%d", i) dayName := fmt.Sprintf("Day%d", D.DayOfWeek-1) valueHour, _ := reflections.GetField(D.SummaryCallsPerHours, hourName) _ = reflections.SetField(&results[i], dayName, valueHour) } }
func ExampleSetField() { s := MyStruct{ FirstField: "first value", SecondField: 2, ThirdField: "third value", } // In order to be able to set the structure's values, // a pointer to it has to be passed to it. err := reflections.SetField(&s, "FirstField", "new value") if err != nil { log.Fatal(err) } // If you try to set a field's value using the wrong type, // an error will be returned err = reflections.SetField(&s, "FirstField", 123) // err != nil if err != nil { log.Fatal(err) } }
func hookDisableWebpage(payload interface{}, nv *bool) { if nv != nil { has, _ := reflections.HasField(payload, "DisableWebPagePreview") if has { value, _ := reflections.GetField(payload, "DisableWebPagePreview") bvalue := value.(*bool) if bvalue == nil { reflections.SetField(payload, "DisableWebPagePreview", nv) } } } }
func hookReplyToMessageID(payload interface{}, nv *bool) { if nv != nil { has, _ := reflections.HasField(payload, "ReplyToMessageID") if has { value, _ := reflections.GetField(payload, "ReplyToMessageID") bvalue := value.(*int) if bvalue == nil { reflections.SetField(payload, "ReplyToMessageID", nv) } } } }
func hookSelective(payload interface{}, nv *bool) { if nv != nil { has, _ := reflections.HasField(payload, "Selective") if has { value, _ := reflections.GetField(payload, "Selective") bvalue := value.(*bool) if bvalue == nil { reflections.SetField(payload, "Selective", nv) } } } }
func hookOneTimeKeyboard(payload interface{}, nv *bool) { if nv != nil { has, _ := reflections.HasField(payload, "OneTimeKeyboard") if has { value, _ := reflections.GetField(payload, "OneTimeKeyboard") bvalue := value.(*bool) if bvalue == nil { reflections.SetField(payload, "OneTimeKeyboard", nv) } } } }
// HandleStructField sets the value for the given supported struct field. func (dc *DeepCopier) HandleStructField(options *FieldOptions) error { f, err := reflections.GetField(dc.Source, options.SourceField) if err != nil { return err } switch v := f.(type) { case pq.NullTime: if v.Valid { if err := reflections.SetField(dc.Destination, options.DestinationField, &v.Time); err != nil { return err } } case time.Time: if err := reflections.SetField(dc.Destination, options.DestinationField, v); err != nil { return err } } return nil }
func (s *UserStore) UpdateUser(user *User, changes map[string]interface{}) (err error) { u := s.ByName(user.Username) u.mux.Lock() for k, v := range changes { err = reflections.SetField(u, k, v) } u.mux.Unlock() if err != nil { return err } s.save() return nil }
func setProperty(obj interface{}, prop string, val interface{}) error { if reflect.TypeOf(obj).Kind() == reflect.Map { value := reflect.ValueOf(obj) value.SetMapIndex(reflect.ValueOf(prop), reflect.ValueOf(val)) return nil } if reflect.TypeOf(obj).Kind() != reflect.Ptr { return errors.New("Object must be a pointer to a struct") } prop = strings.Title(prop) return reflections.SetField(obj, prop, val) }
// OverrideWith will override the Environment values // according to a provided key-value map. func (e *Environment) OverrideWith(data map[string]string) error { for field, value := range data { has, err := reflections.HasField(*e, field) if !has { errMsg := fmt.Sprintf("No such field %s in Environement struct", field) return errors.New(errMsg) } else if err != nil { return err } if value != "" { reflections.SetField(e, field, value) } } return nil }
func (d *Dsn) SetDefaults(defaults map[string]string) error { for k, v := range defaults { // Check the dsn struct has field value, err := reflections.GetField(d, k) if err != nil { return err } // If dsn instance field is set to zero value, // then override it with provided default value if value == "" { err := reflections.SetField(d, k, v) if err != nil { return err } } } return nil }
// Load method will try to load Environment struct // tagged fields value from system environement. Every // found values will override Environment field current // value. func (e *Environment) Load() error { var err error var envTags map[string]string envTags, err = reflections.Tags(*e, "env") if err != nil { return err } for field, tag := range envTags { envVar := os.Getenv(tag) if envVar != "" { err = reflections.SetField(e, field, envVar) if err != nil { return err } } } return nil }
func (l Loader) normalizeField(fieldName string, normalization string) error { if normalization == "filepath" { value, _ := reflections.GetField(l.Config, fieldName) fieldKind, _ := reflections.GetFieldKind(l.Config, fieldName) // Make sure we're normalizing a string filed if fieldKind != reflect.String { return fmt.Errorf("filepath normalization only works on string fields") } // Normalize the field to be a filepath if valueAsString, ok := value.(string); ok { normalizedPath := NormalizeFilePath(valueAsString) if err := reflections.SetField(l.Config, fieldName, normalizedPath); err != nil { return err } } } else { return fmt.Errorf("Unknown normalization `%s`", normalization) } return nil }
// Unmarshal parses a csv file and stores its value to a list of entpoint structs func (m *Marshaler) Unmarshal() ([]interface{}, error) { structs := *new([]interface{}) line := 0 for { line++ var record stringSlice record, err := m.Reader.Read() if err != nil { if err == io.EOF { break } if !m.Lazy { return nil, err } if pe, ok := err.(*csv.ParseError); ok { m.errors = append(m.errors, *pe) } continue } if line == 1 { // first line contains header information for i, fieldInfo := range m.fieldInfos { index := record.pos(fieldInfo.headerName) if index >= 0 { m.fieldInfos[i].position = index } } if !m.fieldInfos.isComplete() { return nil, &csv.ParseError{Err: ErrHeaderNotComplete} } continue } sPtr := reflect.New(reflect.TypeOf(m.endPointStruct)).Interface() var ( value interface{} rerr error ) for _, fieldInfo := range m.fieldInfos { switch fieldInfo.kind { case reflect.Bool: value, rerr = strconv.ParseBool(record[fieldInfo.position]) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value, rerr = strconv.Atoi(record[fieldInfo.position]) case reflect.Float32, reflect.Float64: value, rerr = strconv.ParseFloat(record[fieldInfo.position], 64) case reflect.String: value = record[fieldInfo.position] default: rerr = ErrUnsupportedCSVType } if rerr != nil { m.errors = append(m.errors, csv.ParseError{ Column: fieldInfo.position, Line: line, Err: rerr, }) break } reflections.SetField(sPtr, fieldInfo.fieldName, value) } // add value only if error is nil if rerr == nil { v := reflect.ValueOf(sPtr).Elem().Interface() structs = append(structs, v) } } if len(m.errors) == 0 { return structs, nil } return structs, m.errors }
func (l Loader) setFieldValueFromCLI(fieldName string, cliName string) error { // Get the kind of field we need to set fieldKind, err := reflections.GetFieldKind(l.Config, fieldName) if err != nil { return fmt.Errorf(`Failed to get the type of struct field %s`, fieldName) } var value interface{} // See the if the cli option is using the special format i.e. (arg:1) special := CLISpecialNameRegex.FindStringSubmatch(cliName) if len(special) == 3 { // Should this cli option be loaded from the CLI arguments? if special[1] == "arg" { // Convert the arg position to an integer i, err := strconv.Atoi(special[2]) if err != nil { return fmt.Errorf("Failed to convert string to int: %s", err) } // Only set the value if the args are long enough for // the position to exist. if len(l.CLI.Args()) > i { // Get the value from the args value = l.CLI.Args()[i] } } } else { // If the cli name didn't have the special format, then we need to // either load from the context's flags, or from a config file. // We start by defaulting the value to what ever was provided // by the configuration file if l.File != nil { if configFileValue, ok := l.File.Config[cliName]; ok { // Convert the config file value to it's correct type if fieldKind == reflect.String { value = configFileValue } else if fieldKind == reflect.Slice { value = strings.Split(configFileValue, ",") } else if fieldKind == reflect.Bool { value, _ = strconv.ParseBool(configFileValue) } else { return fmt.Errorf("Unable to convert string to type %s", fieldKind) } } } // If a value hasn't been found in a config file, but there // _is_ one provided by the CLI context, then use that. if value == nil || l.cliValueIsSet(cliName) { if fieldKind == reflect.String { value = l.CLI.String(cliName) } else if fieldKind == reflect.Slice { value = l.CLI.StringSlice(cliName) } else if fieldKind == reflect.Bool { value = l.CLI.Bool(cliName) } else { return fmt.Errorf("Unable to handle type: %s", fieldKind) } } } // Set the value to the cfg if value != nil { err = reflections.SetField(l.Config, fieldName, value) if err != nil { return fmt.Errorf("Could not set value `%s` to field `%s` (%s)", value, fieldName, err) } } return nil }
// Reflects on the values in the commandLineOptions structure, and fills it // with values either from the command line, or from the ENV. func parseArgs(opts *commandLineOptions, args []string) { // Create a flag set for args flags := flag.NewFlagSet(commandLineName, flag.ExitOnError) // Get the fields for the strucutre fields, _ := reflections.Fields(opts) // Loop through each field of the structure, and define a flag for it for i := 0; i < len(fields); i++ { fieldName := fields[i] flagName, _ := reflections.GetFieldTag(opts, fieldName, "flag") fieldKind, _ := reflections.GetFieldKind(opts, fieldName) if fieldKind == reflect.String { flags.String(flagName, "", "") } else if fieldKind == reflect.Bool { flags.Bool(flagName, false, "") } else { exitAndError(fmt.Sprintf("Could not create flag for %s", fieldName)) } } // Define our custom usage text flags.Usage = func() { fmt.Printf("%s\n", commandLineUsage) } // Search the args until we find a "--", which signifies the user has started // defining options. var argumentFlags []string started := false for i := 0; i < len(args); i++ { if strings.HasPrefix(args[i], "--") { started = true } if started { argumentFlags = append(argumentFlags, args[i]) } } // Now parse the flags flags.Parse(argumentFlags) // Now the flag set has been populated with values, retrieve them and // set them (or use the ENV variable if empty) for i := 0; i < len(fields); i++ { fieldName := fields[i] fieldKind, _ := reflections.GetFieldKind(opts, fieldName) // Grab the flags we need flagName, _ := reflections.GetFieldTag(opts, fieldName, "flag") envName, _ := reflections.GetFieldTag(opts, fieldName, "env") required, _ := reflections.GetFieldTag(opts, fieldName, "required") // Grab the value from the flag value := flags.Lookup(flagName).Value.String() // If the value of the flag is empty, try the ENV if value == "" { value = os.Getenv(envName) } // Do validation if required == "true" && value == "" { exitAndError(fmt.Sprintf("missing %s", flagName)) } // Set the value in the right way if fieldKind == reflect.String { reflections.SetField(opts, fieldName, value) } else if fieldKind == reflect.Bool { // The bool is converted to a string above if value == "true" { reflections.SetField(opts, fieldName, true) } else { reflections.SetField(opts, fieldName, false) } } else { exitAndError(fmt.Sprintf("Could not set value of %s", fieldName)) } } }
// SetFieldValue Sets the given value to the given field. func (dc *DeepCopier) SetFieldValue(entity interface{}, name string, value reflect.Value) error { kind := value.Kind() // Maps if kind == reflect.Map { switch v := value.Interface().(type) { case map[string]interface{}, map[string]string, map[string]map[string]string, map[string]map[string]map[string]string: if err := reflections.SetField(entity, name, v); err != nil { return err } return nil } } // Structs if kind == reflect.Struct { switch v := value.Interface().(type) { case time.Time, pq.NullTime: if err := reflections.SetField(entity, name, v); err != nil { return err } return nil } } // Reflect switch kind { case reflect.Int8: if err := reflections.SetField(entity, name, int8(value.Int())); err != nil { return err } return nil case reflect.Int16: if err := reflections.SetField(entity, name, int16(value.Int())); err != nil { return err } return nil case reflect.Int32: if err := reflections.SetField(entity, name, int32(value.Int())); err != nil { return err } return nil case reflect.Int64: if err := reflections.SetField(entity, name, value.Int()); err != nil { return err } return nil case reflect.Int: if err := reflections.SetField(entity, name, int(value.Int())); err != nil { return err } return nil case reflect.Uint8: if err := reflections.SetField(entity, name, uint8(value.Uint())); err != nil { return err } return nil case reflect.Uint16: if err := reflections.SetField(entity, name, uint16(value.Uint())); err != nil { return err } return nil case reflect.Uint32: if err := reflections.SetField(entity, name, uint32(value.Uint())); err != nil { return err } return nil case reflect.Uint64: if err := reflections.SetField(entity, name, value.Uint()); err != nil { return err } return nil case reflect.Uint: if err := reflections.SetField(entity, name, uint(value.Uint())); err != nil { return err } return nil case reflect.Float32: if err := reflections.SetField(entity, name, float32(value.Float())); err != nil { return err } return nil case reflect.Float64: if err := reflections.SetField(entity, name, value.Float()); err != nil { return err } return nil case reflect.String: if err := reflections.SetField(entity, name, value.String()); err != nil { return err } return nil case reflect.Bool: if err := reflections.SetField(entity, name, value.Bool()); err != nil { return err } return nil } return nil }