lundi 1 février 2016

How to initialize a struct value fields using reflection?

I got a .ini configuration file that I want to use to initialize a Configuration struct.

I'd like to use the Configuration fields names and loop over them to populate my new instance with the corresponding value in the .ini file.

I thought the best way to achieve this might be reflection API (maybe I'm totally wrong, tell me...)

My problem here is that I cannot figure out how to access field's name (if it is at least possible)

Here is my code:

package test
import(
     "reflect"
     "gopkg.in/ini.v1"
 )

type Config struct {
    certPath string
    keyPath  string
    caPath   string
}

func InitConfig(iniConf *ini.File) *Config{
    config:=new(Config)
    var valuePtr reflect.Value = reflect.ValueOf(config)
    var value reflect.Value = valuePtr.Elem()
    for i := 0; i < value.NumField(); i++ {
        field := value.Field(i)
        if field.Type() == reflect.TypeOf("") {
            //here is my problem, I can't get the field name, this method does not exist... :'(
            value:=cfg.GetSection("section").GetKey(field.GetName())
            field.SetString(value)
        }
    }
    return config
}

Any help appreciated...





Aucun commentaire:

Enregistrer un commentaire