Practical Flag Usage
Real-World Flag Implementation Patterns
package main
import (
"flag"
"fmt"
"log"
)
type Config struct {
Environment string
LogLevel string
DBConnection string
}
func parseConfig() *Config {
env := flag.String("env", "development", "Application environment")
logLevel := flag.String("log", "info", "Logging level")
dbConn := flag.String("db", "localhost:5432", "Database connection string")
flag.Parse()
return &Config{
Environment: *env,
LogLevel: *logLevel,
DBConnection: *dbConn,
}
}
func main() {
config := parseConfig()
fmt.Printf("Configuration Loaded:\n")
fmt.Printf("Environment: %s\n", config.Environment)
fmt.Printf("Log Level: %s\n", config.LogLevel)
fmt.Printf("Database: %s\n", config.DBConnection)
}
Flag Usage Patterns
Pattern |
Description |
Example |
Configuration Management |
Control application behavior |
--env=production |
Feature Toggling |
Enable/disable features |
--debug |
Resource Configuration |
Set runtime parameters |
--max-connections=100 |
Logging Control |
Adjust logging verbosity |
--log-level=debug |
Comprehensive Flag Handling
graph TD
A[Flag Declaration] --> B[Parsing]
B --> C{Validation}
C --> |Valid| D[Configuration]
C --> |Invalid| E[Error Handling]
D --> F[Application Execution]
Advanced Flag Scenarios
Multiple Flag Sources
package main
import (
"flag"
"fmt"
"os"
)
func main() {
// Primary configuration flags
configFile := flag.String("config", "", "Path to configuration file")
// Optional override flags
port := flag.Int("port", 8080, "Server port")
// Environment variable fallback
flag.Parse()
// Prioritize flag values
finalPort := *port
if envPort := os.Getenv("SERVER_PORT"); envPort != "" {
finalPort, _ = strconv.Atoi(envPort)
}
fmt.Printf("Configuration File: %s\n", *configFile)
fmt.Printf("Server Port: %d\n", finalPort)
}
Best Practices
- Use meaningful flag names
- Provide default values
- Include comprehensive help text
- Implement input validation
- Support multiple configuration sources
Error Handling Strategies
func validateFlags() error {
if *port < 1024 || *port > 65535 {
return fmt.Errorf("invalid port number: %d", *port)
}
return nil
}
- Minimize flag parsing complexity
- Use lazy initialization
- Cache parsed flag values
- Implement efficient validation
LabEx Recommendation
LabEx provides interactive environments to practice advanced flag handling techniques in real-world scenarios.
Flag Design Principles
- Clarity
- Consistency
- Flexibility
- Intuitive Usage