func()

in tools/go-agent/instrument/plugins/enhance_config.go [198:248]


func (f *ConfigField) GenerateAssignFieldValue(varName string, field, path []string) []dst.Stmt {
	field = append(field, f.Name)
	path = append(path, f.Key)
	if len(f.ChildFields) > 0 {
		result := make([]dst.Stmt, 0)
		for _, child := range f.ChildFields {
			result = append(result, child.GenerateAssignFieldValue(varName, field, path)...)
		}
		return result
	}
	fieldKeyPathStr := strings.Join(path, ".")
	fieldPathStr := strings.Join(field, ".")
	pluginConfig := config.GetConfig().Plugin.Config.ParseToStringValue(path...)
	if pluginConfig == nil {
		panic(fmt.Errorf("cannot find the config %s", fieldKeyPathStr))
	}
	resultType := f.Type
	getFromEnvStr := ""
	if pluginConfig.EnvKey != "" {
		getFromEnvStr = fmt.Sprintf("if v := tools.GetEnvValue(%q); v != \"\" { result = v };", pluginConfig.EnvKey)
	}
	parseResStr := ""
	parseErrorMessage := fmt.Sprintf(`"cannot parse the config %s: " + err.Error()`, fieldKeyPathStr)
	switch f.Type {
	case "string":
		parseResStr = "return result"
	case "bool":
		parseResStr = "return tools.ParseBool(result)"
	case "int":
		parseResStr = "if v, err := tools.Atoi(result); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "int16":
		parseResStr = "if v, err := tools.ParseInt(result, 10, 16); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "int32":
		parseResStr = "if v, err := tools.ParseInt(result, 10, 32); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "int64":
		parseResStr = "if v, err := tools.ParseInt(result, 10, 64); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "float32":
		parseResStr = "if v, err := tools.ParseFloat(result, 32); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "float64":
		parseResStr = "if v, err := tools.ParseFloat(result, 64); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "float":
		parseResStr = "if v, err := tools.ParseFloat(result, 64); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	case "[]string":
		parseResStr = "if v, err := tools.ParseStringArray(result); err != nil { panic(" + parseErrorMessage + ") } else { return v }"
	default:
		panic("unsupported config type " + f.Type)
	}
	stmtStr := fmt.Sprintf("%s.%s = func () %s { result := %q; %s%s }()",
		varName, fieldPathStr, resultType, pluginConfig.Default, getFromEnvStr, parseResStr)
	return tools.GoStringToStats(stmtStr)
}