Validation Patterns
Why Validate Environment Variables?
Environment variable validation ensures application configuration integrity and prevents runtime errors. By implementing robust validation patterns, developers can create more reliable and secure applications.
Validation Strategies
graph TD
A[Env Var Validation] --> B[Type Checking]
A --> C[Format Validation]
A --> D[Range Validation]
A --> E[Mandatory Checks]
Basic Validation Techniques
Type Conversion and Checking
package main
import (
"fmt"
"os"
"strconv"
)
func validateIntEnv(key string, min, max int) (int, error) {
valueStr := os.Getenv(key)
if valueStr == "" {
return 0, fmt.Errorf("%s is not set", key)
}
value, err := strconv.Atoi(valueStr)
if err != nil {
return 0, fmt.Errorf("invalid %s: must be an integer", key)
}
if value < min || value > max {
return 0, fmt.Errorf("%s must be between %d and %d", key, min, max)
}
return value, nil
}
Regular Expression Validation
package main
import (
"fmt"
"os"
"regexp"
)
func validateEmailEnv(key string) (string, error) {
email := os.Getenv(key)
if email == "" {
return "", fmt.Errorf("%s is not set", key)
}
emailRegex := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
if !emailRegex.MatchString(email) {
return "", fmt.Errorf("invalid email format for %s", key)
}
return email, nil
}
Comprehensive Validation Patterns
Validation Type |
Description |
Example |
Mandatory Check |
Ensure variable is set |
Check if DATABASE_URL exists |
Type Validation |
Verify correct data type |
Convert MAX_CONNECTIONS to integer |
Format Validation |
Match specific patterns |
Validate email, URL formats |
Range Validation |
Check numeric boundaries |
Ensure port number is between 1-65535 |
Advanced Validation Approach
type EnvConfig struct {
DatabaseURL string
MaxConnection int
LogLevel string
}
func validateConfig() (*EnvConfig, error) {
config := &EnvConfig{}
var err error
// URL validation
config.DatabaseURL, err = validateURLEnv("DATABASE_URL")
if err != nil {
return nil, err
}
// Integer range validation
config.MaxConnection, err = validateIntEnv("MAX_CONNECTIONS", 1, 100)
if err != nil {
return nil, err
}
// Enum-like validation
config.LogLevel, err = validateLogLevelEnv("LOG_LEVEL")
if err != nil {
return nil, err
}
return config, nil
}
Best Practices with LabEx Recommendations
- Always validate environment variables before use
- Provide clear, descriptive error messages
- Use type-safe conversions
- Implement default values when appropriate
- Consider using configuration management libraries
By mastering these validation patterns, developers can create more robust and reliable Golang applications with LabEx's best practices.