Flags and Usage Patterns
Understanding Command-Line Flags
Command-line flags provide a flexible way to customize application behavior. Golang offers multiple approaches to define and manage flags:
package main
import (
"flag"
"fmt"
)
func main() {
// Basic flag types
stringFlag := flag.String("name", "default", "User name")
intFlag := flag.Int("age", 0, "User age")
boolFlag := flag.Bool("verbose", false, "Enable verbose mode")
// Parse flags
flag.Parse()
fmt.Printf("Name: %s, Age: %d, Verbose: %v\n",
*stringFlag, *intFlag, *boolFlag)
}
Flag Types and Usage
Flag Type |
Description |
Example |
String |
Text input |
--name=John |
Integer |
Numeric input |
--port=8080 |
Boolean |
True/False toggle |
--debug |
Duration |
Time interval |
--timeout=5s |
Advanced Flag Patterns
graph TD
A[Flag Definition] --> B{Flag Type}
B --> |String| C[String Parsing]
B --> |Integer| D[Numeric Validation]
B --> |Boolean| E[Toggle Handling]
B --> |Custom| F[Complex Parsing]
Custom Flag Handling
type CustomFlag struct {
Value string
}
func (c *CustomFlag) String() string {
return c.Value
}
func (c *CustomFlag) Set(value string) error {
// Custom validation logic
if len(value) < 3 {
return fmt.Errorf("value too short")
}
c.Value = value
return nil
}
Subcommand Patterns
func main() {
// Create subcommand structure
createCmd := flag.NewFlagSet("create", flag.ExitOnError)
deleteCmd := flag.NewFlagSet("delete", flag.ExitOnError)
createName := createCmd.String("name", "", "Resource name")
deleteName := deleteCmd.String("name", "", "Resource to delete")
// Parse subcommands
switch os.Args[1] {
case "create":
createCmd.Parse(os.Args[2:])
case "delete":
deleteCmd.Parse(os.Args[2:])
}
}
LabEx Recommendation
When developing CLI tools in LabEx, focus on creating intuitive flag interfaces that make your application easy to use and understand.
Best Practices
- Use clear, descriptive flag names
- Provide meaningful default values
- Implement robust flag validation
- Support help and usage information