defaults.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //go:build !windows
  2. // +build !windows
  3. package pgconn
  4. import (
  5. "os"
  6. "os/user"
  7. "path/filepath"
  8. )
  9. func defaultSettings() map[string]string {
  10. settings := make(map[string]string)
  11. settings["host"] = defaultHost()
  12. settings["port"] = "5432"
  13. // Default to the OS user name. Purposely ignoring err getting user name from
  14. // OS. The client application will simply have to specify the user in that
  15. // case (which they typically will be doing anyway).
  16. user, err := user.Current()
  17. if err == nil {
  18. settings["user"] = user.Username
  19. settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass")
  20. settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
  21. sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
  22. sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
  23. if _, err := os.Stat(sslcert); err == nil {
  24. if _, err := os.Stat(sslkey); err == nil {
  25. // Both the cert and key must be present to use them, or do not use either
  26. settings["sslcert"] = sslcert
  27. settings["sslkey"] = sslkey
  28. }
  29. }
  30. sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt")
  31. if _, err := os.Stat(sslrootcert); err == nil {
  32. settings["sslrootcert"] = sslrootcert
  33. }
  34. }
  35. settings["target_session_attrs"] = "any"
  36. return settings
  37. }
  38. // defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost
  39. // on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it
  40. // checks the existence of common locations.
  41. func defaultHost() string {
  42. candidatePaths := []string{
  43. "/var/run/postgresql", // Debian
  44. "/private/tmp", // OSX - homebrew
  45. "/tmp", // standard PostgreSQL
  46. }
  47. for _, path := range candidatePaths {
  48. if _, err := os.Stat(path); err == nil {
  49. return path
  50. }
  51. }
  52. return "localhost"
  53. }