mirror of
https://github.com/spf13/viper
synced 2024-12-22 19:47:01 +00:00
parent
9766537120
commit
04691bc570
1 changed files with 23 additions and 2 deletions
23
README.md
23
README.md
|
@ -236,7 +236,7 @@ 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
|
it is accessed. This means you can bind as early as you want, even in an
|
||||||
`init()` function.
|
`init()` function.
|
||||||
|
|
||||||
The `BindPFlag()` method provides this functionality.
|
For individual flags, the `BindPFlag()` method provides this functionality.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
|
@ -245,6 +245,19 @@ serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
|
||||||
viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
|
viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
|
||||||
```
|
```
|
||||||
|
|
||||||
|
You can also bind an existing set of pflags (pflag.FlagSet):
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```go
|
||||||
|
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](https://github.com/spf13/pflag/) in Viper does not preclude
|
The use of [pflag](https://github.com/spf13/pflag/) in Viper does not preclude
|
||||||
the use of other packages that use the [flag](https://golang.org/pkg/flag/)
|
the use of other packages that use the [flag](https://golang.org/pkg/flag/)
|
||||||
package from the standard library. The pflag package can handle the flags
|
package from the standard library. The pflag package can handle the flags
|
||||||
|
@ -263,8 +276,16 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
|
// using standard library "flag" package
|
||||||
|
flag.Int("flagname", 1234, "help message for flagname")
|
||||||
|
|
||||||
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
|
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
|
||||||
pflag.Parse()
|
pflag.Parse()
|
||||||
|
viper.BindPFlags(pflag.CommandLine)
|
||||||
|
|
||||||
|
i := viper.GetInt("flagname") // retrieve value from viper
|
||||||
|
|
||||||
...
|
...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
Loading…
Reference in a new issue