main.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package config
  2. import (
  3. "os"
  4. "log"
  5. "fmt"
  6. "strconv"
  7. "path/filepath"
  8. "github.com/joho/godotenv"
  9. )
  10. func getEnvFile() (string, bool) {
  11. goEnv, _ := os.LookupEnv("GO_ENV")
  12. switch goEnv {
  13. case "test":
  14. return "test.env", true
  15. case "development":
  16. return ".env", true
  17. default:
  18. return "", false
  19. }
  20. }
  21. func loadEnv() {
  22. envFileBase, loadEnvFile := getEnvFile()
  23. cwd, _ := os.Getwd()
  24. envFile := filepath.Join(cwd, envFileBase)
  25. if loadEnvFile {
  26. err := godotenv.Load(envFile)
  27. if err != nil {
  28. log.Fatal("Error loading dotenv file: ", err)
  29. }
  30. }
  31. }
  32. func getDatabaseUrl() string {
  33. host, hasHost := os.LookupEnv("POSTGRES_HOST")
  34. if !hasHost {
  35. log.Fatal("Must set POSTGRES_HOST")
  36. }
  37. user := os.Getenv("POSTGRES_USER")
  38. password := os.Getenv("POSTGRES_PASSWORD")
  39. port, hasPort := os.LookupEnv("POSTGRES_PORT")
  40. if !hasPort {
  41. port = "5432"
  42. }
  43. portNumeric, err := strconv.Atoi(port)
  44. if err != nil {
  45. log.Fatal("POSTGRES_PORT must be numeric")
  46. }
  47. database, hasDatabase := os.LookupEnv("POSTGRES_DATABASE")
  48. if !hasDatabase {
  49. log.Fatal("Must set POSTGRES_DATABASE")
  50. }
  51. databaseUrl := fmt.Sprintf("postgres://%s:%s@%s:%d/%s", user, password, host, portNumeric, database)
  52. return databaseUrl
  53. }
  54. type config struct {
  55. DatabaseUrl string
  56. }
  57. func getConfig() config {
  58. loadEnv()
  59. return config{
  60. DatabaseUrl: getDatabaseUrl(),
  61. }
  62. }
  63. var Config = getConfig()