dotenv.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "github.com/joho/godotenv"
  8. )
  9. // DefaultEnvFile is loaded automatically when it exists.
  10. const DefaultEnvFile = ".env"
  11. // LoadDotEnv loads KEY=VALUE pairs from the file named by ENV_FILE, or from
  12. // .env in the current directory when ENV_FILE is unset.
  13. //
  14. // Variables that already exist in the process environment are never
  15. // overwritten, so exported shell variables take precedence over the file.
  16. // A missing default .env is ignored; an explicitly configured ENV_FILE must
  17. // exist and be readable.
  18. func LoadDotEnv() error {
  19. if path := strings.TrimSpace(os.Getenv("ENV_FILE")); path != "" {
  20. return LoadEnvFile(path)
  21. }
  22. if err := godotenv.Load(DefaultEnvFile); err != nil {
  23. if errors.Is(err, os.ErrNotExist) {
  24. return nil
  25. }
  26. return fmt.Errorf("load env file %s: %w", DefaultEnvFile, err)
  27. }
  28. return nil
  29. }
  30. // LoadEnvFile loads KEY=VALUE pairs from an explicit file. Existing process
  31. // variables are not overwritten. The file must exist and be readable.
  32. func LoadEnvFile(path string) error {
  33. path = strings.TrimSpace(path)
  34. if path == "" {
  35. return errors.New("env file path must not be empty")
  36. }
  37. if err := godotenv.Load(path); err != nil {
  38. return fmt.Errorf("load env file %s: %w", path, err)
  39. }
  40. return nil
  41. }