Coder Social home page Coder Social logo

viper's Introduction

Viper v2 feedback

Viper is heading towards v2 and we would love to hear what you would like to see in it. Share your thoughts here: https://forms.gle/R6faU74qPRPAzchZ9

Thank you!

Viper

Mentioned in Awesome Go run on repl.it

GitHub Workflow Status Join the chat at https://gitter.im/spf13/viper Go Report Card Go Version PkgGoDev

Go configuration with fangs!

Many Go projects are built using Viper including:

Install

go get github.com/spf13/viper

Note: Viper uses Go Modules to manage dependencies.

What is Viper?

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports:

  • setting defaults
  • reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
  • live watching and re-reading of config files (optional)
  • reading from environment variables
  • reading from remote config systems (etcd or Consul), and watching changes
  • reading from command line flags
  • reading from buffer
  • setting explicit values

Viper can be thought of as a registry for all of your applications configuration needs.

Why Viper?

When building a modern application, you don’t want to worry about configuration file formats; you want to focus on building awesome software. Viper is here to help with that.

Viper does the following for you:

  1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, INI, envfile or Java properties formats.
  2. Provide a mechanism to set default values for your different configuration options.
  3. Provide a mechanism to set override values for options specified through command line flags.
  4. Provide an alias system to easily rename parameters without breaking existing code.
  5. Make it easy to tell the difference between when a user has provided a command line or config file which is the same as the default.

Viper uses the following precedence order. Each item takes precedence over the item below it:

  • explicit call to Set
  • flag
  • env
  • config
  • key/value store
  • default

Important: Viper configuration keys are case insensitive. There are ongoing discussions about making that optional.

Putting Values into Viper

Establishing Defaults

A good configuration system will support default values. A default value is not required for a key, but it’s useful in the event that a key hasn't been set via config file, environment variable, remote configuration or flag.

Examples:

viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})

Reading Config Files

Viper requires minimal configuration so it knows where to look for config files. Viper supports JSON, TOML, YAML, HCL, INI, envfile and Java Properties files. Viper can search multiple paths, but currently a single Viper instance only supports a single configuration file. Viper does not default to any configuration search paths leaving defaults decision to an application.

Here is an example of how to use Viper to search for and read a configuration file. None of the specific paths are required, but at least one path should be provided where a configuration file is expected.

viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("/etc/appname/")   // path to look for the config file in
viper.AddConfigPath("$HOME/.appname")  // call multiple times to add many search paths
viper.AddConfigPath(".")               // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
	panic(fmt.Errorf("fatal error config file: %w", err))
}

You can handle the specific case where no config file is found like this:

if err := viper.ReadInConfig(); err != nil {
	if _, ok := err.(viper.ConfigFileNotFoundError); ok {
		// Config file not found; ignore error if desired
	} else {
		// Config file was found but another error was produced
	}
}

// Config file found and successfully parsed

NOTE [since 1.6]: You can also have a file without an extension and specify the format programmatically. For those configuration files that lie in the home of the user without any extension like .bashrc

Writing Config Files

Reading from config files is useful, but at times you want to store all modifications made at run time. For that, a bunch of commands are available, each with its own purpose:

  • WriteConfig - writes the current viper configuration to the predefined path, if exists. Errors if no predefined path. Will overwrite the current config file, if it exists.
  • SafeWriteConfig - writes the current viper configuration to the predefined path. Errors if no predefined path. Will not overwrite the current config file, if it exists.
  • WriteConfigAs - writes the current viper configuration to the given filepath. Will overwrite the given file, if it exists.
  • SafeWriteConfigAs - writes the current viper configuration to the given filepath. Will not overwrite the given file, if it exists.

As a rule of the thumb, everything marked with safe won't overwrite any file, but just create if not existent, whilst the default behavior is to create or truncate.

A small examples section:

viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
viper.SafeWriteConfigAs("/path/to/my/.other_config")

Watching and re-reading config files

Viper supports the ability to have your application live read a config file while running.

Gone are the days of needing to restart a server to have a config take effect, viper powered applications can read an update to a config file while running and not miss a beat.

Simply tell the viper instance to watchConfig. Optionally you can provide a function for Viper to run each time a change occurs.

Make sure you add all of the configPaths prior to calling WatchConfig()

viper.OnConfigChange(func(e fsnotify.Event) {
	fmt.Println("Config file changed:", e.Name)
})
viper.WatchConfig()

Reading Config from io.Reader

Viper predefines many configuration sources such as files, environment variables, flags, and remote K/V store, but you are not bound to them. You can also implement your own required configuration source and feed it to viper.

viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")

// any approach to require this configuration into your program.
var yamlExample = []byte(`
Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
  jacket: leather
  trousers: denim
age: 35
eyes : brown
beard: true
`)

viper.ReadConfig(bytes.NewBuffer(yamlExample))

viper.Get("name") // this would be "steve"

Setting Overrides

These could be from a command line flag, or from your own application logic.

viper.Set("Verbose", true)
viper.Set("LogFile", LogFile)
viper.Set("host.port", 5899)   // set subset

Registering and Using Aliases

Aliases permit a single value to be referenced by multiple keys

viper.RegisterAlias("loud", "Verbose")

viper.Set("verbose", true) // same result as next line
viper.Set("loud", true)   // same result as prior line

viper.GetBool("loud") // true
viper.GetBool("verbose") // true

Working with Environment Variables

