Improve documentation for flags

See #329
This commit is contained in:
Brad Peabody 2017-07-22 22:26:21 -07:00 committed by Anthony Fok
parent 9766537120
commit 04691bc570

View file

@ -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
... ...
} }
``` ```