Argument Validation
Why Argument Validation Matters
Argument validation is a critical process in ensuring the reliability and security of command-line applications. It helps prevent unexpected behavior and provides clear feedback to users.
Basic Validation Techniques
Checking Argument Count
package main
import (
"fmt"
"os"
)
func validateArgumentCount(expectedCount int) {
if len(os.Args) < expectedCount + 1 {
fmt.Printf("Error: Expected %d arguments, got %d\n", expectedCount, len(os.Args)-1)
fmt.Println("Usage: program <arg1> <arg2> ...")
os.Exit(1)
}
}
func main() {
// Require exactly 2 arguments
validateArgumentCount(2)
// Process arguments
fmt.Println("First argument:", os.Args[1])
fmt.Println("Second argument:", os.Args[2])
}
Comprehensive Validation Strategies
flowchart TD
A[Argument Validation] --> B{Argument Count}
B --> |Insufficient| C[Reject Execution]
B --> |Sufficient| D{Type Validation}
D --> |Invalid Type| E[Convert or Reject]
D --> |Valid Type| F{Value Range Check]
F --> |Out of Range| G[Handle Error]
F --> |In Range| H[Process Argument]
Type and Value Validation
package main
import (
"fmt"
"os"
"strconv"
)
func validateIntegerArgument(arg string) (int, error) {
// Convert and validate integer argument
value, err := strconv.Atoi(arg)
if err != nil {
return 0, fmt.Errorf("invalid integer: %s", arg)
}
// Additional range validation
if value < 0 || value > 100 {
return 0, fmt.Errorf("value must be between 0 and 100")
}
return value, nil
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide an integer argument")
os.Exit(1)
}
value, err := validateIntegerArgument(os.Args[1])
if err != nil {
fmt.Println("Validation error:", err)
os.Exit(1)
}
fmt.Println("Valid input:", value)
}
Validation Patterns
Validation Type |
Description |
Example |
Count Validation |
Check number of arguments |
Ensure 2-3 arguments |
Type Validation |
Verify argument types |
Convert to int, float |
Range Validation |
Check value boundaries |
0-100, positive numbers |
Format Validation |
Validate specific formats |
Email, date, regex |
Advanced Validation Techniques
Using Reflection for Complex Validation
package main
import (
"fmt"
"reflect"
"strconv"
)
func validateArgument(arg interface{}, expectedType reflect.Kind) bool {
return reflect.TypeOf(arg).Kind() == expectedType
}
func main() {
// Example of type checking
intArg := "42"
if validateArgument(intArg, reflect.String) {
value, _ := strconv.Atoi(intArg)
fmt.Println("Valid integer:", value)
}
}
Best Practices for LabEx Developers
- Always validate input before processing
- Provide clear error messages
- Use type-specific validation functions
- Implement comprehensive error handling
Note: Robust argument validation is crucial for creating reliable command-line tools in Go, especially when developing applications on LabEx platforms.