godash/internal/env/env.go

55 lines
1.7 KiB
Go
Raw Normal View History

2023-06-16 13:19:10 +02:00
package env
import (
"errors"
2024-03-12 15:49:08 +01:00
"github.com/caarlos0/env/v10"
2023-06-16 13:19:10 +02:00
"github.com/go-playground/validator/v10"
)
type Config struct {
2024-03-15 18:56:32 +01:00
TimeZone string `env:"TZ" envDefault:"Etc/UTC" validate:"timezone"`
2024-03-18 21:54:35 +01:00
PublicUrl string `env:"PUBLIC_URL" validate:"url"`
2024-03-15 18:56:32 +01:00
Title string `env:"TITLE" envDefault:"goDash"`
Port int `env:"PORT" envDefault:"4000" validate:"min=1024,max=49151"`
Version string `env:"APP_VERSION"`
2024-03-19 11:36:09 +01:00
LocationLatitude float32 `env:"LOCATION_LATITUDE" envDefault:"48.780331609463815" validate:"latitude"`
LocationLongitude float32 `env:"LOCATION_LONGITUDE" envDefault:"9.177968320179422" validate:"longitude"`
2024-03-15 18:56:32 +01:00
WeatherKey string `env:"WEATHER_KEY"`
WeatherUnits string `env:"WEATHER_UNITS" envDefault:"metric"`
2024-03-19 11:36:09 +01:00
WeatherLanguage string `env:"WEATHER_LANG" envDefault:"en" validate:"bcp47_language_tag"`
WeatherDigits bool `env:"WEATHER_DIGITS" envDefault:"false"`
2024-03-27 22:43:36 +01:00
SSODomain string `env:"SSO_DOMAIN" default:"" validate:"omitempty,fqdn"`
SSOKey string `env:"SSO_KEY,unset"`
SSOClientId string `env:"SSO_CLIENT_ID,unset"`
2023-06-16 13:19:10 +02:00
}
var errParse = errors.New("error parsing environment variables")
func Parse() (*Config, error) {
2024-03-27 22:43:36 +01:00
cfg := &Config{}
2023-06-16 13:19:10 +02:00
if err := env.Parse(cfg); err != nil {
return cfg, err
}
if err := validateContent(cfg); err != nil {
return cfg, err
}
return cfg, nil
}
func validateContent(cfg *Config) error {
validate := validator.New()
err := validate.Struct(cfg)
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
return err
} else {
for _, err := range err.(validator.ValidationErrors) {
return err
}
}
return errParse
}
return nil
}