pg
pg copied to clipboard
BeforeConnect Hook
As per discussions in https://github.com/go-pg/pg/discussions/1848
This PR adds a new hook into Options
to facilitate the use of secret providers / dynamic / one-time passwords. It has been added as BeforeConnect
in order for the usage to be generic; whether it is for secret providers or simply logging when database connections are established.
Example
some error handling removed for readability
package main
imports (
"context"
"github.com/go-pg/pg/v10"
"github.com/fake-user/supersecrets"
)
func main() {
opts, _ := pg.ParseURL("postgresql://dbUser@dbhost/accounts")
opts.BeforeConnect = func(ctx context.Context, o *pg.Options) error {
token, err := supersecrets.GetToken("accounts-db-password")
if err != nil {
return err
}
o.Password = token
return nil
}
db := pg.Connect(opts)
// business logic
}
Thanks for the feedback, I'll work the suggestions into this PR over the coming days
@vmihailenco any way I'd be able to take this over? Still very interested in it
@elliotcourant sure, go ahead :+1:
@vmihailenco sorry for the horrendous delay in this. Before I get around to resolve the testing points from @elliotcourant, could I confirm whether the current changes align with your expectations around cloning Options?
@justcompile I will take a look at the diff again this weekend and double check it!