Viper has full support for environment variables. This enables 12 factor applications out of the box. There are five methods that exist to aid working with ENV:

  • AutomaticEnv()
  • BindEnv(string...) : error
  • SetEnvPrefix(string)
  • SetEnvKeyReplacer(string...) *strings.Replacer
  • AllowEmptyEnv(bool)

When working with ENV variables, it’s important to recognize that Viper treats ENV variables as case sensitive.

Viper provides a mechanism to try to ensure that ENV variables are unique. By using SetEnvPrefix, you can tell Viper to use a prefix while reading from the environment variables. Both BindEnv and AutomaticEnv will use this prefix.

BindEnv takes one or more parameters. The first parameter is the key name, the rest are the name of the environment variables to bind to this key. If more than one are provided, they will take precedence in the specified order. The name of the environment variable is case sensitive. If the ENV variable name is not provided, then Viper will automatically assume that the ENV variable matches the following format: prefix + "_" + the key name in ALL CAPS. When you explicitly provide the ENV variable name (the second parameter), it does not automatically add the prefix. For example if the second parameter is "id", Viper will look for the ENV variable "ID".

One important thing to recognize when working with ENV variables is that the value will be read each time it is accessed. Viper does not fix the value when the BindEnv is called.

AutomaticEnv is a powerful helper especially when combined with SetEnvPrefix. When called, Viper will check for an environment variable any time a viper.Get request is made. It will apply the following rules. It will check for an environment variable with a name matching the key uppercased and prefixed with the EnvPrefix if set.

SetEnvKeyReplacer allows you to use a strings.Replacer object to rewrite Env keys to an extent. This is useful if you want to use - or something in your Get() calls, but want your environmental variables to use _ delimiters. An example of using it can be found in viper_test.go.

Alternatively, you can use EnvKeyReplacer with NewWithOptions factory function. Unlike SetEnvKeyReplacer, it accepts a StringReplacer interface allowing you to write custom string replacing logic.

By default empty environment variables are considered unset and will fall back to the next configuration source. To treat empty environment variables as set, use the AllowEmptyEnv method.

Env example

SetEnvPrefix("spf") // will be uppercased automatically
BindEnv("id")

os.Setenv("SPF_ID", "13") // typically done outside of the app

id := Get("id") // 13

Working with Flags

Viper has the ability to bind to flags. Specifically, Viper supports Pflags as used in the Cobra library.

Like BindEnv, the value is not set when the binding method is called, but when it is accessed. This means you can bind as early as you want, even in an init() function.

For individual flags, the BindPFlag() method provides this functionality.

Example:

serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))

You can also bind an existing set of pflags (pflag.FlagSet):

Example:

pflag.Int("flagname", 1234, "help message for flagname")

pflag.Parse()
viper.BindPFlags(pflag.CommandLine)

i := viper.GetInt("flagname") // retrieve values from viper instead of pflag

The use of pflag in Viper does not preclude the use of other packages that use the flag package from the standard library. The pflag package can handle the flags defined for the flag package by importing these flags. This is accomplished by a calling a convenience function provided by the pflag package called AddGoFlagSet().

Example:

package main

import (
	"flag"
	"github.com/spf13/pflag"
)

func main() {

	// using standard library "flag" package
	flag.Int("flagname", 1234, "help message for flagname")

	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
	pflag.Parse()
	viper.BindPFlags(pflag.CommandLine)

	i := viper.GetInt("flagname") // retrieve value from viper

	// ...
}

Flag interfaces

Viper provides two Go interfaces to bind other flag systems if you don’t use Pflags.

FlagValue represents a single flag. This is a very simple example on how to implement this interface:

type myFlag struct {}
func (f myFlag) HasChanged() bool { return false }
func (f myFlag) Name() string { return "my-flag-name" }
func (f myFlag) ValueString() string { return "my-flag-value" }
func (f myFlag) ValueType() string { return "string" }

Once your flag implements this interface, you can simply tell Viper to bind it:

viper.BindFlagValue("my-flag-name", myFlag{})

FlagValueSet represents a group of flags. This is a very simple example on how to implement this interface:

type myFlagSet struct {
	flags []myFlag
}

func (f myFlagSet) VisitAll(fn func(FlagValue)) {
	for _, flag := range flags {
		fn(flag)
	}
}

Once your flag set implements this interface, you can simply tell Viper to bind it:

fSet := myFlagSet{
	flags: []myFlag{myFlag{}, myFlag{}},
}
viper.BindFlagValues("my-flags", fSet)

Remote Key/Value Store Support

To enable remote support in Viper, do a blank import of the viper/remote package:

import _ "github.com/spf13/viper/remote"

Viper will read a config string (as JSON, TOML, YAML, HCL or envfile) retrieved from a path in a Key/Value store such as etcd or Consul. These values take precedence over default values, but are overridden by configuration values retrieved from disk, flags, or environment variables.

Viper supports multiple hosts. To use, pass a list of endpoints separated by ;. For example http://127.0.0.1:4001;http://127.0.0.1:4002.

Viper uses crypt to retrieve configuration from the K/V store, which means that you can store your configuration values encrypted and have them automatically decrypted if you have the correct gpg keyring. Encryption is optional.

You can use remote configuration in conjunction with local configuration, or independently of it.

crypt has a command-line helper that you can use to put configurations in your K/V store. crypt defaults to etcd on http://127.0.0.1:4001.

$ go get github.com/sagikazarmark/crypt/bin/crypt
$ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json

Confirm that your value was set:

$ crypt get -plaintext /config/hugo.json

See the crypt documentation for examples of how to set encrypted values, or how to use Consul.

Remote Key/Value Store Example - Unencrypted

etcd

viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001","/config/hugo.json")
viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
err := viper.ReadRemoteConfig()

etcd3

viper.AddRemoteProvider("etcd3", "http://127.0.0.1:4001","/config/hugo.json")
viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
err := viper.ReadRemoteConfig()

Consul

You need to set a key to Consul key/value storage with JSON value containing your desired config. For example, create a Consul key/value store key MY_CONSUL_KEY with value:

{
    "port": 8080,
    "hostname": "myhostname.com"
}
viper.AddRemoteProvider("consul", "localhost:8500", "MY_CONSUL_KEY")
viper.SetConfigType("json") // Need to explicitly set this to json
err := viper.ReadRemoteConfig()

fmt.Println(viper.Get("port")) // 8080
fmt.Println(viper.Get("hostname")) // myhostname.com

Firestore

viper.AddRemoteProvider("firestore", "google-cloud-project-id", "collection/document")
viper.SetConfigType("json") // Config's format: "json", "toml", "yaml", "yml"
err := viper.ReadRemoteConfig()

Of course, you're allowed to use SecureRemoteProvider also

NATS

viper.AddRemoteProvider("nats", "nats://127.0.0.1:4222", "myapp.config")
viper.SetConfigType("json")
err := viper.ReadRemoteConfig()

Remote Key/Value Store Example - Encrypted

viper.AddSecureRemoteProvider("etcd","http://127.0.0.1:4001","/config/hugo.json","/etc/secrets/mykeyring.gpg")
viper.SetConfigType("json") // because there is no file extension in a stream of bytes,  supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
err := viper.ReadRemoteConfig()

Watching Changes in etcd - Unencrypted

// alternatively, you can create a new viper instance.
var runtime_viper = viper.New()

runtime_viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/hugo.yml")
runtime_viper.SetConfigType("yaml") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"

// read from remote config the first time.
err := runtime_viper.ReadRemoteConfig()

// unmarshal config
runtime_viper.Unmarshal(&runtime_conf)

// open a goroutine to watch remote changes forever
go func(){
	for {
		time.Sleep(time.Second * 5) // delay after each request

		// currently, only tested with etcd support
		err := runtime_viper.WatchRemoteConfig()
		if err != nil {
			log.Errorf("unable to read remote config: %v", err)
			continue
		}

		// unmarshal new config into our runtime config struct. you can also use channel
		// to implement a signal to notify the system of the changes
		runtime_viper.Unmarshal(&runtime_conf)
	}
}()

Getting Values From Viper

In Viper, there are a few ways to get a value depending on the value’s type. The following functions and methods exist:

  • Get(key string) : any
  • GetBool(key string) : bool
  • GetFloat64(key string) : float64
  • GetInt(key string) : int
  • GetIntSlice(key string) : []int
  • GetString(key string) : string
  • GetStringMap(key string) : map[string]any
  • GetStringMapString(key string) : map[string]string
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • IsSet(key string) : bool
  • AllSettings() : map[string]any

One important thing to recognize is that each Get function will return a zero value if it’s not found. To check if a given key exists, the IsSet() method has been provided.

The zero value will also be returned if the value is set, but fails to parse as the requested type.

Example:

viper.GetString("logfile") // case-insensitive Setting & Getting
if viper.GetBool("verbose") {
	fmt.Println("verbose enabled")
}

Accessing nested keys

The accessor methods also accept formatted paths to deeply nested keys. For example, if the following JSON file is loaded:

{
    "host": {
        "address": "localhost",
        "port": 5799
    },
    "datastore": {
        "metric": {
            "host": "127.0.0.1",
            "port": 3099
        },
        "warehouse": {
            "host": "198.0.0.1",
            "port": 2112
        }
    }
}

Viper can access a nested field by passing a . delimited path of keys:

GetString("datastore.metric.host") // (returns "127.0.0.1")

This obeys the precedence rules established above; the search for the path will cascade through the remaining configuration registries until found.

For example, given this configuration file, both datastore.metric.host and datastore.metric.port are already defined (and may be overridden). If in addition datastore.metric.protocol was defined in the defaults, Viper would also find it.

However, if datastore.metric was overridden (by a flag, an environment variable, the Set() method, …) with an immediate value, then all sub-keys of datastore.metric become undefined, they are “shadowed” by the higher-priority configuration level.

Viper can access array indices by using numbers in the path. For example:

{
    "host": {
        "address": "localhost",
        "ports": [
            5799,
            6029
        ]
    },
    "datastore": {
        "metric": {
            "host": "127.0.0.1",
            "port": 3099
        },
        "warehouse": {
            "host": "198.0.0.1",
            "port": 2112
        }
    }
}

GetInt("host.ports.1") // returns 6029

Lastly, if there exists a key that matches the delimited key path, its value will be returned instead. E.g.

{
    "datastore.metric.host": "0.0.0.0",
    "host": {
        "address": "localhost",
        "port": 5799
    },
    "datastore": {
        "metric": {
            "host": "127.0.0.1",
            "port": 3099
        },
        "warehouse": {
            "host": "198.0.0.1",
            "port": 2112
        }
    }
}

GetString("datastore.metric.host") // returns "0.0.0.0"

Extracting a sub-tree

When developing reusable modules, it's often useful to extract a subset of the configuration and pass it to a module. This way the module can be instantiated more than once, with different configurations.

For example, an application might use multiple different cache stores for different purposes:

cache:
  cache1:
    max-items: 100
    item-size: 64
  cache2:
    max-items: 200
    item-size: 80

We could pass the cache name to a module (eg. NewCache("cache1")), but it would require weird concatenation for accessing config keys and would be less separated from the global config.

