Пример #1
0
func marshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)

	switch strings.ToLower(configType) {
	case "yaml", "yml":
		if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "toml":
		if _, err := toml.Decode(buf.String(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "properties", "props", "prop":
		var p *properties.Properties
		var err error
		if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
			return ConfigParseError{err}
		}
		for _, key := range p.Keys() {
			value, _ := p.Get(key)
			c[key] = value
		}
	}

	insensitiviseMap(c)
	return nil
}
Пример #2
0
func marshallConfigReader(in io.Reader, c map[string]interface{}, configType string) {
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)

	switch configType {
	case "yaml", "yml":
		if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "toml":
		if _, err := toml.Decode(buf.String(), &c); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "properties", "props", "prop":
		var p *properties.Properties
		var err error
		if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}
		for _, key := range p.Keys() {
			value, _ := p.Get(key)
			c[key] = value
		}
	}

	insensitiviseMap(c)
}
Пример #3
0
Файл: util.go Проект: ovh/tatcli
func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)

	switch strings.ToLower(configType) {
	case "yaml", "yml":
		if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "hcl":
		obj, err := hcl.Parse(string(buf.Bytes()))
		if err != nil {
			return ConfigParseError{err}
		}
		if err = hcl.DecodeObject(&c, obj); err != nil {
			return ConfigParseError{err}
		}

	case "toml":
		tree, err := toml.LoadReader(buf)
		if err != nil {
			return ConfigParseError{err}
		}
		tmap := tree.ToMap()
		for k, v := range tmap {
			c[k] = v
		}

	case "properties", "props", "prop":
		var p *properties.Properties
		var err error
		if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
			return ConfigParseError{err}
		}
		for _, key := range p.Keys() {
			value, _ := p.Get(key)
			// recursively build nested maps
			path := strings.Split(key, ".")
			lastKey := strings.ToLower(path[len(path)-1])
			deepestMap := deepSearch(c, path[0:len(path)-1])
			// set innermost value
			deepestMap[lastKey] = value
		}
	}

	insensitiviseMap(c)
	return nil
}
Пример #4
0
func (propertiesParser *PropertiesParser) Parse(content []byte, c map[string]interface{}) error {

	var p *properties.Properties
	p, err := properties.Load(content, properties.UTF8)
	if err != nil {
		return err
	}
	for _, key := range p.Keys() {
		value, _ := p.Get(key)
		c[key] = value
	}
	return err
}
Пример #5
0
// stringVal returns the first non-empty value found or the default value.
// Keys are checked in order and environment variables take precedence over
// properties values.  Environment varaible names are derived from property
// names by replacing the dots with underscores.
func stringVal(p *properties.Properties, def string, keys ...string) string {
	for _, key := range keys {
		if v := os.Getenv(strings.Replace(key, ".", "_", -1)); v != "" {
			return v
		}
		if p == nil {
			continue
		}
		if v, ok := p.Get(key); ok {
			return v
		}
	}
	return def
}
Пример #6
0
// ParseFlags parses command line arguments and provides fallback
// values from environment variables and config file values.
// Environment variables are case-insensitive and can have either
// of the provided prefixes.
func (f *FlagSet) ParseFlags(args, environ, prefixes []string, p *properties.Properties) error {
	if err := f.Parse(args); err != nil {
		return err
	}

	if len(prefixes) == 0 {
		prefixes = []string{""}
	}

	// parse environment in case-insensitive way
	env := map[string]string{}
	for _, e := range environ {
		p := strings.SplitN(e, "=", 2)
		env[strings.ToUpper(p[0])] = p[1]
	}

	// determine all values that were set via cmdline
	f.Visit(func(fl *flag.Flag) {
		f.set[fl.Name] = true
	})

	// lookup the rest via environ and properties
	f.VisitAll(func(fl *flag.Flag) {
		// skip if already set
		if f.set[fl.Name] {
			return
		}

		// check environment variables
		for _, pfx := range prefixes {
			name := strings.ToUpper(pfx + strings.Replace(fl.Name, ".", "_", -1))
			if val, ok := env[name]; ok {
				f.set[fl.Name] = true
				f.Set(fl.Name, val)
				return
			}
		}

		// check properties
		if p == nil {
			return
		}
		if val, ok := p.Get(fl.Name); ok {
			f.set[fl.Name] = true
			f.Set(fl.Name, val)
			return
		}
	})
	return nil
}
Пример #7
0
func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)

	switch strings.ToLower(configType) {
	case "yaml", "yml":
		if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "hcl":
		obj, err := hcl.Parse(string(buf.Bytes()))
		if err != nil {
			return ConfigParseError{err}
		}
		if err = hcl.DecodeObject(&c, obj); err != nil {
			return ConfigParseError{err}
		}

	case "toml":
		tree, err := toml.LoadReader(buf)
		if err != nil {
			return ConfigParseError{err}
		}
		tmap := tree.ToMap()
		for k, v := range tmap {
			c[k] = v
		}

	case "properties", "props", "prop":
		var p *properties.Properties
		var err error
		if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
			return ConfigParseError{err}
		}
		for _, key := range p.Keys() {
			value, _ := p.Get(key)
			c[key] = value
		}
	}

	insensitiviseMap(c)
	return nil
}
Пример #8
0
func fromProperties(p *properties.Properties) (cfg *Config, err error) {
	cfg = &Config{}

	deprecate := func(key, msg string) {
		_, exists := p.Get(key)
		if exists {
			log.Print("[WARN] config: ", msg)
		}
	}

	cfg.Proxy = Proxy{
		MaxConn:               intVal(p, Default.Proxy.MaxConn, "proxy.maxconn"),
		Strategy:              stringVal(p, Default.Proxy.Strategy, "proxy.strategy"),
		ShutdownWait:          durationVal(p, Default.Proxy.ShutdownWait, "proxy.shutdownwait"),
		DialTimeout:           durationVal(p, Default.Proxy.DialTimeout, "proxy.dialtimeout"),
		ResponseHeaderTimeout: durationVal(p, Default.Proxy.ResponseHeaderTimeout, "proxy.timeout"),
		KeepAliveTimeout:      durationVal(p, Default.Proxy.KeepAliveTimeout, "proxy.timeout"),
		LocalIP:               stringVal(p, Default.Proxy.LocalIP, "proxy.localip"),
		ClientIPHeader:        stringVal(p, Default.Proxy.ClientIPHeader, "proxy.header.clientip"),
		TLSHeader:             stringVal(p, Default.Proxy.TLSHeader, "proxy.header.tls"),
		TLSHeaderValue:        stringVal(p, Default.Proxy.TLSHeaderValue, "proxy.header.tls.value"),
	}

	readTimeout := durationVal(p, time.Duration(0), "proxy.readtimeout")
	writeTimeout := durationVal(p, time.Duration(0), "proxy.writetimeout")

	cfg.Listen, err = parseListen(stringVal(p, Default.Listen[0].Addr, "proxy.addr"), readTimeout, writeTimeout)
	if err != nil {
		return nil, err
	}

	cfg.Metrics = parseMetrics(
		stringVal(p, Default.Metrics[0].Target, "metrics.target"),
		stringVal(p, Default.Metrics[0].Prefix, "metrics.prefix"),
		stringVal(p, Default.Metrics[0].Addr, "metrics.graphite.addr"),
		durationVal(p, Default.Metrics[0].Interval, "metrics.interval"),
	)

	cfg.Registry = Registry{
		Backend: stringVal(p, Default.Registry.Backend, "registry.backend"),
		File: File{
			Path: stringVal(p, Default.Registry.File.Path, "registry.file.path"),
		},
		Static: Static{
			Routes: stringVal(p, Default.Registry.Static.Routes, "registry.static.routes"),
		},
		Consul: Consul{
			Addr:          stringVal(p, Default.Registry.Consul.Addr, "registry.consul.addr", "consul.addr"),
			Token:         stringVal(p, Default.Registry.Consul.Token, "registry.consul.token", "consul.token"),
			KVPath:        stringVal(p, Default.Registry.Consul.KVPath, "registry.consul.kvpath", "consul.kvpath"),
			TagPrefix:     stringVal(p, Default.Registry.Consul.TagPrefix, "registry.consul.tagprefix", "consul.tagprefix"),
			ServiceAddr:   stringVal(p, Default.Registry.Consul.ServiceAddr, "registry.consul.register.addr"),
			ServiceName:   stringVal(p, Default.Registry.Consul.ServiceName, "registry.consul.register.name", "consul.register.name"),
			CheckInterval: durationVal(p, Default.Registry.Consul.CheckInterval, "registry.consul.register.checkInterval", "consul.register.checkInterval"),
			CheckTimeout:  durationVal(p, Default.Registry.Consul.CheckTimeout, "registry.consul.register.checkTimeout", "consul.register.checkTimeout"),
		},
		GoogleCloudPlatform: GoogleCloudPlatform{
			CheckInterval: durationVal(p, Default.Registry.GoogleCloudPlatform.CheckInterval, "registry.gcp.updateEvery"),
			Project:       stringVal(p, Default.Registry.GoogleCloudPlatform.Project, "registry.gcp.project"),
			Zone:          stringVal(p, Default.Registry.GoogleCloudPlatform.Zone, "registry.gcp.zone"),
		},
	}
	deprecate("consul.addr", "consul.addr has been replaced by registry.consul.addr")
	deprecate("consul.token", "consul.token has been replaced by registry.consul.token")
	deprecate("consul.kvpath", "consul.kvpath has been replaced by registry.consul.kvpath")
	deprecate("consul.tagprefix", "consul.tagprefix has been replaced by registry.consul.tagprefix")
	deprecate("consul.register.name", "consul.register.name has been replaced by registry.consul.register.name")
	deprecate("consul.register.checkInterval", "consul.register.checkInterval has been replaced by registry.consul.register.checkInterval")
	deprecate("consul.register.checkTimeout", "consul.register.checkTimeout has been replaced by registry.consul.register.checkTimeout")
	deprecate("consul.url", "consul.url is obsolete. Please remove it.")

	proxyRoutes := stringVal(p, "", "proxy.routes")
	if strings.HasPrefix(proxyRoutes, "@") {
		cfg.Registry.Backend = "file"
		cfg.Registry.File.Path = proxyRoutes[1:]
		deprecate("proxy.routes", "Please use registry.backend=file and registry.file.path=<path> instead of proxy.routes=@<path>")
	} else if proxyRoutes != "" {
		cfg.Registry.Backend = "static"
		cfg.Registry.Static.Routes = proxyRoutes
		deprecate("proxy.routes", "Please use registry.backend=static and registry.static.routes=<routes> instead of proxy.routes=<routes>")
	}

	cfg.Runtime = Runtime{
		GOGC:       intVal(p, Default.Runtime.GOGC, "runtime.gogc"),
		GOMAXPROCS: intVal(p, Default.Runtime.GOMAXPROCS, "runtime.gomaxprocs"),
	}
	if cfg.Runtime.GOMAXPROCS == -1 {
		cfg.Runtime.GOMAXPROCS = runtime.NumCPU()
	}

	cfg.UI = UI{
		Addr:  stringVal(p, Default.UI.Addr, "ui.addr"),
		Color: stringVal(p, Default.UI.Color, "ui.color"),
		Title: stringVal(p, Default.UI.Title, "ui.title"),
	}

	dump(cfg)
	return cfg, nil
}