Skip to content

Instantly share code, notes, and snippets.

@cdornsife
Last active July 25, 2017 17:12
Show Gist options
  • Save cdornsife/bbc7c61c0ec6da249e9e3654ee5cb42c to your computer and use it in GitHub Desktop.
Save cdornsife/bbc7c61c0ec6da249e9e3654ee5cb42c to your computer and use it in GitHub Desktop.
Handy code to implement string map for pflag
package app
import (
"fmt"
"strings"
)
// See: https://github.com/spf13/pflag/issues/129
// $ mycommand --string-map-option "a=b,c=d"
type StringMap struct {
Values []map[string][]string
}
// Implement the flag.Value interface
func (s *StringMap) Set(value string) error {
allValues := strings.Split(value, ",")
stringMap := make(map[string][]string, len(allValues))
for _, arg := range strings.Split(value, ",") {
x := strings.Split(arg, "=")
if len(x) < 2 {
if arg == "" {
arg = "empty"
}
return fmt.Errorf("Incorrect key=value format for %s", arg)
}
stringMap[x[0]] = append(stringMap[x[0]], x[1])
}
s.Values = append(s.Values, stringMap)
return nil
}
func (s *StringMap) String() string {
return fmt.Sprintf("%v", *s)
}
func (s *StringMap) Type() string {
return fmt.Sprintf("%T", s)
}
func (s *StringMap) Usage() string {
return "\"a=1,a=2,a=3,b=4,c=5\" returns map[string{key}][]string{values} "
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment