defaults_windows.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package pgconn
  2. import (
  3. "os"
  4. "os/user"
  5. "path/filepath"
  6. "strings"
  7. )
  8. func defaultSettings() map[string]string {
  9. settings := make(map[string]string)
  10. settings["host"] = defaultHost()
  11. settings["port"] = "5432"
  12. // Default to the OS user name. Purposely ignoring err getting user name from
  13. // OS. The client application will simply have to specify the user in that
  14. // case (which they typically will be doing anyway).
  15. user, err := user.Current()
  16. appData := os.Getenv("APPDATA")
  17. if err == nil {
  18. // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`,
  19. // but the libpq default is just the `user` portion, so we strip off the first part.
  20. username := user.Username
  21. if strings.Contains(username, "\\") {
  22. username = username[strings.LastIndex(username, "\\")+1:]
  23. }
  24. settings["user"] = username
  25. settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf")
  26. settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
  27. sslcert := filepath.Join(appData, "postgresql", "postgresql.crt")
  28. sslkey := filepath.Join(appData, "postgresql", "postgresql.key")
  29. if _, err := os.Stat(sslcert); err == nil {
  30. if _, err := os.Stat(sslkey); err == nil {
  31. // Both the cert and key must be present to use them, or do not use either
  32. settings["sslcert"] = sslcert
  33. settings["sslkey"] = sslkey
  34. }
  35. }
  36. sslrootcert := filepath.Join(appData, "postgresql", "root.crt")
  37. if _, err := os.Stat(sslrootcert); err == nil {
  38. settings["sslrootcert"] = sslrootcert
  39. }
  40. }
  41. settings["target_session_attrs"] = "any"
  42. return settings
  43. }
  44. // defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost
  45. // on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it
  46. // checks the existence of common locations.
  47. func defaultHost() string {
  48. return "localhost"
  49. }