I am writing a quick ssh config to json processor in golang. I have the following stuct:
type SshConfig struct {
Host string
Port string
User string
LocalForward string
...
}
I am currently looping over every line of my ssh config file and splitting the line on spaces and checking which property to update.
if split[0] == "Port" {
sshConfig.Port = strings.Join(split[1:], " ")
}
Is there a way to check a property exists and then set it dynamically?
Go by Example: Structs This person struct type has name and age fields. newPerson constructs a new person struct with the given name. You can safely return a pointer to local variable as a local variable will survive the scope of the function. This syntax creates a new struct.
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
To work with a struct, you need to create an instance of it. The var keyword initializes a variable and, using dot notation, values are assigned to the struct fields. You must now create a struct type Player. Here, you have assigned the values to the struct while creating an instance ply1.
Use the reflect package to set a field by name:
// setField sets field of v with given name to given value.
func setField(v interface{}, name string, value string) error {
// v must be a pointer to a struct
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.Elem().Kind() != reflect.Struct {
return errors.New("v must be pointer to struct")
}
// Dereference pointer
rv = rv.Elem()
// Lookup field by name
fv := rv.FieldByName(name)
if !fv.IsValid() {
return fmt.Errorf("not a field name: %s", name)
}
// Field must be exported
if !fv.CanSet() {
return fmt.Errorf("cannot set field %s", name)
}
// We expect a string field
if fv.Kind() != reflect.String {
return fmt.Errorf("%s is not a string field", name)
}
// Set the value
fv.SetString(value)
return nil
}
Call it like this:
var config SshConfig
...
err := setField(&config, split[0], strings.Join(split[1:], " "))
if err != nil {
// handle error
}
playground example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With