From a311871528f574c03863430d501b00d39e6386f8 Mon Sep 17 00:00:00 2001 From: David Chang Date: Tue, 27 Feb 2024 13:59:03 -0500 Subject: [PATCH] Fix fatal error if .env doesn't load in production --- .env.example | 1 + README.md | 1 + main.go | 16 ++++++++++------ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index b7fa869..74ee532 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ +ENVIRONMENT=[development] MYSQL_PORT=[3306] DB_USER=[root] DB_PASSWORD=[password] diff --git a/README.md b/README.md index 12b27a4..5577221 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ RESTful API for interacting with David Chang programmatically ### Configure `$ cp .env.example .env` - Fill out all the details for your local database (replace examples in brackets): + - ENVIRONMENT=[development] - MYSQL_PORT=[3306] - DB_USER=[root] - DB_PASSWORD=[password] diff --git a/main.go b/main.go index 0f30d99..6503b20 100644 --- a/main.go +++ b/main.go @@ -23,12 +23,16 @@ type Resume struct { } func init() { - // Load environment variables from a file if needed - // For simplicity, you can set them directly in your Cloud Run service configuration. - // LoadEnvFromFile(".env") // Uncomment this line if you are using a .env file - err := godotenv.Load() - if err != nil { - log.Fatal("Error loading .env file") + // Check if running in a development environment + env := os.Getenv("ENVIRONMENT") + if env == "" || strings.ToLower(env) == "development" { + // Load environment variables from a file for development + err := godotenv.Load() + if err != nil { + log.Fatal("Error loading .env file") + } + } else { + // In production, environment variables are provided by the deployment platform (ie. Cloud Run) } }