So instead of doing that let's pass a Viper instance to the constructor that represents a subset of the configuration:

cache1Config := viper.Sub("cache.cache1")
if cache1Config == nil { // Sub returns nil if the key cannot be found
	panic("cache configuration not found")
}

cache1 := NewCache(cache1Config)

Note: Always check the return value of Sub. It returns nil if a key cannot be found.

Internally, the NewCache function can address max-items and item-size keys directly:

func NewCache(v *Viper) *Cache {
	return &Cache{
		MaxItems: v.GetInt("max-items"),
		ItemSize: v.GetInt("item-size"),
	}
}

The resulting code is easy to test, since it's decoupled from the main config structure, and easier to reuse (for the same reason).

Unmarshaling

You also have the option of Unmarshaling all or a specific value to a struct, map, etc.

There are two methods to do this:

  • Unmarshal(rawVal any) : error
  • UnmarshalKey(key string, rawVal any) : error

Example:

type config struct {
	Port int
	Name string
	PathMap string `mapstructure:"path_map"`
}

var C config

err := viper.Unmarshal(&C)
if err != nil {
	t.Fatalf("unable to decode into struct, %v", err)
}

If you want to unmarshal configuration where the keys themselves contain dot (the default key delimiter), you have to change the delimiter:

v := viper.NewWithOptions(viper.KeyDelimiter("::"))

v.SetDefault("chart::values", map[string]any{
	"ingress": map[string]any{
		"annotations": map[string]any{
			"traefik.frontend.rule.type":                 "PathPrefix",
			"traefik.ingress.kubernetes.io/ssl-redirect": "true",
		},
	},
})

type config struct {
	Chart struct{
		Values map[string]any
	}
}

var C config

v.Unmarshal(&C)

Viper also supports unmarshaling into embedded structs:

/*
Example config:

module:
    enabled: true
    token: 89h3f98hbwf987h3f98wenf89ehf
*/
type config struct {
	Module struct {
		Enabled bool

		moduleConfig `mapstructure:",squash"`
	}
}

// moduleConfig could be in a module specific package
type moduleConfig struct {
	Token string
}

var C config

err := viper.Unmarshal(&C)
if err != nil {
	t.Fatalf("unable to decode into struct, %v", err)
}

Viper uses github.com/go-viper/mapstructure under the hood for unmarshaling values which uses mapstructure tags by default.

Decoding custom formats

A frequently requested feature for Viper is adding more value formats and decoders. For example, parsing character (dot, comma, semicolon, etc) separated strings into slices.

This is already available in Viper using mapstructure decode hooks.

Read more about the details in this blog post.

Marshalling to string

You may need to marshal all the settings held in viper into a string rather than write them to a file. You can use your favorite format's marshaller with the config returned by AllSettings().

import (
	yaml "gopkg.in/yaml.v2"
	// ...
)

func yamlStringSettings() string {
	c := viper.AllSettings()
	bs, err := yaml.Marshal(c)
	if err != nil {
		log.Fatalf("unable to marshal config to YAML: %v", err)
	}
	return string(bs)
}

Viper or Vipers?

Viper comes with a global instance (singleton) out of the box.

Although it makes setting up configuration easy, using it is generally discouraged as it makes testing harder and can lead to unexpected behavior.

The best practice is to initialize a Viper instance and pass that around when necessary.

The global instance MAY be deprecated in the future. See #1855 for more details.

Working with multiple vipers

You can also create many different vipers for use in your application. Each will have its own unique set of configurations and values. Each can read from a different config file, key value store, etc. All of the functions that viper package supports are mirrored as methods on a viper.

Example:

x := viper.New()
y := viper.New()

x.SetDefault("ContentDir", "content")
y.SetDefault("ContentDir", "foobar")

//...

When working with multiple vipers, it is up to the user to keep track of the different vipers.

Q & A

Why is it called “Viper”?

A: Viper is designed to be a companion to Cobra. While both can operate completely independently, together they make a powerful pair to handle much of your application foundation needs.

Why is it called “Cobra”?

Is there a better name for a commander?

Does Viper support case sensitive keys?

tl;dr: No.

Viper merges configuration from various sources, many of which are either case insensitive or uses different casing than the rest of the sources (eg. env vars). In order to provide the best experience when using multiple sources, the decision has been made to make all keys case insensitive.

There has been several attempts to implement case sensitivity, but unfortunately it's not that trivial. We might take a stab at implementing it in Viper v2, but despite the initial noise, it does not seem to be requested that much.

You can vote for case sensitivity by filling out this feedback form: https://forms.gle/R6faU74qPRPAzchZ9

Is it safe to concurrently read and write to a viper?

No, you will need to synchronize access to the viper yourself (for example by using the sync package). Concurrent reads and writes can cause a panic.

Troubleshooting

See TROUBLESHOOTING.md.

Development

For an optimal developer experience, it is recommended to install Nix and direnv.

Alternatively, install Go on your computer then run make deps to install the rest of the dependencies.

Run the test suite:

make test

Run linters:

make lint # pass -j option to run them in parallel

Some linter violations can automatically be fixed:

make fmt

License

The project is licensed under the MIT License.

viper's People

Contributors

akutz avatar alexandear avatar alxmsl avatar andrewstuart avatar anthonyfok avatar benoitmasson avatar bep avatar bersace avatar bketelsen avatar burgesq avatar chancez avatar dependabot[bot] avatar didenko avatar illarion avatar jackspirou avatar javaducky avatar michael-k avatar moorereason avatar muesli avatar n10v avatar nmiyake avatar oliveagle avatar patdhlk avatar sagikazarmark avatar scop avatar serazoli avatar spf13 avatar taylorono avatar wofr avatar xcoulon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

