tags:

views:

153

answers:

2

How do I nicely parse a list of program parameters and automate handling "--help" and/or "--version" (such as "program [-d value] [--abc] [FILE1]") in Go?

+5  A: 

Use the 'flag' package: http://golang.org/pkg/flag/. It doesn't do double-dash arguments, however. There isn't anything that exactly mimics GNU getopt behaviour (yet.)

Thomas Wouters
About time someone wrote one. It's been out for a whole day now.
Jurily
I'm desperately in need of an Emacs editing mode for "Go" right now. I haven't indented by hand like this for about fifteen years.
Kinopiko
@Kinopiko: Take a look at go-mode.el in the misc/emacs directory of the source code repo.
rq
+2  A: 

I made it just for you:

package main
import ("fmt"; "os")
func main() {
  for i := 1; i < len(os.Args); i++ {
    if os.Args[i] == "-help" {
      fmt.Printf ("I need somebody\n")
    }
    else if os.Args[i] == "-version" {
      fmt.Printf ("Version Zero\n")
    } else {
      fmt.Printf("arg %d: %s\n", i, os.Args[i])
    }
  }
}

Test:

$ ./8.out -help -version monkey business
I need somebody
Version Zero
arg 3: monkey
arg 4: business
Kinopiko