1
- // Copyright 2020 The Go Authors. All rights reserved.
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
2
// Use of this source code is governed by a BSD-style
3
3
// license that can be found in the LICENSE file.
4
4
@@ -11,18 +11,25 @@ import (
11
11
)
12
12
13
13
func ExampleFlagSet () {
14
+
14
15
start := func (args []string ) {
16
+ // A real program (not an example) would use flag.ExitOnError.
15
17
fs := flag .NewFlagSet ("start" , flag .ContinueOnError )
16
- addr := fs .String ("address" , ":8080" , "`address` to listen on" )
17
- fs .Parse (args )
18
+ addr := fs .String ("addr" , ":8080" , "`address` to listen on" )
19
+ if err := fs .Parse (args ); err != nil {
20
+ fmt .Printf ("error: %s" , err )
21
+ return
22
+ }
18
23
fmt .Printf ("starting server on %s\n " , * addr )
19
24
}
20
25
21
26
stop := func (args []string ) {
22
- // On regular program use `flag.ExitOnError`.
23
27
fs := flag .NewFlagSet ("stop" , flag .ContinueOnError )
24
28
timeout := fs .Duration ("timeout" , time .Second , "stop timeout in `seconds`" )
25
- fs .Parse (args )
29
+ if err := fs .Parse (args ); err != nil {
30
+ fmt .Printf ("error: %s" , err )
31
+ return
32
+ }
26
33
fmt .Printf ("stopping server (timeout=%v)\n " , * timeout )
27
34
}
28
35
@@ -35,16 +42,16 @@ func ExampleFlagSet() {
35
42
stop (subArgs )
36
43
default :
37
44
fmt .Printf ("error: unknown command - %q\n " , args [1 ])
38
- // On regular main print to ` os.Stderr` and exit the program with non-zero value.
45
+ // On a real program (not an example) print to os.Stderr and exit the program with non-zero value.
39
46
}
40
47
}
41
48
42
- main ([]string {"httpd" , "start" , "-address " , ":9999" })
49
+ main ([]string {"httpd" , "start" , "-addr " , ":9999" })
43
50
main ([]string {"httpd" , "stop" })
44
- main ([]string {"http" , "info " })
51
+ main ([]string {"http" , "start" , "-log-level" , "verbose " })
45
52
46
53
// Output:
47
54
// starting server on :9999
48
55
// stopping server (timeout=1s)
49
- // error: unknown command - "info"
56
+ // error: flag provided but not defined: -log-level
50
57
}
0 commit comments