viper's Issues

Multiple config paths doesn't seem to be working

I've been using viper with single config path. However, when I add multiple files the second one could not be retrieved. Here's the code;

    viper.SetConfigType("toml")

    viper.SetConfigName("config")

    viper.AddConfigPath("./config.toml")
    viper.AddConfigPath("./messages/messages.toml")

    messages.SetDefaultLocale("en")

    err := viper.ReadInConfig()
    if err != nil {
        panic(fmt.Errorf("%s\n", err))
    }

    fmt.Println("messages value", viper.GetString("hello.world"))
    fmt.Println("config value http.host", viper.GetString("http.host"))

Here's the output

messages value
config value http.host 0.0.0.0
# messages.toml
[hello]
world = "Hello world"

And one strange error, if I comment out with line ./config.toml, the output is same!. I think viper is doing some caching and it's not invalidating.

Support for properties file style configs

I work where java is king and most of our configs are controlled with key: value .properties files.

I like the looks of cobra and viper, and would like to see support for .properties files.

Working on a PR

Include '.yml' as supported YAML extension

Not a big deal but ".yml" is a valid file extension for YAML and will be nice to include it. I run into this issue earlier. Might be helpful to either add the extension or update the documentation to specify the extensions supported. Thanks.

Configuration file per environment?

Hi there,

I come from Node.js world, when we got the config module. This one allows to specify several configuration files, such as default.json, development.json and production.json. Depending of environment variable, we serve either dev or prod file, fallbacking on default.json for not specified values.

Can we achieve the same process with Viper?

I guess we can switch on correct configuration file using a test on environment variable and viper.SetConfigName method. But what about the fallback feature? Can we tell Viper to get them from a file instead of setting them manually via several SetDefault calls?

Accessing nested keys does not work

Accessing nested keys doesn't seem to work as is described in the documentation:

using

                {
                        "ImportPath": "github.com/spf13/viper",
                        "Rev": "29f1858f8782bd55fa432c459f7e64b7032b3c33"
                },

Go version is:

go version go1.4.2 darwin/amd64

This is the test

package main

import (
    "fmt"
    "log"

    "github.com/spf13/viper"
)

func main() {
    viper.SetConfigName("test")
    err := viper.ReadInConfig()
    if err != nil {
        log.Println(err)
    }
    fmt.Println("Keys:", viper.AllKeys())
    fmt.Println("AllSettings:", viper.AllSettings())
    log.Println(viper.GetString("datastore.metric.host"))
}

This is the JSON file being used as config, is a copy and paste form the documentation.

{
    "host": {
        "address": "localhost",
        "port": 5799
    },
    "datastore": {
        "metric": {
            "host": "127.0.0.1",
            "port": 3099
        },
        "warehouse": {
            "host": "198.0.0.1",
            "port": 2112
        }
    }
}

This is the result:

 rmoral00@HQSML-312266 ❯ godep go build && ./test
Keys: [host datastore]
AllSettings: map[host:map[address:localhost port:5799] datastore:map[metric:map[host:127.0.0.1 port:3099] warehouse:map[host:198.0.0.1 port:2112]]]
2015/05/08 07:43:34

Default option when no key set in config after configuration reload

Hello, @spf13 !

I was implementing configuration reload on SIGHUP signal and came across an issue with default option value. When I am deleting key entirely from JSON config I expect that after reload value for this key will be set to default value, but it's not - the key still have previous value.

Here is an example:

package main

import (
    "fmt"
    "io/ioutil"

    "github.com/spf13/viper"
)

func main() {
    var jsonExample []byte

    viper.SetDefault("num", 5)
    viper.SetConfigFile("/tmp/example.json")

    jsonExample = []byte(`
    {
        "num": 3
    }
    `)
    ioutil.WriteFile("/tmp/example.json", jsonExample, 0644)
    viper.ReadInConfig()
    fmt.Println(viper.GetInt("num"))

    jsonExample = []byte(`
    {}
    `)
    ioutil.WriteFile("/tmp/example.json", jsonExample, 0644)
    viper.ReadInConfig()
    fmt.Println(viper.GetInt("num")) // expecting default value 5 here

    jsonExample = []byte(`
    {
        "num": 10
    }
    `)
    ioutil.WriteFile("/tmp/example.json", jsonExample, 0644)
    viper.ReadInConfig()
    fmt.Println(viper.GetInt("num"))
}

The output:

3
3
10

While I am expecting this:

3
5
10

?

Current directory used for config if no other specified directories exist

It does not seem to be a problem if no directories were added with AddConfigPath - CWD is probably a good assumption.

However, if config directories are misconfigured, or, more importantly, get accidentally erased later, then loading configuration from CWD is a surprise behaviour. I would expect a failure at that point.

Code example:

package main

import (
    "io/ioutil"
    "os"

    "github.com/spf13/viper"
)

const configFile = "surprise_inside"
const configFileFull = configFile + ".toml"

func main() {

    defer os.Remove(configFileFull)

    // Although probably distinct use cases, viper
    // reads the config in cwd regardless of AddConfigPath
    // being commented out or not
    viper.AddConfigPath("this_junk_does_not_exist")

    viper.SetConfigName(configFile)
    viper.SetDefault("key", "Feels good!")

    err := viper.ReadInConfig()
    if err != nil {
        println("Fatal error reading config file - good")
    } else {
        println(viper.GetString("key"))
    }

    println("Writing " + configFileFull)

    err = ioutil.WriteFile(
        configFileFull,
        []byte("key = \"Surprise!\"\n"),
        0600)
    if err != nil {
        println("Fatal error writing config file - bad")
    } else {

        err = viper.ReadInConfig()
        if err != nil {
            println("Fatal error reading config file - bad")
        } else {
            println(viper.GetString("key"))
        }
    }
}

