Skip to content

Instantly share code, notes, and snippets.

@koyo-miyamura

koyo-miyamura/main.go

Last active Jun 29, 2019
Embed
What would you like to do?
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