我有一个.ini
要用于初始化Configuration
结构的配置文件。
我想使用Configuration
字段名称并遍历它们,以.ini文件中的相应值填充新实例。
我认为实现此目标的最佳方法可能是反射API(也许我完全错了,告诉我...)
我的问题是我无法弄清楚如何访问字段名称(如果至少可以)
这是我的代码:
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
}
任何帮助表示赞赏...
使用类型,以获得StructField。StructField的名称为:
name := value.Type().Field(i).Name
请注意,ini包的File.MapTo和Section.MapTo方法实现了此功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句