Practical Use Cases
Configuration Management
Database Connection Configuration
func connectDatabase() *sql.DB {
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
user := os.Getenv("DB_USER")
password := os.Getenv("DB_PASSWORD")
connectionString := fmt.Sprintf("host=%s port=%s user=%s password=%s",
host, port, user, password)
db, err := sql.Open("postgres", connectionString)
if err != nil {
log.Fatal("Database connection error")
}
return db
}
Deployment Environment Detection
func getEnvironmentMode() string {
mode := os.Getenv("APP_ENV")
switch mode {
case "production":
return "Production Mode"
case "staging":
return "Staging Mode"
default:
return "Development Mode"
}
}
Security Configuration
API Key Management
type APIClient struct {
apiKey string
}
func NewAPIClient() *APIClient {
apiKey := os.Getenv("API_SECRET_KEY")
if apiKey == "" {
log.Fatal("Missing API Secret Key")
}
return &APIClient{apiKey: apiKey}
}
Environment-Specific Logging
func configureLogger() *log.Logger {
logLevel := os.Getenv("LOG_LEVEL")
switch logLevel {
case "DEBUG":
return log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)
case "ERROR":
return log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
default:
return log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime)
}
}
Use Case Scenarios
Scenario |
Environment Variable |
Purpose |
Database Config |
DB_HOST, DB_PORT |
Connection Details |
Deployment Mode |
APP_ENV |
Environment Detection |
Logging |
LOG_LEVEL |
Logging Configuration |
API Security |
API_SECRET_KEY |
Secure Access |
Environment Flow Diagram
graph TD
A[Environment Variables] --> B{Detect Environment}
B --> |Production| C[High Security Config]
B --> |Staging| D[Intermediate Config]
B --> |Development| E[Relaxed Config]
C --> F[Secure Logging]
D --> G[Moderate Logging]
E --> H[Verbose Logging]
LabEx Development Tip
In LabEx environments, consistently use environment variables to create flexible and secure application configurations across different deployment stages.
Best Practices
- Always validate environment variables
- Use default values when appropriate
- Implement secure fallback mechanisms
- Separate configuration from code