Aliases don't work in config file

The values in the config file don't have their keys resolved into the "real key", so when aliases are set, if a value was in the config file with an alias, people trying to get or set that value will have their Get request change the key value into the "real key", which isn't in the map that is loaded from the config file.

No way to read in config from io.Reader

I want to be able to give viper an io.Reader to read from, rather than having viper always read from a file... this makes it a lot easier for me to test - I can just hand viper a bytes.Buffer{} rather than having to write a config to disk during tests. I could make a PR, but I noticed that there used to be a viper.MarshalReader which has since disappeared.... so I wanted to post this first to see if the PR is a good idea in general before doing the work. I see there's already a (non-exported) marshalReader function, so hopefully it wouldn't require much to make something like that publicly visible in a nice way.

viper.Get and viper.GetString. Different results for string setting.

config (json):

{
    "msg": "Hello World"
}

code:

lconfig := viper.New()
...
log.Println("msg get:", lconfig.Get("msg"))
log.Println("msg get + cast:", cast.ToString(lconfig.Get("msg")))
log.Println("msg get string:", lconfig.GetString("msg"))

output:

2014/12/06 14:46:01 msg get: Hello World
2014/12/06 14:46:01 msg get + cast: Hello World
2014/12/06 14:46:01 msg get string: 

Use filepath instead of path to handle os specific path manipulation

Run into a bug with path handling in windows were using "/" as file separator kept failing. Dug around the code for a bit and found the user of path.Join(..) use in func searchInPath which doesn't account for the target operating system-defined file paths. Replacing path.join with filepath.Join(..) accounts for both os paths and fixes the issue. Hope this help.

Config export

Hi,

How can i export loaded config (with ie. override some parts of it using ENV or CLI args) back to original or even different config file?

Go 1.2 compatibility

Apparently an upstream package is now not go 1.2 compatible - see here. Either Travis CI config should remove the 1.2 target or upstream dependencies need fixing so that viper builds succeed in the future.

multiple config files

To read from multiple config files, I have to do something like:

    viper.SetConfigName("db")
    viper.AddConfigPath("config")
    viper.ReadInConfig()
    dbConfig := viper.GetStringMapString("devEnv")
    viper.Reset()   

I think sth like this would be nicer?

    dbConfig := viper.NewConfig()
    dbConfig.SetConfigName("db")
    dbConfig.AddConfigPath("config")
    err := dbConfig.ReadInConfig()
    if err != nil {
        panic(err) // or whatever
    }
    dbConfig.GetStringMapString("devEnv")

Dashes in flag names should be handled.

For example, when doing BindEnv dashes should be replaced with _ underscores. And when Marshal()-ing, it should be eliminated from the key of the target struct.

viper is a unexported struct. Use New().

// A viper is a unexported struct. Use New() to create a new instance of viper
// or use the functions for a "global instance"

OK, i use New() for create a new instance of viper, but then how can I send created viper to another my package (viper is not export)? I can create an interface, that is equal to viper interface. But i think would be better if viper provide exported Viper interface or exported Viper struct for use it interface.

Default value for nested key

To support yaml and json config files, it would be nice if it is possible to set default values for nested key.

Currently when I set a default value for.

viper.SetDefault("datastore.metric.host", "0.0.0.0")

The key would not be interpreted as a nested key and it is not possible to overwrite it with a yaml or json config file

Top level JSON Array `ReadInConfig`

Hi,
i have a problem using the ReadInConfig method. I am loading data from a JSON file structured as follows:

[
  {
    "name": "sample1"
  },
  {
    "name": "sample2"
  }
]

When reading it using err = viper.ReadInConfig() i got the following error:

ERROR: 2015/07/03 Error parsing config: json: cannot unmarshal array into Go value of type map[string]interface {}
exit status 1

Better documentation or examples?

I don't know if its just me or if I'm stupid, but I am often going in to the actual code to figure out how to use viper. In my opinion, I should not worry of the internals and the API is just not clear to me, nor the examples. It would be nice to have better docs. I couldn't find godocs for it either.

Complex JSON and Get() function

Hello, I'm having some problem getting data from a nested JSON config file.

My JSON:

{
  "types": [
    {
      "web": {
        "foo": "bar"
      }
    }
  ]
}

I need to get the foo key, so I thought I would do:

x := viper.Get("types")
x[0]["web"]["foo"]

I thought I would also be able to iterate on x using range but this does not work due to a error:

invalid operation: x[0] (type interface {} does not support indexing)

To correctly get the value I need to write this:

// this returns "bar"
viper.Get("types").([]interface{})[0].(map[string]interface{})["web"].(map[string]interface{})["foo"]

Any hint on how this could be improved? Is the intended behaviour? Am I totally missing something?

Thanks for the cool library ( and cobra and jww, I'm using them all :D )

Is viper thread safe?

I've been reading about how database layers and so on are bound to request contexts, and are thread safe. For example, gorilla/context uses sync mutex to ensure that only one thread can read / write to the context for a single request at any given time. I couldn't see anything like that on first glance at viper.

Is it safe to use viper with many simultaneous threads?

Support yml extension

yml extension is very common for YAML files, why not support it? It's on purpose or it can be added?

Defaults to current dir

Viper defaults to loading config.toml (if that is the config name set) from the current directory.

This is very confusing if you have several applications using Viper, and your command prompt happen to be in "the other one".

Can't get MarshallKey to work

Hi, couldn't find an irc or something to discuss this on, so I'm posting it here.

I'm having trouble getting Marshall key to Unmarshal to a struct. Here's some example code of what I'm trying to do.

type Server struct {
  address string
  name string
}

var (
  ServerConfigs map[string]Server
)

func main() {
  ...
  viper.Marshalkey("servers", &ServerConfigs)
}

Example config in toml:

[servers]
[servers.server1]
address = "serveraddress"
name = "server1"

[servers.server2]
address = "address2"

My result ends up being a map with the keys "server1" and "server2" with the struct fields being empty.

Any tips on getting this to work? Or is this something that requires #15 being implemented? I also can't find any documentation of using struct labels for the MarshalKey interface, is there any support for that?

toml and sections

Hi,

Let say, we have TOML file like:

[foo]
bar = "baz"

[bam]
bip = "bop"

Is there any way to get foo.bar value directly like viper.Get("foo.bar")? And another question, how can i set defaults for this kind of vars (from toml with sections) so they can be overrided later?

Command line --help

It would be cool if you could automate the output when the app is run with --help based on the config values created.

Clarify error handling and config file search techniques in documentation

I included a few specific issues I had to figure out in issue #6 that has been closed, but I hadn't seen any specific fixes in the docs for the issues listed. I'm fine with the bug being 'wont fixed' but I just wanted to be sure the specific issues I had were bubbled up in case they were seen as just a 'me too' post on the thread. From #6:

I couldn't get this working on my first try out of the box and no feedback/ detailed errors (beyond generic io errors) from the apis makes figure this stuff out even harder

In my particular case, I assumed two things that were not obvious to me without reading the code:

  • the current working directory is not included in configPaths by default.
  • the config file is required to have the extension of the file type even though you can specify through SetConfigType. I assumed the search code would have included looking at configName rather than just configName+"."+ext for each known extension

In addition, it would have been helpful for the example that does exist in the readme to properly check for errors loading the file to make it clear that thats how the API works without needing to dig into the source (as is the norm in go) e.g:

viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath("/etc/appname/")   // path to look for the config file in
viper.AddConfigPath("$HOME/.appname")  // call multiple times to add many search paths
err := viper.ReadInConfig() // Find and read the config file
if err != nil {
  fmt.Println("Failed to read config", err)
}

Application exits when marshallConfigReader encounters parsing errors

Hello!

When I send  SIGHUP signal to my already running server application - I want to reload configuration on the fly. But when updated configuration file has errors - wrong JSON format for example - my application exits as marshallConfigReader calls Fatalf. I just want to log that configuration file contains errors that must be fixed before reloading.

ReadInConfig already returns an error – maybe it's better to return an error from marshallConfigReader too so my application code could decide what to do with error if it occurred?

Unmarshal vs. Marshal

Hey spf13, we love your package.

Seems to me you use "Marshal" to mean what most libraries I've used call "Unmarshal". (Compare with the Go JSON package.

What's your thinking on this?

How to get the currently used config path?

Is there a way to get the config path that viper has decided to go with? For example if I set

viper.AddConfgPath("/etc/somename")
viper.AddConfigPath("$HOME/.config/somename")

Viper decides to read the config file from etc how can I retrieve that path later on?

viper/flag cooperation

Hey there,

I was looking for a configuration management tool and viper looked promising. I was interested in how viper works with flag/pflag. This is what the README says (BTW it looks broken):

serverCmd.Flags().Int("port", 1138, "Port to run Application server on") viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))

This does not work for me. Maybe a working example would be cool. Anyway, it looks very complicated to me to need to write two lines of code to let config files and command line flags work together. This is what I came up with:

$ cat main.go
package main

import (
    "fmt"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "os"
)

func main() {
    wd, _ := os.Getwd()

    viper.SetConfigName("config") // name of config file (without extension)
    viper.AddConfigPath(wd)       // path to look for the config file in
    viper.ReadInConfig()          // Find and read the config file

    var cmd *cobra.Command
    var s string

    cmd = &cobra.Command{
        Use:   "hugo",
        Short: "Hugo is a very fast static site generator",
        Long: `A Fast and Flexible Static Site Generator built with
            love by spf13 and friends in Go.
            Complete documentation is available at http://hugo.spf13.com`,
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Printf("source: %#v\n", s)
        },
    }

    // Just use config of configuration file provided by `viper` as default value for the command line flag.
    cmd.Flags().StringVarP(&s, "source", "s", viper.GetString("source"), "Source directory to read from")

    cmd.Execute()
}
$ cat config.json
{
  "source": "not modified"
}
$ ./test
source: "not modified"
$ ./test -s foo
source: "foo"

It would be cool to know how this is intended to work and what people think about my proposal.

Durations don't work in viper.Marshal

Hi, I am unable to Marshal (or Unmarshal) Duration fields whereas, GetDuration("fieldName") works

I've attached an simple test case

package main

import (
    "bytes"
    "testing"
    "time"

    "github.com/spf13/viper"
)

