Пример #1
0
func LoadConfigStruct(sectionName string, env envconf.Environment,
	config toml.Primitive, configable HasConfigStruct) (
	configStruct interface{}, err error) {

	if configStruct = configable.ConfigStruct(); configStruct == nil {
		return configStruct, nil
	}

	// Global section options
	// SimplePush defines some common parameters
	// that are defined in the ExtensibleGlobals struct.
	// Use reflection to extract the tagged ExtensibleGlobals fields.
	var pg ExtensibleGlobals
	rt := reflect.TypeOf(pg)

	ignoreConfig := make(map[string]interface{}, rt.NumField())
	ignoreEnv := make(map[string]interface{}, rt.NumField())

	for i := 0; i < rt.NumField(); i++ {
		sft := rt.Field(i)
		kname := sft.Tag.Get("toml")
		if len(kname) == 0 {
			kname = sft.Name
		}
		ignoreConfig[kname] = true
		if kname = sft.Tag.Get("env"); len(kname) == 0 {
			kname = sft.Name
		}
		ignoreEnv[toEnvName(sectionName, kname)] = true
	}

	if err = toml.PrimitiveDecodeStrict(config, configStruct, ignoreConfig); err != nil {
		matches := unknownOptionRegex.FindStringSubmatch(err.Error())
		if len(matches) == 2 {
			// We've got an unrecognized config option.
			err = fmt.Errorf("Unknown config setting for section '%s': %s",
				sectionName, matches[1])
		}
		return nil, err
	}

	if err = env.DecodeStrict(toEnvName(sectionName), EnvSep, configStruct, ignoreEnv); err != nil {
		return nil, fmt.Errorf("Invalid environment variable for section '%s': %s",
			sectionName, err)
	}

	return configStruct, nil
}