Documentation:(issue_786) Add docs for flag validation
This commit is contained in:
parent
8ea10b85ca
commit
31487e73a3
@ -596,3 +596,51 @@ The precedence for flag value sources is as follows (highest to lowest):
|
||||
0. Environment variable (if specified)
|
||||
0. Configuration file (if specified)
|
||||
0. Default defined on the flag
|
||||
|
||||
#### Flag Actions
|
||||
|
||||
Handlers can be registered per flag which are triggered after a flag has been processed.
|
||||
This can be used for a variety of purposes, one of which is flag validation
|
||||
|
||||
<!-- {
|
||||
"args": ["--port 70000"],
|
||||
"output": "Flag port value 70000 out of range[0-65535]"
|
||||
} -->
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := &cli.App{
|
||||
Flags: []cli.Flag{
|
||||
&cli.IntFlag{
|
||||
Name: "port",
|
||||
Usage: "Use a randomized port",
|
||||
Value: 0,
|
||||
DefaultText: "random",
|
||||
Action: func(ctx *cli.Context, v int) error {
|
||||
if v >= 65536 {
|
||||
return fmt.Errorf("Flag port value %v out of range[0-65535]", v)
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Will result in help output like:
|
||||
|
||||
```
|
||||
Flag port value 70000 out of range[0-65535]
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user