{"id":13400553,"url":"https://github.com/spf13/viper","last_synced_at":"2025-05-12T17:39:04.408Z","repository":{"id":15632497,"uuid":"18369373","full_name":"spf13/viper","owner":"spf13","description":"Go configuration with fangs","archived":false,"fork":false,"pushed_at":"2025-05-02T17:34:26.000Z","size":1624,"stargazers_count":28439,"open_issues_count":517,"forks_count":2051,"subscribers_count":252,"default_branch":"master","last_synced_at":"2025-05-05T15:08:33.496Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spf13.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-04-02T14:33:33.000Z","updated_at":"2025-05-05T14:20:04.000Z","dependencies_parsed_at":"2024-02-05T20:00:36.547Z","dependency_job_id":"f88a37bf-4dab-416c-9d23-c20a9c6fbdf3","html_url":"https://github.com/spf13/viper","commit_stats":{"total_commits":809,"total_committers":184,"mean_commits":4.396739130434782,"dds":0.6526576019777504,"last_synced_commit":"60e5c44537893d7f8c26196e7b346cac59a41df5"},"previous_names":[],"tags_count":51,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spf13%2Fviper","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spf13%2Fviper/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spf13%2Fviper/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spf13%2Fviper/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spf13","download_url":"https://codeload.github.com/spf13/viper/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253789278,"owners_count":21964649,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T19:00:53.258Z","updated_at":"2025-05-12T17:39:04.367Z","avatar_url":"https://github.com/spf13.png","language":"Go","readme":"\u003e ## Viper v2 feedback\n\u003e 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\n\u003e\n\u003e **Thank you!**\n\n![viper logo](https://github.com/user-attachments/assets/acae9193-2974-41f3-808d-2d433f5ada5e)\n\n\n[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge-flat.svg)](https://github.com/avelino/awesome-go#configuration)\n[![run on repl.it](https://repl.it/badge/github/sagikazarmark/Viper-example)](https://repl.it/@sagikazarmark/Viper-example#main.go)\n\n[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/spf13/viper/ci.yaml?branch=master\u0026style=flat-square)](https://github.com/spf13/viper/actions?query=workflow%3ACI)\n[![Join the chat at https://gitter.im/spf13/viper](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/spf13/viper?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/viper?style=flat-square)](https://goreportcard.com/report/github.com/spf13/viper)\n![Go Version](https://img.shields.io/badge/go%20version-%3E=1.23-61CFDD.svg?style=flat-square)\n[![PkgGoDev](https://pkg.go.dev/badge/mod/github.com/spf13/viper)](https://pkg.go.dev/mod/github.com/spf13/viper)\n\n**Go configuration with fangs!**\n\nMany Go projects are built using Viper including:\n\n* [Hugo](http://gohugo.io)\n* [EMC RexRay](http://rexray.readthedocs.org/en/stable/)\n* [Imgur’s Incus](https://github.com/Imgur/incus)\n* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)\n* [Docker Notary](https://github.com/docker/Notary)\n* [BloomApi](https://www.bloomapi.com/)\n* [doctl](https://github.com/digitalocean/doctl)\n* [Clairctl](https://github.com/jgsqware/clairctl)\n* [Mercure](https://mercure.rocks)\n* [Meshery](https://github.com/meshery/meshery)\n* [Bearer](https://github.com/bearer/bearer)\n* [Coder](https://github.com/coder/coder)\n* [Vitess](https://vitess.io/)\n\n\n## Install\n\n```shell\ngo get github.com/spf13/viper\n```\n\n**Note:** Viper uses [Go Modules](https://go.dev/wiki/Modules) to manage dependencies.\n\n\n## What is Viper?\n\nViper is a complete configuration solution for Go applications including [12-Factor apps](https://12factor.net/#the_twelve_factors).\nIt is designed to work within an application, and can handle all types of configuration needs\nand formats. It supports:\n\n* setting defaults\n* reading from JSON, TOML, YAML, HCL, envfile and Java properties config files\n* live watching and re-reading of config files (optional)\n* reading from environment variables\n* reading from remote config systems (etcd or Consul), and watching changes\n* reading from command line flags\n* reading from buffer\n* setting explicit values\n\nViper can be thought of as a registry for all of your applications configuration needs.\n\n\n## Why Viper?\n\nWhen building a modern application, you don’t want to worry about\nconfiguration file formats; you want to focus on building awesome software.\nViper is here to help with that.\n\nViper does the following for you:\n\n1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, INI, envfile or Java properties formats.\n2. Provide a mechanism to set default values for your different configuration options.\n3. Provide a mechanism to set override values for options specified through command line flags.\n4. Provide an alias system to easily rename parameters without breaking existing code.\n5. 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.\n\nViper uses the following precedence order. Each item takes precedence over the item below it:\n\n * explicit call to `Set`\n * flag\n * env\n * config\n * key/value store\n * default\n\n**Important:** Viper configuration keys are case insensitive.\nThere are ongoing discussions about making that optional.\n\n\n## Putting Values into Viper\n\n### Establishing Defaults\n\nA good configuration system will support default values. A default value is not\nrequired for a key, but it’s useful in the event that a key hasn't been set via\nconfig file, environment variable, remote configuration or flag.\n\nExamples:\n\n```go\nviper.SetDefault(\"ContentDir\", \"content\")\nviper.SetDefault(\"LayoutDir\", \"layouts\")\nviper.SetDefault(\"Taxonomies\", map[string]string{\"tag\": \"tags\", \"category\": \"categories\"})\n```\n\n### Reading Config Files\n\nViper requires minimal configuration so it knows where to look for config files.\nViper supports JSON, TOML, YAML, HCL, INI, envfile and Java Properties files. Viper can search multiple paths, but\ncurrently a single Viper instance only supports a single configuration file.\nViper does not default to any configuration search paths leaving defaults decision\nto an application.\n\nHere is an example of how to use Viper to search for and read a configuration file.\nNone of the specific paths are required, but at least one path should be provided\nwhere a configuration file is expected.\n\n```go\nviper.SetConfigName(\"config\") // name of config file (without extension)\nviper.SetConfigType(\"yaml\") // REQUIRED if the config file does not have the extension in the name\nviper.AddConfigPath(\"/etc/appname/\")   // path to look for the config file in\nviper.AddConfigPath(\"$HOME/.appname\")  // call multiple times to add many search paths\nviper.AddConfigPath(\".\")               // optionally look for config in the working directory\nerr := viper.ReadInConfig() // Find and read the config file\nif err != nil { // Handle errors reading the config file\n\tpanic(fmt.Errorf(\"fatal error config file: %w\", err))\n}\n```\n\nYou can handle the specific case where no config file is found like this:\n\n```go\nif err := viper.ReadInConfig(); err != nil {\n\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t// Config file not found; ignore error if desired\n\t} else {\n\t\t// Config file was found but another error was produced\n\t}\n}\n\n// Config file found and successfully parsed\n```\n\n*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`\n\n### Writing Config Files\n\nReading from config files is useful, but at times you want to store all modifications made at run time.\nFor that, a bunch of commands are available, each with its own purpose:\n\n* 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.\n* 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.\n* WriteConfigAs - writes the current viper configuration to the given filepath. Will overwrite the given file, if it exists.\n* SafeWriteConfigAs - writes the current viper configuration to the given filepath. Will not overwrite the given file, if it exists.\n\nAs 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.\n\nA small examples section:\n\n```go\nviper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'\nviper.SafeWriteConfig()\nviper.WriteConfigAs(\"/path/to/my/.config\")\nviper.SafeWriteConfigAs(\"/path/to/my/.config\") // will error since it has already been written\nviper.SafeWriteConfigAs(\"/path/to/my/.other_config\")\n```\n\n### Watching and re-reading config files\n\nViper supports the ability to have your application live read a config file while running.\n\nGone are the days of needing to restart a server to have a config take effect,\nviper powered applications can read an update to a config file while running and\nnot miss a beat.\n\nSimply tell the viper instance to watchConfig.\nOptionally you can provide a function for Viper to run each time a change occurs.\n\n**Make sure you add all of the configPaths prior to calling `WatchConfig()`**\n\n```go\nviper.OnConfigChange(func(e fsnotify.Event) {\n\tfmt.Println(\"Config file changed:\", e.Name)\n})\nviper.WatchConfig()\n```\n\n### Reading Config from io.Reader\n\nViper predefines many configuration sources such as files, environment\nvariables, flags, and remote K/V store, but you are not bound to them. You can\nalso implement your own required configuration source and feed it to viper.\n\n```go\nviper.SetConfigType(\"yaml\") // or viper.SetConfigType(\"YAML\")\n\n// any approach to require this configuration into your program.\nvar yamlExample = []byte(`\nHacker: true\nname: steve\nhobbies:\n- skateboarding\n- snowboarding\n- go\nclothing:\n  jacket: leather\n  trousers: denim\nage: 35\neyes : brown\nbeard: true\n`)\n\nviper.ReadConfig(bytes.NewBuffer(yamlExample))\n\nviper.Get(\"name\") // this would be \"steve\"\n```\n\n### Setting Overrides\n\nThese could be from a command line flag, or from your own application logic.\n\n```go\nviper.Set(\"Verbose\", true)\nviper.Set(\"LogFile\", LogFile)\nviper.Set(\"host.port\", 5899)   // set subset\n```\n\n### Registering and Using Aliases\n\nAliases permit a single value to be referenced by multiple keys\n\n```go\nviper.RegisterAlias(\"loud\", \"Verbose\")\n\nviper.Set(\"verbose\", true) // same result as next line\nviper.Set(\"loud\", true)   // same result as prior line\n\nviper.GetBool(\"loud\") // true\nviper.GetBool(\"verbose\") // true\n```\n\n### Working with Environment Variables\n\nViper has full support for environment variables. This enables 12 factor\napplications out of the box. There are five methods that exist to aid working\nwith ENV:\n\n * `AutomaticEnv()`\n * `BindEnv(string...) : error`\n * `SetEnvPrefix(string)`\n * `SetEnvKeyReplacer(string...) *strings.Replacer`\n * `AllowEmptyEnv(bool)`\n\n_When working with ENV variables, it’s important to recognize that Viper\ntreats ENV variables as case sensitive._\n\nViper provides a mechanism to try to ensure that ENV variables are unique. By\nusing `SetEnvPrefix`, you can tell Viper to use a prefix while reading from\nthe environment variables. Both `BindEnv` and `AutomaticEnv` will use this\nprefix.\n\n`BindEnv` takes one or more parameters. The first parameter is the key name, the\nrest are the name of the environment variables to bind to this key. If more than\none are provided, they will take precedence in the specified order. The name of\nthe environment variable is case sensitive. If the ENV variable name is not provided, then\nViper 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),\nit **does not** automatically add the prefix. For example if the second parameter is \"id\",\nViper will look for the ENV variable \"ID\".\n\nOne important thing to recognize when working with ENV variables is that the\nvalue will be read each time it is accessed. Viper does not fix the value when\nthe `BindEnv` is called.\n\n`AutomaticEnv` is a powerful helper especially when combined with\n`SetEnvPrefix`. When called, Viper will check for an environment variable any\ntime a `viper.Get` request is made. It will apply the following rules. It will\ncheck for an environment variable with a name matching the key uppercased and\nprefixed with the `EnvPrefix` if set.\n\n`SetEnvKeyReplacer` allows you to use a `strings.Replacer` object to rewrite Env\nkeys to an extent. This is useful if you want to use `-` or something in your\n`Get()` calls, but want your environmental variables to use `_` delimiters. An\nexample of using it can be found in `viper_test.go`.\n\nAlternatively, you can use `EnvKeyReplacer` with `NewWithOptions` factory function.\nUnlike `SetEnvKeyReplacer`, it accepts a `StringReplacer` interface allowing you to write custom string replacing logic.\n\nBy default empty environment variables are considered unset and will fall back to\nthe next configuration source. To treat empty environment variables as set, use\nthe `AllowEmptyEnv` method.\n\n#### Env example\n\n```go\nSetEnvPrefix(\"spf\") // will be uppercased automatically\nBindEnv(\"id\")\n\nos.Setenv(\"SPF_ID\", \"13\") // typically done outside of the app\n\nid := Get(\"id\") // 13\n```\n\n### Working with Flags\n\nViper has the ability to bind to flags. Specifically, Viper supports `Pflags`\nas used in the [Cobra](https://github.com/spf13/cobra) library.\n\nLike `BindEnv`, the value is not set when the binding method is called, but when\nit is accessed. This means you can bind as early as you want, even in an\n`init()` function.\n\nFor individual flags, the `BindPFlag()` method provides this functionality.\n\nExample:\n\n```go\nserverCmd.Flags().Int(\"port\", 1138, \"Port to run Application server on\")\nviper.BindPFlag(\"port\", serverCmd.Flags().Lookup(\"port\"))\n```\n\nYou can also bind an existing set of pflags (pflag.FlagSet):\n\nExample:\n\n```go\npflag.Int(\"flagname\", 1234, \"help message for flagname\")\n\npflag.Parse()\nviper.BindPFlags(pflag.CommandLine)\n\ni := viper.GetInt(\"flagname\") // retrieve values from viper instead of pflag\n```\n\nThe use of [pflag](https://github.com/spf13/pflag/) in Viper does not preclude\nthe use of other packages that use the [flag](https://golang.org/pkg/flag/)\npackage from the standard library. The pflag package can handle the flags\ndefined for the flag package by importing these flags. This is accomplished\nby a calling a convenience function provided by the pflag package called\nAddGoFlagSet().\n\nExample:\n\n```go\npackage main\n\nimport (\n\t\"flag\"\n\t\"github.com/spf13/pflag\"\n)\n\nfunc main() {\n\n\t// using standard library \"flag\" package\n\tflag.Int(\"flagname\", 1234, \"help message for flagname\")\n\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\tviper.BindPFlags(pflag.CommandLine)\n\n\ti := viper.GetInt(\"flagname\") // retrieve value from viper\n\n\t// ...\n}\n```\n\n#### Flag interfaces\n\nViper provides two Go interfaces to bind other flag systems if you don’t use `Pflags`.\n\n`FlagValue` represents a single flag. This is a very simple example on how to implement this interface:\n\n```go\ntype myFlag struct {}\nfunc (f myFlag) HasChanged() bool { return false }\nfunc (f myFlag) Name() string { return \"my-flag-name\" }\nfunc (f myFlag) ValueString() string { return \"my-flag-value\" }\nfunc (f myFlag) ValueType() string { return \"string\" }\n```\n\nOnce your flag implements this interface, you can simply tell Viper to bind it:\n\n```go\nviper.BindFlagValue(\"my-flag-name\", myFlag{})\n```\n\n`FlagValueSet` represents a group of flags. This is a very simple example on how to implement this interface:\n\n```go\ntype myFlagSet struct {\n\tflags []myFlag\n}\n\nfunc (f myFlagSet) VisitAll(fn func(FlagValue)) {\n\tfor _, flag := range flags {\n\t\tfn(flag)\n\t}\n}\n```\n\nOnce your flag set implements this interface, you can simply tell Viper to bind it:\n\n```go\nfSet := myFlagSet{\n\tflags: []myFlag{myFlag{}, myFlag{}},\n}\nviper.BindFlagValues(\"my-flags\", fSet)\n```\n\n### Remote Key/Value Store Support\n\nTo enable remote support in Viper, do a blank import of the `viper/remote`\npackage:\n\n`import _ \"github.com/spf13/viper/remote\"`\n\nViper will read a config string (as JSON, TOML, YAML, HCL or envfile) retrieved from a path\nin a Key/Value store such as etcd or Consul.  These values take precedence over\ndefault values, but are overridden by configuration values retrieved from disk,\nflags, or environment variables.\n\nViper 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`.\n\nViper uses [crypt](https://github.com/sagikazarmark/crypt) to retrieve\nconfiguration from the K/V store, which means that you can store your\nconfiguration values encrypted and have them automatically decrypted if you have\nthe correct gpg keyring.  Encryption is optional.\n\nYou can use remote configuration in conjunction with local configuration, or\nindependently of it.\n\n`crypt` has a command-line helper that you can use to put configurations in your\nK/V store. `crypt` defaults to etcd on http://127.0.0.1:4001.\n\n```bash\n$ go get github.com/sagikazarmark/crypt/bin/crypt\n$ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json\n```\n\nConfirm that your value was set:\n\n```bash\n$ crypt get -plaintext /config/hugo.json\n```\n\nSee the `crypt` documentation for examples of how to set encrypted values, or\nhow to use Consul.\n\n### Remote Key/Value Store Example - Unencrypted\n\n#### etcd\n```go\nviper.AddRemoteProvider(\"etcd\", \"http://127.0.0.1:4001\",\"/config/hugo.json\")\nviper.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\"\nerr := viper.ReadRemoteConfig()\n```\n\n#### etcd3\n```go\nviper.AddRemoteProvider(\"etcd3\", \"http://127.0.0.1:4001\",\"/config/hugo.json\")\nviper.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\"\nerr := viper.ReadRemoteConfig()\n```\n\n#### Consul\nYou need to set a key to Consul key/value storage with JSON value containing your desired config.\nFor example, create a Consul key/value store key `MY_CONSUL_KEY` with value:\n\n```json\n{\n    \"port\": 8080,\n    \"hostname\": \"myhostname.com\"\n}\n```\n\n```go\nviper.AddRemoteProvider(\"consul\", \"localhost:8500\", \"MY_CONSUL_KEY\")\nviper.SetConfigType(\"json\") // Need to explicitly set this to json\nerr := viper.ReadRemoteConfig()\n\nfmt.Println(viper.Get(\"port\")) // 8080\nfmt.Println(viper.Get(\"hostname\")) // myhostname.com\n```\n\n#### Firestore\n\n```go\nviper.AddRemoteProvider(\"firestore\", \"google-cloud-project-id\", \"collection/document\")\nviper.SetConfigType(\"json\") // Config's format: \"json\", \"toml\", \"yaml\", \"yml\"\nerr := viper.ReadRemoteConfig()\n```\n\nOf course, you're allowed to use `SecureRemoteProvider` also\n\n\n#### NATS\n\n```go\nviper.AddRemoteProvider(\"nats\", \"nats://127.0.0.1:4222\", \"myapp.config\")\nviper.SetConfigType(\"json\")\nerr := viper.ReadRemoteConfig()\n```\n\n### Remote Key/Value Store Example - Encrypted\n\n```go\nviper.AddSecureRemoteProvider(\"etcd\",\"http://127.0.0.1:4001\",\"/config/hugo.json\",\"/etc/secrets/mykeyring.gpg\")\nviper.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\"\nerr := viper.ReadRemoteConfig()\n```\n\n### Watching Changes in etcd - Unencrypted\n\n```go\n// alternatively, you can create a new viper instance.\nvar runtime_viper = viper.New()\n\nruntime_viper.AddRemoteProvider(\"etcd\", \"http://127.0.0.1:4001\", \"/config/hugo.yml\")\nruntime_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\"\n\n// read from remote config the first time.\nerr := runtime_viper.ReadRemoteConfig()\n\n// unmarshal config\nruntime_viper.Unmarshal(\u0026runtime_conf)\n\n// open a goroutine to watch remote changes forever\ngo func(){\n\tfor {\n\t\ttime.Sleep(time.Second * 5) // delay after each request\n\n\t\t// currently, only tested with etcd support\n\t\terr := runtime_viper.WatchRemoteConfig()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to read remote config: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// unmarshal new config into our runtime config struct. you can also use channel\n\t\t// to implement a signal to notify the system of the changes\n\t\truntime_viper.Unmarshal(\u0026runtime_conf)\n\t}\n}()\n```\n\n## Getting Values From Viper\n\nIn Viper, there are a few ways to get a value depending on the value’s type.\nThe following functions and methods exist:\n\n * `Get(key string) : any`\n * `GetBool(key string) : bool`\n * `GetFloat64(key string) : float64`\n * `GetInt(key string) : int`\n * `GetIntSlice(key string) : []int`\n * `GetString(key string) : string`\n * `GetStringMap(key string) : map[string]any`\n * `GetStringMapString(key string) : map[string]string`\n * `GetStringSlice(key string) : []string`\n * `GetTime(key string) : time.Time`\n * `GetDuration(key string) : time.Duration`\n * `IsSet(key string) : bool`\n * `AllSettings() : map[string]any`\n\nOne important thing to recognize is that each Get function will return a zero\nvalue if it’s not found. To check if a given key exists, the `IsSet()` method\nhas been provided.\n\nThe zero value will also be returned if the value is set, but fails to parse\nas the requested type.\n\nExample:\n```go\nviper.GetString(\"logfile\") // case-insensitive Setting \u0026 Getting\nif viper.GetBool(\"verbose\") {\n\tfmt.Println(\"verbose enabled\")\n}\n```\n### Accessing nested keys\n\nThe accessor methods also accept formatted paths to deeply nested keys. For\nexample, if the following JSON file is loaded:\n\n```json\n{\n    \"host\": {\n        \"address\": \"localhost\",\n        \"port\": 5799\n    },\n    \"datastore\": {\n        \"metric\": {\n            \"host\": \"127.0.0.1\",\n            \"port\": 3099\n        },\n        \"warehouse\": {\n            \"host\": \"198.0.0.1\",\n            \"port\": 2112\n        }\n    }\n}\n\n```\n\nViper can access a nested field by passing a `.` delimited path of keys:\n\n```go\nGetString(\"datastore.metric.host\") // (returns \"127.0.0.1\")\n```\n\nThis obeys the precedence rules established above; the search for the path\nwill cascade through the remaining configuration registries until found.\n\nFor example, given this configuration file, both `datastore.metric.host` and\n`datastore.metric.port` are already defined (and may be overridden). If in addition\n`datastore.metric.protocol` was defined in the defaults, Viper would also find it.\n\nHowever, if `datastore.metric` was overridden (by a flag, an environment variable,\nthe `Set()` method, …) with an immediate value, then all sub-keys of\n`datastore.metric` become undefined, they are “shadowed” by the higher-priority\nconfiguration level.\n\nViper can access array indices by using numbers in the path. For example:\n\n```jsonc\n{\n    \"host\": {\n        \"address\": \"localhost\",\n        \"ports\": [\n            5799,\n            6029\n        ]\n    },\n    \"datastore\": {\n        \"metric\": {\n            \"host\": \"127.0.0.1\",\n            \"port\": 3099\n        },\n        \"warehouse\": {\n            \"host\": \"198.0.0.1\",\n            \"port\": 2112\n        }\n    }\n}\n\nGetInt(\"host.ports.1\") // returns 6029\n\n```\n\nLastly, if there exists a key that matches the delimited key path, its value\nwill be returned instead. E.g.\n\n```jsonc\n{\n    \"datastore.metric.host\": \"0.0.0.0\",\n    \"host\": {\n        \"address\": \"localhost\",\n        \"port\": 5799\n    },\n    \"datastore\": {\n        \"metric\": {\n            \"host\": \"127.0.0.1\",\n            \"port\": 3099\n        },\n        \"warehouse\": {\n            \"host\": \"198.0.0.1\",\n            \"port\": 2112\n        }\n    }\n}\n\nGetString(\"datastore.metric.host\") // returns \"0.0.0.0\"\n```\n\n### Extracting a sub-tree\n\nWhen developing reusable modules, it's often useful to extract a subset of the configuration\nand pass it to a module. This way the module can be instantiated more than once, with different configurations.\n\nFor example, an application might use multiple different cache stores for different purposes:\n\n```yaml\ncache:\n  cache1:\n    max-items: 100\n    item-size: 64\n  cache2:\n    max-items: 200\n    item-size: 80\n```\n\nWe could pass the cache name to a module (eg. `NewCache(\"cache1\")`),\nbut it would require weird concatenation for accessing config keys and would be less separated from the global config.\n\nSo instead of doing that let's pass a Viper instance to the constructor that represents a subset of the configuration:\n\n```go\ncache1Config := viper.Sub(\"cache.cache1\")\nif cache1Config == nil { // Sub returns nil if the key cannot be found\n\tpanic(\"cache configuration not found\")\n}\n\ncache1 := NewCache(cache1Config)\n```\n\n**Note:** Always check the return value of `Sub`. It returns `nil` if a key cannot be found.\n\nInternally, the `NewCache` function can address `max-items` and `item-size` keys directly:\n\n```go\nfunc NewCache(v *Viper) *Cache {\n\treturn \u0026Cache{\n\t\tMaxItems: v.GetInt(\"max-items\"),\n\t\tItemSize: v.GetInt(\"item-size\"),\n\t}\n}\n```\n\nThe resulting code is easy to test, since it's decoupled from the main config structure,\nand easier to reuse (for the same reason).\n\n\n### Unmarshaling\n\nYou also have the option of Unmarshaling all or a specific value to a struct, map,\netc.\n\nThere are two methods to do this:\n\n * `Unmarshal(rawVal any) : error`\n * `UnmarshalKey(key string, rawVal any) : error`\n\nExample:\n\n```go\ntype config struct {\n\tPort int\n\tName string\n\tPathMap string `mapstructure:\"path_map\"`\n}\n\nvar C config\n\nerr := viper.Unmarshal(\u0026C)\nif err != nil {\n\tt.Fatalf(\"unable to decode into struct, %v\", err)\n}\n```\n\nIf you want to unmarshal configuration where the keys themselves contain dot (the default key delimiter),\nyou have to change the delimiter:\n\n```go\nv := viper.NewWithOptions(viper.KeyDelimiter(\"::\"))\n\nv.SetDefault(\"chart::values\", map[string]any{\n\t\"ingress\": map[string]any{\n\t\t\"annotations\": map[string]any{\n\t\t\t\"traefik.frontend.rule.type\":                 \"PathPrefix\",\n\t\t\t\"traefik.ingress.kubernetes.io/ssl-redirect\": \"true\",\n\t\t},\n\t},\n})\n\ntype config struct {\n\tChart struct{\n\t\tValues map[string]any\n\t}\n}\n\nvar C config\n\nv.Unmarshal(\u0026C)\n```\n\nViper also supports unmarshaling into embedded structs:\n\n```go\n/*\nExample config:\n\nmodule:\n    enabled: true\n    token: 89h3f98hbwf987h3f98wenf89ehf\n*/\ntype config struct {\n\tModule struct {\n\t\tEnabled bool\n\n\t\tmoduleConfig `mapstructure:\",squash\"`\n\t}\n}\n\n// moduleConfig could be in a module specific package\ntype moduleConfig struct {\n\tToken string\n}\n\nvar C config\n\nerr := viper.Unmarshal(\u0026C)\nif err != nil {\n\tt.Fatalf(\"unable to decode into struct, %v\", err)\n}\n```\n\nViper uses [github.com/go-viper/mapstructure](https://github.com/go-viper/mapstructure) under the hood for unmarshaling values which uses `mapstructure` tags by default.\n\n### Decoding custom formats\n\nA frequently requested feature for Viper is adding more value formats and decoders.\nFor example, parsing character (dot, comma, semicolon, etc) separated strings into slices.\n\nThis is already available in Viper using mapstructure decode hooks.\n\nRead more about the details in [this blog post](https://sagikazarmark.hu/blog/decoding-custom-formats-with-viper/).\n\n### Marshalling to string\n\nYou may need to marshal all the settings held in viper into a string rather than write them to a file.\nYou can use your favorite format's marshaller with the config returned by `AllSettings()`.\n\n```go\nimport (\n\tyaml \"gopkg.in/yaml.v2\"\n\t// ...\n)\n\nfunc yamlStringSettings() string {\n\tc := viper.AllSettings()\n\tbs, err := yaml.Marshal(c)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to marshal config to YAML: %v\", err)\n\t}\n\treturn string(bs)\n}\n```\n\n## Viper or Vipers?\n\nViper comes with a global instance (singleton) out of the box.\n\nAlthough it makes setting up configuration easy,\nusing it is generally discouraged as it makes testing harder and can lead to unexpected behavior.\n\nThe best practice is to initialize a Viper instance and pass that around when necessary.\n\nThe global instance _MAY_ be deprecated in the future.\nSee [#1855](https://github.com/spf13/viper/issues/1855) for more details.\n\n### Working with multiple vipers\n\nYou can also create many different vipers for use in your application. Each will\nhave its own unique set of configurations and values. Each can read from a\ndifferent config file, key value store, etc. All of the functions that viper\npackage supports are mirrored as methods on a viper.\n\nExample:\n\n```go\nx := viper.New()\ny := viper.New()\n\nx.SetDefault(\"ContentDir\", \"content\")\ny.SetDefault(\"ContentDir\", \"foobar\")\n\n//...\n```\n\nWhen working with multiple vipers, it is up to the user to keep track of the\ndifferent vipers.\n\n\n## Q \u0026 A\n\n### Why is it called “Viper”?\n\nA: Viper is designed to be a [companion](http://en.wikipedia.org/wiki/Viper_(G.I._Joe))\nto [Cobra](https://github.com/spf13/cobra). While both can operate completely\nindependently, together they make a powerful pair to handle much of your\napplication foundation needs.\n\n### Why is it called “Cobra”?\n\nIs there a better name for a [commander](http://en.wikipedia.org/wiki/Cobra_Commander)?\n\n### Does Viper support case sensitive keys?\n\n**tl;dr:** No.\n\nViper 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).\nIn order to provide the best experience when using multiple sources, the decision has been made to make all keys case insensitive.\n\nThere 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](https://github.com/spf13/viper/issues/772), but despite the initial noise, it does not seem to be requested that much.\n\nYou can vote for case sensitivity by filling out this feedback form: https://forms.gle/R6faU74qPRPAzchZ9\n\n### Is it safe to concurrently read and write to a viper?\n\nNo, 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.\n\n## Troubleshooting\n\nSee [TROUBLESHOOTING.md](TROUBLESHOOTING.md).\n\n## Development\n\n**For an optimal developer experience, it is recommended to install [Nix](https://nixos.org/download.html) and [direnv](https://direnv.net/docs/installation.html).**\n\n_Alternatively, install [Go](https://go.dev/dl/) on your computer then run `make deps` to install the rest of the dependencies._\n\nRun the test suite:\n\n```shell\nmake test\n```\n\nRun linters:\n\n```shell\nmake lint # pass -j option to run them in parallel\n```\n\nSome linter violations can automatically be fixed:\n\n```shell\nmake fmt\n```\n\n## License\n\nThe project is licensed under the [MIT License](LICENSE).\n","funding_links":[],"categories":["Go","HarmonyOS","配置","开源类库","Config","Configuration","Programming","配置管理","Go Libraries","Uncategorized","Golang Packages","Open source library","语言资源库","Command Line","others","Tools","\u003cspan id=\"组态-configuration\"\u003e组态 Configuration\u003c/span\u003e","配置管理 `配置解析库`","[Go](https://go.dev/)","Go 🐹"],"sub_categories":["Windows Manager","标准CLI","配置","Advanced Console UIs","Standard CLI","Golang","Atom Extensions","Uncategorized","Construction","go","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e","标准 CLI","Mock","高級控制台界面","Useful awesome list for Dotnet cli","高级控制台界面"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspf13%2Fviper","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspf13%2Fviper","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspf13%2Fviper/lists"}