WeatherService/src/config/Configuration.go

75 lines
1.5 KiB
Go
Raw Normal View History

2020-07-20 18:02:54 +02:00
package config
import (
"fmt"
"os"
"strconv"
2020-07-21 16:50:51 +02:00
"strings"
2020-07-20 18:02:54 +02:00
)
type Configuration struct {
ApiKey string
Language string
2020-07-21 16:50:51 +02:00
Units Units
2020-07-20 18:02:54 +02:00
Port int
JwtSecret string
2020-07-20 19:42:18 +02:00
SentryDsn string
2020-07-20 18:02:54 +02:00
}
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"),
2020-07-21 16:50:51 +02:00
Units: StringToUnit(getEnv("UNITS", "metric")),
2020-07-20 18:02:54 +02:00
Port: getEnvAsInt("PORT", 8080),
JwtSecret: getEnv("JWT_SECRET", "super secret value"),
2020-07-20 19:42:18 +02:00
SentryDsn: getEnv("SENTRY_DSN", ""),
2020-07-20 18:02:54 +02:00
}
}
// 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
}
2020-07-21 16:50:51 +02:00
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
}
}