Skip to content

Instantly share code, notes, and snippets.

@koyo-miyamura
Last active June 29, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koyo-miyamura/86db81e04237c6c4f5bad4a2f93a31f1 to your computer and use it in GitHub Desktop.
Save koyo-miyamura/86db81e04237c6c4f5bad4a2f93a31f1 to your computer and use it in GitHub Desktop.
FlagSetのサンプル
package main
import (
"errors"
"flag"
"fmt"
"os"
)
var (
h1 string
h2 string
flagSet *flag.FlagSet
flagSet2 *flag.FlagSet
)
func init() {
flagSet = flag.NewFlagSet("hoge1", flag.ExitOnError)
flagSet.StringVar(&h1, "foo", "", "sample hoge")
flagSet2 = flag.NewFlagSet("hoge2", flag.ExitOnError)
flagSet2.StringVar(&h2, "foo", "", "sample hoge")
}
func main() {
subCommand := os.Args[1]
if err := parseFlagSet(subCommand); err != nil {
fmt.Println(err)
os.Exit(2)
}
if h1 != "" {
fmt.Printf("hoge1 %s\n", h1)
}
if h2 != "" {
fmt.Printf("hoge2 %s\n", h2)
}
}
func parseFlagSet(subCommand string) error {
switch subCommand {
case "hoge1":
return flagSet.Parse(os.Args[2:])
case "hoge2":
return flagSet2.Parse(os.Args[2:])
default:
return errors.New("error parse FlagSet")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment