Convert setJailProperty to setStructFieldValue

This commit is contained in:
yo
2022-04-18 13:36:33 +02:00
parent 4f85f2e6ac
commit f9ce3601df
2 changed files with 48 additions and 46 deletions

View File

@ -23,7 +23,7 @@ func NewJailConfig() (JailConfig, error) {
hostid, err := ioutil.ReadFile("/etc/hostid")
if err != nil {
return err
return jc, err
} else {
hostid = []byte(strings.Replace(string(hostid), "\n", "", -1))
}
@ -157,7 +157,7 @@ func NewJailConfig() (JailConfig, error) {
jc.Writebps = "off"
jc.Writeiops = "off"
return jc
return jc, nil
}
/*****************************************************************************
@ -331,6 +331,7 @@ func getStructFieldNames(parentStruct interface{}, result []string, prefix strin
/********************************************************************************
* Recurse into structure, returning reflect.Value of wanted field.
* Nested fields are named with a dot (ex "MyStruct.MyField")
* Returns (value, field_name, error)
*******************************************************************************/
func getStructFieldValue(parentStruct interface{}, fieldName string) (*reflect.Value, string, error) {
v := reflect.ValueOf(parentStruct)
@ -431,6 +432,39 @@ func getStructField(parentStruct interface{}, fieldName string) (reflect.Value,
return v, fieldName
}
// setStructFieldValue takes a string as propValue, whatever the real property type is.
// It will be converted.
func setStructFieldValue(parentStruct interface{}, propName string, propValue string) error {
val, _, err := getStructFieldValue(parentStruct, propName)
if err != nil {
return err
}
if val.CanSet() {
switch val.Kind() {
case reflect.String:
val.SetString(propValue)
case reflect.Int:
ival, err := strconv.ParseInt(propValue, 10, 64)
if err != nil {
return err
}
val.SetInt(ival)
case reflect.Bool:
bval, err := strconv.ParseBool(propValue)
if err != nil {
return err
}
val.SetBool(bval)
default:
return errors.New(fmt.Sprintf("Field is an unkown type: %s: %s", propName, val.Kind().String()))
}
} else {
return errors.New(fmt.Sprintf("Field is not writable : %s", propName))
}
return nil
}
/********************************************************************************
* Pretty display of jails field