log/default env variable name in pgx
In Go, when using pgx to connect database we will passed the connection string like this:
1pool, err := pgxpool.New(ctx, "connection string")
2if err != nil {
3 log.Error().Err(err).Msg("unable to connect to database")
4}
We usually passed username password in to the connection string. However when using pgx we don't need to do that, because pgx will always check default env varible. It shown in function inside pgx package:
1func parseEnvSettings() map[string]string {
2 settings := make(map[string]string)
3
4 nameMap := map[string]string{
5 "PGHOST": "host",
6 "PGPORT": "port",
7 "PGDATABASE": "database",
8 "PGUSER": "user",
9 "PGPASSWORD": "password",
10 "PGPASSFILE": "passfile",
11 "PGAPPNAME": "application_name",
12 "PGCONNECT_TIMEOUT": "connect_timeout",
13 "PGSSLMODE": "sslmode",
14 "PGSSLKEY": "sslkey",
15 "PGSSLCERT": "sslcert",
16 "PGSSLSNI": "sslsni",
17 "PGSSLROOTCERT": "sslrootcert",
18 "PGSSLPASSWORD": "sslpassword",
19 "PGTARGETSESSIONATTRS": "target_session_attrs",
20 "PGSERVICE": "service",
21 "PGSERVICEFILE": "servicefile",
22 }
23
24 for envname, realname := range nameMap {
25 value := os.Getenv(envname)
26 if value != "" {
27 settings[realname] = value
28 }
29 }
30
31 return settings
32}