From 5410531c7273a21029e18379b517b6d730f8aee4 Mon Sep 17 00:00:00 2001 From: jetlag <77204008+botxx15@users.noreply.github.com> Date: Fri, 21 Mar 2025 09:07:01 +0800 Subject: [PATCH] fix: centralize environment loading to avoid duplicate .env processing This commit fixes the environment loading mechanism by: - Removing duplicate .env loading in utils/get_env.go - Centralizing all environment loading in main.go - Adding better error handling with more descriptive messages - Making .env loading non-fatal to support fallback to default values - Improving debugging by displaying the working directory The previous implementation attempted to load the .env file in multiple places, leading to confusing error messages and potential inconsistencies. This change makes the environment loading process more robust and easier to debug when issues occur. --- main.go | 20 +++++++++++++++----- utils/get_env.go | 9 +-------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/main.go b/main.go index 2b947d3..683c709 100644 --- a/main.go +++ b/main.go @@ -31,14 +31,24 @@ func Worker(ctx context.Context, wg *sync.WaitGroup, id int) { } func main() { - err := godotenv.Load() + workDir, _ := os.Getwd() + fmt.Printf("Current working directory: %s\n", workDir) + + err := godotenv.Load("./.env") if err != nil { - log.Fatal("Error loading .env file") + altErr := godotenv.Load() + if altErr != nil { + log.Println("Warning: .env file not found, will use default values if needed") + } else { + log.Println("Environment loaded from default location") + } + } else { + log.Println("Environment loaded from ./.env") } - + pubKey, err := utils.GetCompressedPublicKey() if err != nil { - log.Fatal("Error loading .env file") + log.Fatalf("Error getting compressed public key: %v", err) } log.Printf("Compressed Public Key: %s", pubKey) @@ -61,4 +71,4 @@ func main() { wg.Wait() fmt.Println("Worker has shut down. Exiting..") -} +} \ No newline at end of file diff --git a/utils/get_env.go b/utils/get_env.go index c2a2b4d..750e9cd 100644 --- a/utils/get_env.go +++ b/utils/get_env.go @@ -1,19 +1,12 @@ package utils import ( - "log" "os" - - "github.com/joho/godotenv" ) func GetEnv(key, defaultValue string) string { - err := godotenv.Load() - if err != nil { - log.Println("Warning: .env file not loaded in processor") - } if value, exists := os.LookupEnv(key); exists { return value } return defaultValue -} +} \ No newline at end of file