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!
Go configuration with fangs!
Many Go projects are built using Viper including:
go get github.com/spf13/viper
Note: Viper uses Go Modules to manage dependencies.
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:
Viper can be thought of as a registry for all of your applications configuration needs.
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:
Viper uses the following precedence order. Each item takes precedence over the item below it:
SetImportant: Viper configuration keys are case insensitive. There are ongoing discussions about making that optional.
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"})
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
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:
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")
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()
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"
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
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
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...) : errorSetEnvPrefix(string)SetEnvKeyReplacer(string...) *strings.ReplacerAllowEmptyEnv(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.
SetEnvPrefix("spf") // will be uppercased automatically
BindEnv("id")
os.Setenv("SPF_ID", "13") // typically done outside of the app
id := Get("id") // 13
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
// ...
}
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:
```go t
$ claude mcp add viper \
-- python -m otcore.mcp_server <graph>