You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.3 KiB
Go

package config
import (
"log"
"os"
"time"
"github.com/joho/godotenv"
)
var (
Mode string
Host string
BaseURL string
AdminPassword string
MonitorScriptsDir string
MonitorCacheTimeout time.Duration
)
func loadEnv(key string, defaultValue ...string) string {
env, present := os.LookupEnv(key)
if len(defaultValue) > 0 && !present {
env = defaultValue[0]
}
log.Printf("Env variable %s = %q", key, env)
return env
}
func parseEnv[T any](key, defaultValue string, parseFunc func(string) (T, error)) T {
env := loadEnv(key, defaultValue)
v, err := parseFunc(env)
if err != nil {
v, err = parseFunc(defaultValue)
if err != nil {
log.Fatalf("Unable to parse default value %q to type %T", defaultValue, v)
}
}
log.Printf(`Env variable %s parsed from %q to %T of value %v`, key, env, v, v)
return v
}
func init() {
// Setup logger
log.SetFlags(log.Lshortfile | log.Ltime | log.Ldate)
// Load Config
godotenv.Load()
Mode = loadEnv("MODE", "development")
Host = loadEnv("HOST", ":4000")
BaseURL = loadEnv("HOST", "http://localhost:4000")
AdminPassword = loadEnv("ADMIN_PASSWORD", "secret")
MonitorScriptsDir = loadEnv("MONITOR_SCRIPTS_DIR", "./scripts")
MonitorCacheTimeout = parseEnv("MONITOR_CACHE_TIMEOUT", "5s", time.ParseDuration)
}