WeatherService/src/config/Configuration.go

75 lines
1.5 KiB
Go

package config
import (
"fmt"
"os"
"strconv"
"strings"
)
type Configuration struct {
ApiKey string
Language string
Units Units
Port int
JwtSecret string
SentryDsn string
}
func (config Configuration) String() string {
return fmt.Sprintf("api_key=%s language=%s, units=%s, port=%d, jwt_secret=%s", config.ApiKey, config.Language, config.Units, config.Port, config.JwtSecret)
}
//returns a new Config struct
func LoadConfiguration() *Configuration {
return &Configuration{
ApiKey: getEnv("API_KEY", ""),
Language: getEnv("LANGUAGE", "en"),
Units: StringToUnit(getEnv("UNITS", "metric")),
Port: getEnvAsInt("PORT", 8080),
JwtSecret: getEnv("JWT_SECRET", "super secret value"),
SentryDsn: getEnv("SENTRY_DSN", ""),
}
}
// Simple helper function to read an environment or return a default value
func getEnv(key string, defaultVal string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultVal
}
// Simple helper function to read an environment variable into integer or return a default value
func getEnvAsInt(name string, defaultVal int) int {
valueStr := getEnv(name, "")
if value, err := strconv.Atoi(valueStr); err == nil {
return value
}
return defaultVal
}
type Units int
const (
Metric Units = iota
Imperial
)
func (unit Units) String() string {
return [...]string{"metric", "imperial"}[unit]
}
func StringToUnit(string string) Units {
if strings.EqualFold(string, "metric") {
return Metric
} else {
return Imperial
}
}