Can command line flags in Go be set to mandatory?

前端 未结 7 1465
-上瘾入骨i
-上瘾入骨i 2021-02-05 00:04

Is there a way how to set that certain flags are mandatory, or do I have to check for their presence on my own?

7条回答
  •  名媛妹妹
    2021-02-05 00:21

    As already mentioned, the flag package does not provide this feature directly and usually you can (and should) be able to provide a sensible default. For cases where you only need a small number of explicit arguments (e.g. an input and output filename) you could use positional arguments (e.g. after flag.Parse() check that flag.NArg()==2 and then input, output := flag.Arg(0), flag.Arg(1)).

    If however, you have a case where this isn't sensible; say a few integer flags you want to accept in any order, where any integer value is reasonable, but no default is. Then you can use the flag.Visit function to check if the flags you care about were explicitly set or not. I think this is the only way to tell if a flag was explicitly set to it's default value (not counting a custom flag.Value type with a Set implementation that kept state).

    For example, perhaps something like:

        required := []string{"b", "s"}
        flag.Parse()
    
        seen := make(map[string]bool)
        flag.Visit(func(f *flag.Flag) { seen[f.Name] = true })
        for _, req := range required {
            if !seen[req] {
                // or possibly use `log.Fatalf` instead of:
                fmt.Fprintf(os.Stderr, "missing required -%s argument/flag\n", req)
                os.Exit(2) // the same exit code flag.Parse uses
            }
        }
    

    Playground

    This would produce an error if either the "-b" or "-s" flag was not explicitly set.

提交回复
热议问题