1package main 2 3import ( 4 "errors" 5 "fmt" 6 "github.com/jessevdk/go-flags" 7 "os" 8 "strconv" 9 "strings" 10) 11 12type EditorOptions struct { 13 Input flags.Filename `short:"i" long:"input" description:"Input file" default:"-"` 14 Output flags.Filename `short:"o" long:"output" description:"Output file" default:"-"` 15} 16 17type Point struct { 18 X, Y int 19} 20 21func (p *Point) UnmarshalFlag(value string) error { 22 parts := strings.Split(value, ",") 23 24 if len(parts) != 2 { 25 return errors.New("expected two numbers separated by a ,") 26 } 27 28 x, err := strconv.ParseInt(parts[0], 10, 32) 29 30 if err != nil { 31 return err 32 } 33 34 y, err := strconv.ParseInt(parts[1], 10, 32) 35 36 if err != nil { 37 return err 38 } 39 40 p.X = int(x) 41 p.Y = int(y) 42 43 return nil 44} 45 46func (p Point) MarshalFlag() (string, error) { 47 return fmt.Sprintf("%d,%d", p.X, p.Y), nil 48} 49 50type Options struct { 51 // Example of verbosity with level 52 Verbose []bool `short:"v" long:"verbose" description:"Verbose output"` 53 54 // Example of optional value 55 User string `short:"u" long:"user" description:"User name" optional:"yes" optional-value:"pancake"` 56 57 // Example of map with multiple default values 58 Users map[string]string `long:"users" description:"User e-mail map" default:"system:system@example.org" default:"admin:admin@example.org"` 59 60 // Example of option group 61 Editor EditorOptions `group:"Editor Options"` 62 63 // Example of custom type Marshal/Unmarshal 64 Point Point `long:"point" description:"A x,y point" default:"1,2"` 65} 66 67var options Options 68 69var parser = flags.NewParser(&options, flags.Default) 70 71func main() { 72 if _, err := parser.Parse(); err != nil { 73 if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp { 74 os.Exit(0) 75 } else { 76 os.Exit(1) 77 } 78 } 79} 80