viper

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 16, 2016 License: MIT, MIT Imports: 20 Imported by: 0

README

viper

Go configuration with fangs

What is Viper?

Viper is a complete configuration solution. Designed to work within an application to handle file based configuration and seamlessly marry that with command line flags which can also be used to control application behavior. Viper also supports retrieving configuration values from remote key/value stores. Etcd and Consul are supported.

Why Viper?

When building a modern application you don’t want to have 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 marshall a configuration file in YAML, TOML or JSON.
  2. Provide a mechanism to setDefault values for your different configuration options
  3. Provide a mechanism to setOverride 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 believes that:

  1. command line flags take precedence over options set in config files
  2. config files take precedence over options set in remote key/value stores
  3. remote key/value stores take precedence over defaults

Viper configuration keys are case insensitive.

Usage

Initialization
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
viper.ReadInConfig() // Find and read the config file
Setting Defaults
viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Indexes", map[string]string{"tag": "tags", "category": "categories"})
Setting Overrides
viper.Set("Verbose", true)
viper.Set("LogFile", LogFile)
Registering and Using Aliases
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
Getting Values
viper.GetString("logfile") // case insensitive Setting & Getting
if viper.GetBool("verbose") {
    fmt.Println("verbose enabled")
}
Remote Key/Value Store Support

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

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/xordataexchange/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
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
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
err := viper.ReadRemoteConfig()

Q & A

Q: Why not INI files?

A: Ini files are pretty awful. There’s no standard format and they are hard to validate. Viper is designed to work with YAML, TOML or JSON files. If someone really wants to add this feature, I’d be happy to merge it. It’s easy to specify which formats your application will permit.

Q: 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.

Q: Why is it called "Cobra"?

A: Is there a better name for a commander?

Documentation

Index

Constants

This section is empty.

Variables

View Source
var SupportedExts []string = []string{"json", "toml", "yaml", "yml"}

extensions Supported

View Source
var SupportedRemoteProviders []string = []string{"etcd", "consul"}

Functions

func AddConfigPath

func AddConfigPath(in string)

func AddRemoteProvider

func AddRemoteProvider(provider, endpoint, path string) error

AddRemoteProvider adds a remote configuration source. Remote Providers are searched in the order they are added. provider is a string value, "etcd" or "consul" are currently supported. endpoint is the url. etcd requires http://ip:port consul requires ip:port path is the path in the k/v store to retrieve configuration To retrieve a config file called myapp.json from /configs/myapp.json you should set path to /configs and set config name (SetConfigName()) to "myapp"

func AddSecureRemoteProvider

func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error

AddSecureRemoteProvider adds a remote configuration source. Secure Remote Providers are searched in the order they are added. provider is a string value, "etcd" or "consul" are currently supported. endpoint is the url. etcd requires http://ip:port consul requires ip:port secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg path is the path in the k/v store to retrieve configuration To retrieve a config file called myapp.json from /configs/myapp.json you should set path to /configs and set config name (SetConfigName()) to "myapp" Secure Remote Providers are implemented with github.com/xordataexchange/crypt

func AllKeys

func AllKeys() []string

func AllSettings

func AllSettings() map[string]interface{}

func AutomaticEnv

func AutomaticEnv()

Have viper check ENV variables for all keys set in config, default & flags

func BindEnv

func BindEnv(input ...string) (err error)

Binds a viper key to a ENV variable ENV variables are case sensitive If only a key is provided, it will use the env key matching the key, uppercased.

func BindPFlag

func BindPFlag(key string, flag *pflag.Flag) (err error)

Bind a specific key to a flag (as used by cobra)

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

func ConfigFileUsed

func ConfigFileUsed() string

func Debug

func Debug()

func Get

func Get(key string) interface{}

Get returns an interface.. Must be typecast or used by something that will typecast

func GetBool

func GetBool(key string) bool

func GetFloat64

func GetFloat64(key string) float64

func GetInt

func GetInt(key string) int

func GetString

func GetString(key string) string

func GetStringMap

func GetStringMap(key string) map[string]interface{}

func GetStringMapString

func GetStringMapString(key string) map[string]string

func GetStringSlice

func GetStringSlice(key string) []string

func GetTime

func GetTime(key string) time.Time

func InConfig

func InConfig(key string) bool

func IsSet

func IsSet(key string) bool

func Marshal

func Marshal(rawVal interface{}) error

Marshals the config into a Struct

func MarshalKey

func MarshalKey(key string, rawVal interface{}) error

Takes a single key and marshals it into a Struct

func MarshallReader

func MarshallReader(in io.Reader, c map[string]interface{})

func ReadInConfig

func ReadInConfig() error

Viper will discover and load the configuration file from disk and key/value stores, searching in one of the defined paths.

func ReadRemoteConfig

func ReadRemoteConfig() error

func RegisterAlias

func RegisterAlias(alias string, key string)

Aliases provide another accessor for the same key. This enables one to change a name without breaking the application

func Reset

func Reset()

func Set

func Set(key string, value interface{})

The user provided value (via flag) Will be used instead of values obtained via config file, ENV, default, or key/value store

func SetConfigFile

func SetConfigFile(in string)

Explicitly define the path, name and extension of the config file Viper will use this and not check any of the config paths

func SetConfigName

func SetConfigName(in string)

Name for the config file. Does not include extension.

func SetConfigType

func SetConfigType(in string)

func SetDefault

func SetDefault(key string, value interface{})

Set the default value for this key. Default only used when no value is provided by the user via flag, config or ENV.

Types

type RemoteConfigError

type RemoteConfigError string

func (RemoteConfigError) Error

func (rce RemoteConfigError) Error() string

type UnsupportedConfigError

type UnsupportedConfigError string

func (UnsupportedConfigError) Error

func (str UnsupportedConfigError) Error() string

type UnsupportedRemoteProviderError

type UnsupportedRemoteProviderError string

func (UnsupportedRemoteProviderError) Error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL