go flag command line - ghdrako/doc_snipets GitHub Wiki

With flag, you can set up default values for your flags, provide descriptions for flags, and allow users to override defaults at the command line.

Flags with the flag package are simply proceeded by --, similar to --endpoint. Values can simply be a contiguous string following the endpoint or a quoted string. While you can use a single - instead of --, there are some corner cases when dealing with Boolean flags. I would recommend using -- in all cases.

You can find the flag package documentation here: https://pkg.go.dev/flag.

var endpoint = flag.String(
  "endpoint",                         // flag name
  "myserver.aws.com",                 // flag default value
  "The server this app will contact", // flag description
)
func main() {
  flag.Parse()
  fmt.Println("server endpoint is: ", *endpoint) // flag.String() returns *string, hence *endpoint
}

flag.Parse() is crucial to making your flags available in your application. This should only be called inside your main() package.

Pro Tip A best practice in Go is to never define flags outside your main package. Simply pass the values as function arguments or in object constructors.

flag also defines a few other flag functions other than String():

  • Bool() for capturing bool
  • Int() for capturing int
  • Int64() for capturing int64
  • Uint() for capturing uint
  • Uint64() for capturing uint64
  • Float64() for capturing float64
  • Duration() for capturing time.Duration, such as 3m10s