Skip to content

Commit 7563894

Browse files
authored
Merge pull request #1544 from dearchap/issue_786
Documentation:(issue_786) Add docs for flag validation
2 parents 7732a51 + de73d1b commit 7563894

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

docs/v2/examples/flags.md

+50
Original file line numberDiff line numberDiff line change
@@ -596,3 +596,53 @@ The precedence for flag value sources is as follows (highest to lowest):
596596
0. Environment variable (if specified)
597597
0. Configuration file (if specified)
598598
0. Default defined on the flag
599+
600+
#### Flag Actions
601+
602+
Handlers can be registered per flag which are triggered after a flag has been processed.
603+
This can be used for a variety of purposes, one of which is flag validation
604+
605+
<!-- {
606+
"args": ["&#45;&#45;port","70000"],
607+
"error": "Flag port value 70000 out of range[0-65535]"
608+
} -->
609+
```go
610+
package main
611+
612+
import (
613+
"log"
614+
"os"
615+
"fmt"
616+
617+
"github.com/urfave/cli/v2"
618+
)
619+
620+
func main() {
621+
app := &cli.App{
622+
Flags: []cli.Flag{
623+
&cli.IntFlag{
624+
Name: "port",
625+
Usage: "Use a randomized port",
626+
Value: 0,
627+
DefaultText: "random",
628+
Action: func(ctx *cli.Context, v int) error {
629+
if v >= 65536 {
630+
return fmt.Errorf("Flag port value %v out of range[0-65535]", v)
631+
}
632+
return nil
633+
},
634+
},
635+
},
636+
}
637+
638+
if err := app.Run(os.Args); err != nil {
639+
log.Fatal(err)
640+
}
641+
}
642+
```
643+
644+
Will result in help output like:
645+
646+
```
647+
Flag port value 70000 out of range[0-65535]
648+
```

0 commit comments

Comments
 (0)