Skip to content

Latest commit

History

19 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

pgconf

pgconf is a simple Go package for reading/writing to PostgreSQL config file (postgresql.conf) that:

  • Preseves existing whitespace and comments
  • Supports single quoted and backslash-quoted values (eg. search_path = '''$user'', \'public\'')
  • Supports values with optional equal sign (eg. logconnections yes)
  • Works with ASCII and UTF-8 .conf files

How to use

postgresql.conf:

To read or update postgresql.conf files use the pgconf/conf package:

import (
"fmt""github.com/quasoft/pgconf/conf"
)
funcmain() {
c, err:=conf.Open("/data/postgresql.conf")
iferr!=nil {
panic("Could not open conf file: "+err.Error())
}
// StringK automatically dequotes valuesdest, err:=c.StringK("log_destination")
iferr!=nil||dest!="syslog" {
// If key was not set or has the wrong valuefmt.Println("log_destination value is not what we want, changing it now")
c.SetStringK("log_destination", "syslog") // SetStringK automatically quotes values if necessary
}
err=c.WriteFile("/data/postgresql.conf", 0644)
iferr!=nil {
panic("Could not save file: "+err.Error())
}
}

pg_hba.conf

To read or update pg_hba.conf files use the pgconf/hba package:

package main
import (
"fmt""github.com/quasoft/pgconf/hba"
)
funcmain() {
conf, err:=hba.Open("../../hba/testdata/sample.conf") // pg_hba.confiferr!=nil {
panic(fmt.Errorf("Failed opening file pg_hba.conf: %s", err))
}
// Find all rows for replication host-based authenticationrows, err:=conf.LookupAll(hba.Database, "replication")
iferr!=nil {
panic(fmt.Errorf("Failed looking up for replication rows: %s", err))
}
fmt.Printf("Found %d replication rows with addresses as follows:\n", len(rows))
for_, row:=rangerows {
// Get and print value for ADDRESS columnaddress, err:=conf.String(row, hba.Address)
iferr!=nil {
panic(fmt.Errorf("Could not read address value: %s", err))
}
fmt.Println(" - "+address)
}
}

outputs:

Found 3 replication rows with addresses as follows:
- 127.0.0.1/32
- ::1/128
- 10.0.0.3/32

Hint

Usually it's safer to write changes to a temp file and once that writing is over to rename the temp file to the actual configuration file:

...err=c.WriteFile("/data/postgresql.conf.tmp", 0644)
iferr!=nil {
panic("Could not save file: "+err.Error())
}
err=os.Rename("/data/postgresql.conf.tmp", "/data/postgresql.conf")
iferr!=nil {
panic("Could not rename tmp file to conf: "+err.Error())
}
...
}

If you use this approach make sure to store the temp file in a secure location (eg. the data dir) with restricted permissions and not inside the /tmp directory.

About

Simple Go package for reading/writing to PostgreSQL config files

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages