In Go, command-line flags can be easily handled using the flag
package provided by the standard library. To handle required flags and error handling, you can follow these steps:
flag
and fmt
packages:import (
"flag"
"fmt"
)
flag
package:var (
requiredFlag = flag.String("requiredFlag", "", "Description of the required flag")
)
Here, requiredFlag
is the name of the required flag, ""
is the default value, and the string is the description of the flag.
func areRequiredFlagsSet() bool {
if *requiredFlag == "" {
return false
}
return true
}
This function checks if the required flag value is empty or not.
flag.Parse()
This code parses the command-line arguments provided to the program.
if !areRequiredFlagsSet() {
fmt.Println("Required flags are missing.")
flag.PrintDefaults()
return
}
If the required flags are not set, it will print an error message along with the default flag values and exit the program.
Now you can use the value of the required flag anywhere in your program by accessing the *requiredFlag
variable.
Remember to call flag.Parse()
before accessing the flag value.
Additionally, you can define other optional flags using the same method, and the flag
package will handle all the parsing and default values for you.