example_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2012 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. // These examples demonstrate more intricate uses of the flag package.
  5. package pflag_test
  6. import (
  7. "errors"
  8. "fmt"
  9. "strings"
  10. "time"
  11. flag "github.com/spf13/pflag"
  12. )
  13. // Example 1: A single string flag called "species" with default value "gopher".
  14. var species = flag.String("species", "gopher", "the species we are studying")
  15. // Example 2: A flag with a shorthand letter.
  16. var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher")
  17. // Example 3: A user-defined flag type, a slice of durations.
  18. type interval []time.Duration
  19. // String is the method to format the flag's value, part of the flag.Value interface.
  20. // The String method's output will be used in diagnostics.
  21. func (i *interval) String() string {
  22. return fmt.Sprint(*i)
  23. }
  24. func (i *interval) Type() string {
  25. return "interval"
  26. }
  27. // Set is the method to set the flag value, part of the flag.Value interface.
  28. // Set's argument is a string to be parsed to set the flag.
  29. // It's a comma-separated list, so we split it.
  30. func (i *interval) Set(value string) error {
  31. // If we wanted to allow the flag to be set multiple times,
  32. // accumulating values, we would delete this if statement.
  33. // That would permit usages such as
  34. // -deltaT 10s -deltaT 15s
  35. // and other combinations.
  36. if len(*i) > 0 {
  37. return errors.New("interval flag already set")
  38. }
  39. for _, dt := range strings.Split(value, ",") {
  40. duration, err := time.ParseDuration(dt)
  41. if err != nil {
  42. return err
  43. }
  44. *i = append(*i, duration)
  45. }
  46. return nil
  47. }
  48. // Define a flag to accumulate durations. Because it has a special type,
  49. // we need to use the Var function and therefore create the flag during
  50. // init.
  51. var intervalFlag interval
  52. func init() {
  53. // Tie the command-line flag to the intervalFlag variable and
  54. // set a usage message.
  55. flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
  56. }
  57. func Example() {
  58. // All the interesting pieces are with the variables declared above, but
  59. // to enable the flag package to see the flags defined there, one must
  60. // execute, typically at the start of main (not init!):
  61. // flag.Parse()
  62. // We don't run it here because this is not a main function and
  63. // the testing suite has already parsed the flags.
  64. }