0

I have a project that using package flag to read the argv(parameter), it'll print the default settings when no parameter is given:

func initFlag() {
    path := flag.String("F", "store_server.conf", "config file path")
    v := flag.Bool("V", false, "print version")
    flag.Parse()

    if flag.NFlag() == 0 {
        flag.PrintDefaults()
        os.Exit(0)
    }

    fmt.Println(*path, *v)
}

func main() {
    initFlag() // initialize flag and load configure file

    select{}
}

Here comes the execution results:

vinllen@ ~$ go run main.go
  -F string
        config file path (default "store_server.conf")
  -V    print version

But when my code includes other package like glog, the PrintDefaults function will show more settings including glog flag:

  -F string
        config file path (default "store_server.conf")
  -V    print version
  -alsologtostderr
        log to standard error as well as files
  -log_backtrace_at value
        when logging hits line file:N, emit a stack trace
  -log_dir string
        If non-empty, write log files in this directory
  -logtostderr
        log to standard error instead of files
  -stderrthreshold value
        logs at or above this threshold go to stderr
  -v value
        log level for V logs
  -vmodule value
        comma-separated list of pattern=N settings for file-filtered logging

The only two settings I needed are -F and -V, how to delete the others?

vinllen
  • 1,369
  • 2
  • 18
  • 36

1 Answers1

1

You need to use a new FlagSet instead of the default one:

package main

import (
    "flag"
    "github.com/golang/glog"
    "os"
)

func initFlag() {
    flags := flag.NewFlagSet("myFlagSet", 0)
    path := flags.String("F", "store_server.conf", "config file path")
    v := flags.Bool("V", false, "print version")
    flags.Parse(os.Args[1:])

    if flags.NFlag() == 0 {
        if len(os.Args) == 0 {
            flags.PrintDefaults()
            os.Exit(0)
        }
    }

    glog.Info(*path, *v)
}

func main() {
    initFlag() // initialize flag and load configure file
    select {}
}

The second argument to NewFlagSet is the error handling. See here for more details.

When you call flag.someMethod() directly, it uses a default, shared, flag set. If you create a new one, it will be empty.

rofls
  • 4,993
  • 3
  • 27
  • 37
  • it'll print double times when call `go run main.go -F` – vinllen Apr 19 '18 at 08:00
  • @vinllen I updated the answer by checking the argument length to prevent that. It's because it prints the help message when the flags are set incorrectly, and `flags.NFlag()` counts the number of *set* flags. So, if it's not set, it will print the help message. However also the flag was set improperly, which produces the default help response. Hence we got it twice. – rofls Apr 19 '18 at 08:16