Files
orbits/internal/utility/environment.go
T

116 lines
2.5 KiB
Go

package utility
import (
"log/slog"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
)
type Environment struct {
Version string
Codename string
LogLevel string
DataDirectory string
ContentDirectory string
Hostname string
Port int
WatchdogEnabled bool
WatchdogInterval int
WatchdogSyncMode string
}
var (
validSyncModes = []string{
"sync",
"strict",
"dry",
}
)
// part of environment checking
func safeStringGrab(key, fallback string) string {
if v, ok := os.LookupEnv(key); ok {
return v
}
return fallback
}
func safeIntGrab(key string, fallback int) int {
if v, ok := os.LookupEnv(key); ok {
if i, err := strconv.Atoi(v); err == nil {
return i
}
}
return fallback
}
func safeBoolGrab(key string, fallback bool) bool {
if v, ok := os.LookupEnv(key); ok {
if b, err := strconv.ParseBool(v); err == nil {
return b
}
}
return fallback
}
func safeSyncModeGrab(key, fallback string) string {
if v, ok := os.LookupEnv(key); ok {
if slices.Contains(validSyncModes, v) {
return v
}
}
return fallback
}
func GrabEnvironment() Environment {
cwd, err := os.Getwd()
if err != nil {
cwd = "."
}
fbBase := filepath.Join(cwd, "data")
fbContent := filepath.Join(fbBase, "content")
return Environment{
// Basic server configuration
Version: safeStringGrab("VERSION", "0.0.1"),
Codename: safeStringGrab("CODENAME", "Magical Anomaly"),
LogLevel: safeStringGrab("LOG_LEVEL", "debug"),
// GIN API configuration
DataDirectory: safeStringGrab("DATA_DIR", fbBase),
ContentDirectory: safeStringGrab("CONTENT_DIR", fbContent),
Hostname: safeStringGrab("HOSTNAME", "0.0.0.0"),
Port: safeIntGrab("PORT", 8080),
// watchdog configuration
// watchdog is the integrity checker/steward
WatchdogEnabled: safeBoolGrab("WATCHDOG_ENABLED", true),
WatchdogInterval: safeIntGrab("WATCHDOG_INTERVAL", 60),
// sync: sync local files to the database, for example when you want to allow local inserting files which then get added to the database
// strict: make the database leading, this is when you only allow API uploads to be registered, and remove orphaned filesystem files
// dry: do nothing
WatchdogSyncMode: safeStringGrab("WATCHDOG_SYNC_MODE", "strict"),
}
}
func ParseSlogLevel(s string) slog.Level {
switch strings.ToLower(s) {
case "debug":
return slog.LevelDebug
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
case "info":
fallthrough
default:
return slog.LevelInfo
}
}