Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Flag Was Provided in Go

With the flag package, is there a good way to distinguish if a string flag was passed?

For example, when the flag is not passed, I want to set it to a dynamic default value. However, I want to set it to empty if the flag was provided but with a value of "".

Current I am doing the following:

flagHost = flag.String(flagHostFlagKey, "", "...") ... setHostname := false for _, arg := range os.Args {     if arg == "-"+flagHostFlagKey {         setHostname = true     } }  if !setHostname {      ... 

Which seems to work fine, but is kind of ugly. Is there a better way while staying with the standard flag package?

like image 261
Kyle Brandt Avatar asked Mar 05 '16 02:03

Kyle Brandt


People also ask

What is flag in Golang?

In Golang, flag is a built-in package shipped with Go standard library. A flag is a formatted string that is passed as an argument to a program so that, according to the flag passed, the control or behavior of the program has some augmented utilities.

How do you set a flag in Go?

Defining flags is easy, you can set them up using flag. String() , flag. Bool() , flag.Int() , etc. After you've defined your flags, you need to call flag.

What is flag command-line?

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag. package main. Go provides a flag package supporting basic command-line flag parsing.


1 Answers

Use the flag.Visit() function:

func isFlagPassed(name string) bool {     found := false     flag.Visit(func(f *flag.Flag) {         if f.Name == name {             found = true         }     })     return found } 
like image 93
Markus Heukelom Avatar answered Sep 20 '22 17:09

Markus Heukelom