example_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package docopt
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func ExampleParseArgs() {
  7. usage := `Usage:
  8. example tcp [<host>...] [--force] [--timeout=<seconds>]
  9. example serial <port> [--baud=<rate>] [--timeout=<seconds>]
  10. example --help | --version`
  11. // Parse the command line `example tcp 127.0.0.1 --force`
  12. argv := []string{"tcp", "127.0.0.1", "--force"}
  13. opts, _ := ParseArgs(usage, argv, "0.1.1rc")
  14. // Sort the keys of the options map
  15. var keys []string
  16. for k := range opts {
  17. keys = append(keys, k)
  18. }
  19. sort.Strings(keys)
  20. // Print the option keys and values
  21. for _, k := range keys {
  22. fmt.Printf("%9s %v\n", k, opts[k])
  23. }
  24. // Output:
  25. // --baud <nil>
  26. // --force true
  27. // --help false
  28. // --timeout <nil>
  29. // --version false
  30. // <host> [127.0.0.1]
  31. // <port> <nil>
  32. // serial false
  33. // tcp true
  34. }
  35. func ExampleOpts_Bind() {
  36. usage := `Usage:
  37. example tcp [<host>...] [--force] [--timeout=<seconds>]
  38. example serial <port> [--baud=<rate>] [--timeout=<seconds>]
  39. example --help | --version`
  40. // Parse the command line `example serial 443 --baud=9600`
  41. argv := []string{"serial", "443", "--baud=9600"}
  42. opts, _ := ParseArgs(usage, argv, "0.1.1rc")
  43. var conf struct {
  44. Tcp bool
  45. Serial bool
  46. Host []string
  47. Port int
  48. Force bool
  49. Timeout int
  50. Baud int
  51. }
  52. opts.Bind(&conf)
  53. if conf.Serial {
  54. fmt.Printf("port: %d, baud: %d", conf.Port, conf.Baud)
  55. }
  56. // Output:
  57. // port: 443, baud: 9600
  58. }