Initialize a Go module, install a dependency
go mod init podman-27130-reproduce-arg-parse
go get github.com/spf13/pflag| . |
| package main | |
| import ( | |
| "fmt" | |
| "github.com/spf13/pflag" | |
| ) | |
| func main() { | |
| // 1. Declare the map to store the flags | |
| var config map[string]string | |
| // var config []string | |
| // 2. Define the flag | |
| // Arguments: &targetVar, flagName, defaultValue, description | |
| pflag.StringToStringVar(&config, "driver-opts", nil, "Set config values (e.g. --driver-opts key=value)") | |
| // If you want to experiment with other types | |
| // pflag.StringArrayVar(&config, "driver-opts", nil, "Set config values (e.g. --driver-opts key=value)") | |
| // pflag.StringSliceVar(&config, "driver-opts", nil, "Set config values (e.g. --driver-opts key=value)") | |
| // 3. Parse the flags | |
| pflag.Parse() | |
| // 4. Print results | |
| fmt.Println("Configuration:") | |
| for k, v := range config { | |
| fmt.Printf(" %s: %s\n", k, v) | |
| // fmt.Printf(" %d: %s\n", k, v) | |
| } | |
| } |
| ########################## | |
| # Things that don't work # | |
| ########################## | |
| go run main.go --driver-opts=list=/bin/true --driver-opts=lookup="echo \"foo bar\"" --driver-opts=store=/bin/true --driver-opts=delete=/bin/true | |
| # Configuration: | |
| # list: /bin/true | |
| # lookup: echo "foo bar | |
| # store: /bin/true | |
| # delete: /bin/true | |
| go run main.go --driver-opts=list=/bin/true --driver-opts="lookup=echo \"foo bar\"" --driver-opts=store=/bin/true --driver-opts=delete=/bin/true | |
| # Configuration: | |
| # list: /bin/true | |
| # lookup: echo "banana | |
| # store: /bin/true | |
| # delete: /bin/true | |
| go run main.go --driver-opts=list=/bin/true --driver-opts='lookup=echo "foo bar"' --driver-opts=store=/bin/true --driver-opts=delete=/bin/true | |
| # Configuration: | |
| # list: /bin/true | |
| # lookup: echo "foo bar | |
| # store: /bin/true | |
| # delete: /bin/true | |
| ############################# | |
| # Things that actually work # | |
| ############################# | |
| # 1. Adding an extra space at the end | |
| go run main.go --driver-opts=list=/bin/true --driver-opts="lookup=echo \"foo bar\" " --driver-opts=store=/bin/true --driver-opts=delete=/bin/true | |
| # Configuration: | |
| # list: /bin/true | |
| # lookup: echo "foo bar" | |
| # store: /bin/true | |
| # delete: /bin/true | |
| # Note: There is an extra space at the end of the lookup line | |
| # 2. Putting every argument in one set of single quotes, then use CSV double quote rules | |
| go run main.go --driver-opts='list=/bin/true,"lookup=echo ""foo bar""",store=/bin/true,delete=/bin/true' | |
| # Configuration: | |
| # list: /bin/true | |
| # lookup: echo "foo bar" | |
| # store: /bin/true | |
| # delete: /bin/true |