Command line arguments
Arguments from the command line are available inside your program via the stringslice os.Args
, provided you have imported the package os
. The flag
packagehas a more sophisticated interface, and also provides a way to parse flags. Takethis example from a DNS query tool:
dnssec := flag.Bool("dnssec", false, "Request DNSSEC records") 1
port := flag.String("port", "53", "Set the query port") 2
flag.Usage = func() { 3
fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] [name ...]\n", os.Args[0])
flag.PrintDefaults() 4
}
flag.Parse() 4
At 1 we define a bool
flag -dnssec
. Note that this function returnsa pointer to the value, the dnssec
is now a pointer to a bool
. At 2 wedefine an strings
flag. Then at 3 we redefine the Usage
variable of theflag package so we can add some extra text. The PrintDefaults
at 4 willoutput the default help for the flags that are defined. Note even withoutredefining a flag.Usage
the flag -h
is supported and will just output the help textfor each of the flags. Finally at 4 we call Parse
that parses the commandline and fills the variables.
After the flags have been parsed you can used them: if *dnssec { … }