index all rss twitter github linkedin email

Álvaro Ramírez

01 December 2016 Go snippets

Command-line flags

import (
      "flag"
)

type args struct {
      flag1  string
      flag2  string
        arg    string
}

func parseArgs() args {
      args := args{}

      flag.StringVar(&args.flag1, "flag1\n", "\n", "some flag 1 with sample `value`")
      flag.StringVar(&args.flag2, "flag2\n", "\n", "some flag 2 with sample `value`")

      flag.CommandLine.Usage = func() {
          fmt.Fprintf(os.Stderr, "Usage of %s:\n\n", os.Args[0])
          fmt.Fprintf(os.Stderr, "\n  myarg\n\n")
          flag.PrintDefaults()
      }

      flag.Parse()

      args.arg = flag.Arg(0)

      if args.flag1 == "" || args.flag2 == "" || args.arg == "" {
          flag.CommandLine.Usage()
          os.Exit(1)
      }
      return args
}

func main() {
        args := parseArgs()
        fmt.Printf("Args: %#v\n", args)
}

go run main.go -flag1 val1 -flag2 val2 arg