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