func parseFlags() options {
    var opt options
    fs := setupFlags(&opt)
    fs.Parse(os.Args[1:])
    verifyFlags(&opt, fs)
    return opt
}
Parse the command line options, validate them, and process them
further (e.g. Initialize more complex structs) if need be.
package main
import (
    "strings"
    "flag"
    "fmt"
    "os"
)
var (
    CommandLineHelpUsage = `gospec [-v] [-test=PATTERN] [ROOT [PATTERN ...]]`
    CommandLineHelpFooter = `Spec files must end with a suffix "_spec.go".`
)
type options struct {
    Root        string
    TestPattern string
    SpecPattern string
    Verbose     bool
}
func setupFlags(opt *options) *flag.FlagSet {
    fs := flag.NewFlagSet("gospec", flag.ExitOnError)
    fs.BoolVar(&(opt.Verbose), "v", false, "Verbose program output.")
    fs.StringVar(&(opt.Root), "root", "./spec", "Directory containing spec files.")
    fs.StringVar(&(opt.TestPattern), "test", ".*", "Regexp matching tests to run.")
    fs.StringVar(&(opt.SpecPattern), "spec", ".*", "Regexp matching tests to run.")
    setupUsage(fs)
    return fs
}
func verifyFlags(opt *options, fs *flag.FlagSet) {
    args := fs.Args()
    if len(args) > 0 {
        opt.Root = args[0]
        args = args[1:]
    }
    if len(args) > 0 {
        patterns := make([]string, len(args))
        for i := range args {
            patterns[i] = fmt.Sprintf("(%s)", args[i])
        }
        opt.SpecPattern = strings.Join(patterns, "|")
    }
}
func PrintHelp() {
    fs := setupFlags(&options{})
    fs.Usage()
}
func setupUsage(fs *flag.FlagSet) {
    printNonEmpty := func(s string) {
        if s != "" {
            fmt.Fprintf(os.Stderr, "%s\n", s)
        }
    }
    tmpUsage := fs.Usage
    fs.Usage = func() {
        printNonEmpty(CommandLineHelpUsage)
        tmpUsage()
        printNonEmpty(CommandLineHelpFooter)
    }
}