Source file src/flag/example_flagset_test.go

     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  }
    58  

View as plain text