|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/containeroo/dynflags" |
| 12 | + flag "github.com/spf13/pflag" |
| 13 | +) |
| 14 | + |
| 15 | +// Example version string |
| 16 | +var version = "v1.2.3" |
| 17 | + |
| 18 | +// HelpRequested is a custom error to indicate the user requested help or version info. |
| 19 | +type HelpRequested struct { |
| 20 | + Message string |
| 21 | +} |
| 22 | + |
| 23 | +func (e *HelpRequested) Error() string { |
| 24 | + return e.Message |
| 25 | +} |
| 26 | + |
| 27 | +// Is checks if the target is a HelpRequested error. |
| 28 | +func (e *HelpRequested) Is(target error) bool { |
| 29 | + _, ok := target.(*HelpRequested) |
| 30 | + return ok |
| 31 | +} |
| 32 | + |
| 33 | +// parseFlags orchestrates parsing both global flags (with pflag) |
| 34 | +// and dynamic flags (with dynflags). It returns any error that |
| 35 | +// indicates parsing failed, or HelpRequested for help/version output. |
| 36 | +func parseFlags(args []string, version string, output io.Writer) (*flag.FlagSet, *dynflags.DynFlags, error) { |
| 37 | + // 1. Setup the global pflag FlagSet |
| 38 | + flagSet := setupGlobalFlags() |
| 39 | + flagSet.SetOutput(output) // direct usage output here if needed |
| 40 | + |
| 41 | + // 2. Setup dynamic flags |
| 42 | + dynFlags := setupDynamicFlags() |
| 43 | + dynFlags.SetOutput(output) |
| 44 | + dynFlags.SortFlags = true |
| 45 | + |
| 46 | + // 3. Provide custom usage that prints both global and dynamic flags |
| 47 | + setupUsage(flagSet, dynFlags) |
| 48 | + |
| 49 | + // 4. Parse the dynamic flags first so we can separate known vs. unknown arguments |
| 50 | + if err := dynFlags.Parse(args); err != nil { |
| 51 | + return nil, nil, fmt.Errorf("error parsing dynamic flags: %w", err) |
| 52 | + } |
| 53 | + |
| 54 | + // Unknown arguments might be pflag or truly unrecognized |
| 55 | + unknownArgs := dynFlags.UnknownArgs() |
| 56 | + |
| 57 | + // 5. Parse pflag (the known global flags) |
| 58 | + if err := flagSet.Parse(unknownArgs); err != nil { |
| 59 | + return nil, nil, fmt.Errorf("error parsing global flags: %w", err) |
| 60 | + } |
| 61 | + |
| 62 | + // 6. Handle special flags for help and version |
| 63 | + if err := handleSpecialFlags(flagSet, version); err != nil { |
| 64 | + return nil, nil, err |
| 65 | + } |
| 66 | + |
| 67 | + return flagSet, dynFlags, nil |
| 68 | +} |
| 69 | + |
| 70 | +// setupGlobalFlags defines global flags (pflag) for the application |
| 71 | +func setupGlobalFlags() *flag.FlagSet { |
| 72 | + flagSet := flag.NewFlagSet("advancedExample", flag.ContinueOnError) |
| 73 | + flagSet.SortFlags = false |
| 74 | + |
| 75 | + // Some generic global flags: |
| 76 | + flagSet.Bool("version", false, "Show version and exit.") |
| 77 | + flagSet.BoolP("help", "h", false, "Show help.") |
| 78 | + flagSet.Duration("default-interval", 2*time.Second, "Default interval between checks.") |
| 79 | + return flagSet |
| 80 | +} |
| 81 | + |
| 82 | +// setupDynamicFlags defines dynamic flags for HTTP, ICMP, and TCP as an example |
| 83 | +func setupDynamicFlags() *dynflags.DynFlags { |
| 84 | + dyn := dynflags.New(dynflags.ContinueOnError) |
| 85 | + dyn.Epilog("For more information, see https://github.com/containeroo/dynflags") |
| 86 | + dyn.SortGroups = true |
| 87 | + dyn.SortFlags = true |
| 88 | + |
| 89 | + // HTTP group |
| 90 | + http := dyn.Group("http") |
| 91 | + http.String("name", "", "Name of the HTTP checker") |
| 92 | + http.String("method", "GET", "HTTP method to use") |
| 93 | + http.String("address", "", "HTTP target URL") |
| 94 | + http.Duration("interval", 1*time.Second, "Time between HTTP requests (overrides --default-interval if set)") |
| 95 | + http.StringSlices("header", nil, "HTTP headers to send") |
| 96 | + http.Bool("allow-duplicate-headers", false, "Allow duplicate HTTP headers") |
| 97 | + http.String("expected-status-codes", "200", "Expected HTTP status codes") |
| 98 | + http.Bool("skip-tls-verify", false, "Skip TLS verification") |
| 99 | + http.Duration("timeout", 2*time.Second, "Timeout for HTTP requests") |
| 100 | + |
| 101 | + // ICMP group |
| 102 | + icmp := dyn.Group("icmp") |
| 103 | + icmp.String("name", "", "Name of the ICMP checker") |
| 104 | + icmp.String("address", "", "ICMP target address") |
| 105 | + icmp.Duration("interval", 1*time.Second, "Time between ICMP requests (overrides --default-interval if set)") |
| 106 | + icmp.Duration("read-timeout", 2*time.Second, "Timeout for ICMP read") |
| 107 | + icmp.Duration("write-timeout", 2*time.Second, "Timeout for ICMP write") |
| 108 | + |
| 109 | + // TCP group |
| 110 | + tcp := dyn.Group("tcp") |
| 111 | + tcp.String("name", "", "Name of the TCP checker") |
| 112 | + tcp.String("address", "", "TCP target address") |
| 113 | + tcp.Duration("interval", 1*time.Second, "Time between TCP requests (overrides --default-interval if set)") |
| 114 | + tcp.Duration("timeout", 2*time.Second, "Timeout for TCP connection") |
| 115 | + |
| 116 | + return dyn |
| 117 | +} |
| 118 | + |
| 119 | +// setupUsage sets a custom usage function that prints both pflag and dynflags usage. |
| 120 | +func setupUsage(flagSet *flag.FlagSet, dynFlags *dynflags.DynFlags) { |
| 121 | + flagSet.Usage = func() { |
| 122 | + fmt.Fprintf(flagSet.Output(), "Usage: %s [GLOBAL FLAGS...] [DYNAMIC FLAGS...]\n", flagSet.Name()) |
| 123 | + fmt.Fprintln(flagSet.Output(), "\nGlobal Flags:") |
| 124 | + flagSet.PrintDefaults() |
| 125 | + |
| 126 | + fmt.Fprintln(flagSet.Output(), "\nDynamic Flags:") |
| 127 | + dynFlags.PrintDefaults() |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +// handleSpecialFlags checks if --help or --version was requested. |
| 132 | +func handleSpecialFlags(flagSet *flag.FlagSet, versionStr string) error { |
| 133 | + helpFlag := flagSet.Lookup("help") |
| 134 | + if helpFlag != nil && helpFlag.Value.String() == "true" { |
| 135 | + // Capture usage output into a buffer, then return a HelpRequested error. |
| 136 | + buffer := &bytes.Buffer{} |
| 137 | + flagSet.SetOutput(buffer) |
| 138 | + flagSet.Usage() |
| 139 | + return &HelpRequested{Message: buffer.String()} |
| 140 | + } |
| 141 | + |
| 142 | + versionFlag := flagSet.Lookup("version") |
| 143 | + if versionFlag != nil && versionFlag.Value.String() == "true" { |
| 144 | + return &HelpRequested{Message: fmt.Sprintf("%s version %s\n", flagSet.Name(), versionStr)} |
| 145 | + } |
| 146 | + |
| 147 | + return nil |
| 148 | +} |
| 149 | + |
| 150 | +// main is our entry point, showing how to parse and then use the flags. |
| 151 | +func main() { |
| 152 | + // We'll pretend our arguments are from the CLI; replace os.Args[1:] in real usage. |
| 153 | + args := []string{ |
| 154 | + "--http.default.name", "HTTP Checker Default", |
| 155 | + "--http.default.address", "default.com:80", |
| 156 | + "--http.other.name", "HTTP Checker Other", |
| 157 | + "--http.other.address", "other.com:443", |
| 158 | + "--http.other.method", "POST", |
| 159 | + "--icmp.custom.address", "8.8.4.4", |
| 160 | + "--tcp.testing.address", "example.com:443", |
| 161 | + "--default-interval=5s", // pflag |
| 162 | + // "--unknownArg", "someValue", // see how it's handled by dynflags |
| 163 | + } |
| 164 | + |
| 165 | + // Optionally redirect usage/errors to something other than os.Stderr if desired |
| 166 | + output := os.Stdout |
| 167 | + |
| 168 | + // Parse everything |
| 169 | + flagSet, dynFlags, err := parseFlags(args, version, output) |
| 170 | + if err != nil { |
| 171 | + // If the user requested help or version, print the message and exit |
| 172 | + var hr *HelpRequested |
| 173 | + if errors.As(err, &hr) { |
| 174 | + fmt.Fprint(output, hr.Message) |
| 175 | + return |
| 176 | + } |
| 177 | + |
| 178 | + fmt.Fprintf(output, "Failed to parse flags: %v\n", err) |
| 179 | + os.Exit(1) |
| 180 | + } |
| 181 | + |
| 182 | + // If we got here, parse succeeded. Let's show what we got. |
| 183 | + |
| 184 | + // 1. Print global flags |
| 185 | + fmt.Println("=== Global Flags ===") |
| 186 | + defaultInterval, _ := flagSet.GetDuration("default-interval") |
| 187 | + fmt.Printf("default-interval: %v\n", defaultInterval) |
| 188 | + |
| 189 | + // 2. Print dynamic flags |
| 190 | + parsedGroups := dynFlags.Parsed() |
| 191 | + |
| 192 | + fmt.Println("\n=== Dynamic Flags ===") |
| 193 | + for groupName, identifiers := range parsedGroups.Groups() { |
| 194 | + fmt.Printf("Group: %s\n", groupName) |
| 195 | + for identifier, pg := range identifiers { |
| 196 | + fmt.Printf(" Identifier: %s\n", identifier) |
| 197 | + for flagKey, value := range pg.Values { |
| 198 | + fmt.Printf(" %s: %v\n", flagKey, value) |
| 199 | + } |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + fmt.Println("\nDone!") |
| 204 | +} |
0 commit comments