Skip to content

Commit 959b3fd

Browse files
tebekagopherbot
authored andcommitted
flag: add FlagSet example
Add an example for using FlagSet. Fixes #36307 Change-Id: I0bf5805bd836a4f2e9632aafe22dc3eeb1164dcd GitHub-Last-Rev: 79e5304 GitHub-Pull-Request: #64443 Reviewed-on: https://go-review.googlesource.com/c/go/+/545736 Auto-Submit: Ian Lance Taylor <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Dmitri Shuralyov <[email protected]> Reviewed-by: Christopher Taylor <[email protected]> Reviewed-by: Carlos Amedee <[email protected]> Reviewed-by: Rob Pike <[email protected]>
1 parent 6948b4d commit 959b3fd

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/flag/example_flagset_test.go

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Copyright 2023 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package flag_test
6+
7+
import (
8+
"flag"
9+
"fmt"
10+
"time"
11+
)
12+
13+
func ExampleFlagSet() {
14+
15+
start := func(args []string) {
16+
// A real program (not an example) would use flag.ExitOnError.
17+
fs := flag.NewFlagSet("start", flag.ContinueOnError)
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+
}
23+
fmt.Printf("starting server on %s\n", *addr)
24+
}
25+
26+
stop := func(args []string) {
27+
fs := flag.NewFlagSet("stop", flag.ContinueOnError)
28+
timeout := fs.Duration("timeout", time.Second, "stop timeout duration")
29+
if err := fs.Parse(args); err != nil {
30+
fmt.Printf("error: %s", err)
31+
return
32+
}
33+
fmt.Printf("stopping server (timeout=%v)\n", *timeout)
34+
}
35+
36+
main := func(args []string) {
37+
subArgs := args[2:] // Drop program name and command.
38+
switch args[1] {
39+
case "start":
40+
start(subArgs)
41+
case "stop":
42+
stop(subArgs)
43+
default:
44+
fmt.Printf("error: unknown command - %q\n", args[1])
45+
// In a real program (not an example) print to os.Stderr and exit the program with non-zero value.
46+
}
47+
}
48+
49+
main([]string{"httpd", "start", "-addr", ":9999"})
50+
main([]string{"httpd", "stop"})
51+
main([]string{"http", "start", "-log-level", "verbose"})
52+
53+
// Output:
54+
// starting server on :9999
55+
// stopping server (timeout=1s)
56+
// error: flag provided but not defined: -log-level
57+
}

0 commit comments

Comments
 (0)