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
2 years ago
import (
"log"
"os"
"time"
2 years ago
"github.com/joho/godotenv"
)
var (
2 years ago
Mode string
Host string
BaseURL string
AdminPassword string
MonitorScriptsDir string
MonitorCacheTimeout time.Duration
)
2 years ago
func loadEnv(key string, defaultValue ...string) string {
env, present := os.LookupEnv(key)
2 years ago
if len(defaultValue) > 0 && !present {
2 years ago
env = defaultValue[0]
}
log.Printf("Env variable %s = %q", key, env)
2 years ago
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
}
2 years ago
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)
2 years ago
}