func TestDurationConfig(t *testing.T) {
    type DurationConfig struct {
        testduration time.Duration
    }

    var testYaml = []byte(`
               TestDuration: 5ms
        `)

    viper.SetConfigType("yaml")

    viper.ReadConfig(bytes.NewBuffer(testYaml))

    t.Logf("All keys: %#v", viper.AllSettings())

        // this works
    if viper.GetDuration("testduration") != 5*time.Millisecond {
        t.Errorf("Duration is not 5ms - %v", viper.GetDuration("testduration"))
    }

    var config = &DurationConfig{}

    viper.Marshal(config)

        // this doesn't
    if config == nil || config.testduration != 5*time.Millisecond {
        t.Errorf("Duration config is not 5ms - %#v", config)
    }
}

PSA: Remote Providers expect a single key/value that contains json, yaml, etc.

So spent some time trying to figure out why giving our path: configs to the Consul remote providers wasn't working. Turns out the way crypt and viper is written is expecting path to be a single k/v with the contents of a file to parse into viper.

This feels a little counter intuitive to me, at least for consul, because the recommended way to store configs in it is to use many kv's for each configurable thing. Allowing ACL to be applied and other features I presently do not use.

e.g.

/configs/mysql = app:[email protected]:3306/app_db
/configs/cdn = app.proxy.fastly.com

Looking at the current implementation, not sure if there is much that can be done to implement a fix for this. So this is more of a PSA.

If it was possible to fix, I think we would expect to configure a Remote to know if we were fetching a single kv or a directory with many kv's to iterate to fetch. I believe consul supports ?recurse that may provide usable results here...

config file can't be optional

It would be more useful if ReadInConfig could return an error instead of causing the process to Exit if the config can't be found. This would enable the case where the whole file can be optional and the values read from defaults.

func ReadInConfig() {
    jww.INFO.Println("Attempting to read in config file")

    if !stringInSlice(getConfigType(), SupportedExts) {
        jww.ERROR.Fatalf("Unsupported Config Type %q", getConfigType())
    }

    ...

Trouble accessing nested StringSlice

I have the following yaml.

filters:
  SomeTitle:
      reject:
         - "foo"
         - "bar"
      include:
         - "the"
         - "at"

I am trying to access the reject and include lists like so. viper.GetStringSlice("filters.SomeTitle.reject"), but I always end up with a empty slice.

Get config values from environment variables

It is common to use environment variables in container systems as docker to configure settings. It would be great if viper would handle this too:

Defaults -> Environment Variables -> Settings Files -> Command Options

PFlag in PersistentFlags() being ignored

I'm having a bit of trouble between viper and cobra... I'm defining a "log-level" variable as a persistent flag on the root command, and despite binding it in viper it's being ignored. Here's my code snippet:

// logging
CmdTellusRoot.PersistentFlags().String("log-level", "info", "verbosity level for logs")
viper.BindPFlag("log-level", CmdTellusRoot.PersistentFlags().Lookup("log-level"))
viper.BindEnv("log-level")

That's the last thing in init, and I'm not setting things manually anywhere. The environment variable isn't set either. To be specific, when I call viper.GetString("log-level") I always get "info", even if I'm passing "debug" in the flags.

Proposal for materialized paths

I've been working on reconciling #15 with the tip of master. The approach can work, but it has an issue which might lead to performance degradation for large configurations and complicate feature implementation. The index has to be rebuilt on each call to find() since there is no way to keep it up to date and preserve the config source hierarchy. For example, when a value is set for whatever reason (reading in file, pflag, env.), there is no clean way to check if the key to that value should become the new value of the index since all sources share the same index map. So indexing happens for every find() call and involves layering the configs via AllSettings() in order to get the proper, prioritized, structure.

I think that this can be improved in the following way:

  1. Create a config source type which holds both the map of values and the flat index to that map.
  2. Extract all source specific logic from the Viper type and attach it to a specialized config source type (e.g. RemoteConfig, EnvConfig, etc).
  3. In the Viper type, maintain a slice of config sources, sorted for priority.

This allows for incremental index update since each specific index can be set as appropriate and then traversed in priority as needed.
Furthermore, the refactoring of the config sources should help avoid mistakes in config priority as this will be set only once (similar to the issue that #44 fixed).
Lastly, this should make new feature implementation easier in the future - e.g., setting custom priority for config sources, for example making Consul the primary source, and local environment the fallback.

Here is a pseudocode to illustrate:

type Viper struct {
    [...]
    priority []string
    sources map[string]ConfigSource
    [...]
}

func New() *Viper {
    v.sources = map[string]{
        "flags": PFlagSource{},
        "env": EnvSource{},
        "config": FileSource{},
        [...]
    }
}

type ConfigSource interface {
    Find(key string) interface{}
    Set(key string, val interface{})
    [...]
}

type FileSource struct {
    index map[string]interface{}
    config map[string]interface{}
}

This is a fairly large refactor, but it should be completely backwards-compatible, fix the issues with using a shared index on the configs, and make maintenance and future development easier. Working on a prototype, will update this issue with the PR when ready.

viper.Reset() can longer be called from test code

We have a number of tests that depend on viper.Reset() to restore viper's state between tests. Since Reset() got moved to viper_test.go, though, we are no longer able to do that. I thought I remembered some documentation somewhere even suggesting that Reset() could be used in tests but it's possible I'm imagining that. Anyway, having access to that function in our tests would be super helpful.

Optionally strip comments in JSON

I'm working on my first Go project. Our configuration is part configuration files (generated and maintained by humans), and part generated by code on the server and retrieved by clients. For the human part, I'd favor YAML or TOML (or HOCON which I use in the JVM world), but generating the config in code is much easier in JSON, and we would prefer to use the same format for both.

It would make things much easier if viper supported an option for stripping comments in JSON configuration files. Douglas Crockford actually suggests this approach:

Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.