mirror of
https://github.com/httprunner/httprunner.git
synced 2026-09-04 23:16:57 +08:00
feat: load .env file from current working directory upward recursively
This commit is contained in:
+41
-11
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -31,6 +32,46 @@ const (
|
||||
EnvOpenAIInitConfigJSON = "OPENAI_INIT_CONFIG_JSON"
|
||||
)
|
||||
|
||||
func init() {
|
||||
err := loadEnv()
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("load .env file failed")
|
||||
}
|
||||
}
|
||||
|
||||
// loadEnv loads environment variables from .env file
|
||||
// it will search for .env file from current working directory upward recursively
|
||||
func loadEnv() error {
|
||||
// get current working directory
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get current working directory: %v", err)
|
||||
}
|
||||
|
||||
// locate .env file from current working directory upward recursively
|
||||
envPath := cwd
|
||||
for {
|
||||
envFile := filepath.Join(envPath, ".env")
|
||||
if _, err := os.Stat(envFile); err == nil {
|
||||
// found .env file
|
||||
// override existing env variables
|
||||
err = godotenv.Overload(envFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load env file: %v", err)
|
||||
}
|
||||
log.Info().Str("path", envFile).Msg("load env success")
|
||||
return nil
|
||||
}
|
||||
|
||||
// reached root directory
|
||||
parent := filepath.Dir(envPath)
|
||||
if parent == envPath {
|
||||
return fmt.Errorf("no .env file found from current directory to root")
|
||||
}
|
||||
envPath = parent
|
||||
}
|
||||
}
|
||||
|
||||
func checkEnvLLM() error {
|
||||
openaiBaseURL := os.Getenv("OPENAI_BASE_URL")
|
||||
if openaiBaseURL == "" {
|
||||
@@ -50,17 +91,6 @@ func checkEnvLLM() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadEnv loads environment variables from a file
|
||||
func loadEnv(envPath string) error {
|
||||
err := godotenv.Load(envPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Info().Str("path", envPath).Msg("load env success")
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetEnvConfig(key string) string {
|
||||
return os.Getenv(key)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user