Can command line flags in Go be set to mandatory?

前端 未结 7 1520
-上瘾入骨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:43

    I agree with this solution but, in my case default values are usually environment values. For example,

    dsn := flag.String("dsn", os.Getenv("MYSQL_DSN"), "data source name")
    

    And in this case, I want to check if the values are set from invocation (usually local development) or environment var (prod environment).

    So with some minor modifications, it worked for my case.

    Using flag.VisitAll to check the value of all flags.

    required := []string{"b", "s"}
    flag.Parse()
    
    seen := make(map[string]bool)
    flag.VisitAll(func(f *flag.Flag) {
        if f.Value.String() != "" {
            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
        }
    }
    

    Test example in plauground

提交回复
热议问题