Automatically generate the .env file if it is not there

This commit is contained in:
Achim Rohn
2025-09-17 09:59:02 +02:00
parent fae6653f94
commit 0283634b98
5 changed files with 63 additions and 25 deletions
+8 -13
View File
@@ -10,7 +10,6 @@ import (
)
const (
EnvKeyRepositoryType = "REPOSITORY_TYPE"
EnvKeyDatabaseURL = "DATABASE_URL"
EnvKeySessionSecret = "SESSION_SECRET"
EnvKeyBaseURL = "BASE_URL"
@@ -33,7 +32,6 @@ type Environment struct {
DatabaseUrl string
MistralApiKey string
IsDev bool
RepositoryType string
GoogleSheetsCredPath string
GoogleSheetsSpreadId string
GoogleSheetsSheetName string
@@ -54,21 +52,21 @@ type KeycloakConfig struct {
}
func LoadEnvironment() Environment {
if _, err := os.Stat(".env"); err != nil {
err = GenerateEnvFile("", false)
if err != nil {
Error("error generating the environment file", err)
}
}
err := godotenv.Load()
if err != nil {
LogError("Error loading .env file: %v", err)
panic(err)
}
// Default repository type is postgres if not specified
repoType := os.Getenv(EnvKeyRepositoryType)
if repoType == "" {
repoType = "postgres"
}
return Environment{
DatabaseUrl: os.Getenv(EnvKeyDatabaseURL),
IsDev: os.Getenv(EnvKeyIsDev) == "true" || os.Getenv(EnvKeyIsLocal) == "true",
RepositoryType: repoType,
GoogleClientId: os.Getenv(EnvKeyGoogleClientID),
GoogleClientSecret: os.Getenv(EnvKeyGoogleClientSecret),
GoogleRedirectUrl: os.Getenv(EnvKeyGoogleRedirectURL),
@@ -88,7 +86,6 @@ func LoadEnvironment() Environment {
// without duplicating or hard-coding the list elsewhere.
func EnvKeys() []string {
return []string{
EnvKeyRepositoryType,
EnvKeyDatabaseURL,
EnvKeySessionSecret,
EnvKeyBaseURL,
@@ -136,13 +133,11 @@ func GenerateEnvFile(rootPath string, overwrite bool) error {
// Define default values and comments for specific keys
defaults := map[string]string{
EnvKeyRepositoryType: "postgres",
EnvKeyIsLocal: "false",
EnvKeyIsDev: "false",
EnvKeyIsLocal: "true",
EnvKeyIsDev: "true",
}
comments := map[string]string{
EnvKeyRepositoryType: "# Repository type (postgres, sqlite, etc.)",
EnvKeyDatabaseURL: "# Database connection URL",
EnvKeySessionSecret: "# Secret key for session management",
EnvKeyBaseURL: "# Base URL of the application",