Package alloydbconn provides functions for authorizing and encrypting connections. These functions can be used with a database driver to connect to an AlloyDB cluster.
Creating a Dialer
To start working with this package, create a Dialer. There are two ways of creating a Dialer, which one you use depends on your database driver.
Users have the option of using the database/sql interface or using pgx directly.
To use a dialer with pgx, we recommend using connection pooling with pgxpool. To create the dialer use the NewDialer func.
import ( "context" "net" "cloud.google.com/go/alloydbconn" "github.com/jackc/pgx/v4/pgxpool" ) func connect() { // Configure the driver to connect to the database dsn := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", pgUser, pgPass, pgDB) config, err := pgxpool.ParseConfig(dsn) if err != nil { log.Fatalf("failed to parse pgx config: %v", err) } // Create a new dialer with any options d, err := alloydbconn.NewDialer(ctx) if err != nil { log.Fatalf("failed to initialize dialer: %v", err) } defer d.Close() // Tell the driver to use the AlloyDB Go Connector to create connections config.ConnConfig.DialFunc = func(ctx context.Context, _ string, instance string) (net.Conn, error) { return d.Dial(ctx, "projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>") } // Interact with the driver directly as you normally would conn, err := pgxpool.ConnectConfig(context.Background(), config) if err != nil { log.Fatalf("failed to connect: %v", connErr) } defer conn.Close() }
To use database/sql, call pgxv4.RegisterDriver with any necessary Dialer configuration.
import ( "database/sql" "cloud.google.com/go/alloydbconn" "cloud.google.com/go/alloydbconn/driver/pgxv4" ) func connect() { // adjust options as needed cleanup, err := pgxv4.RegisterDriver("alloydb") if err != nil { // ... handle error } defer cleanup() db, err := sql.Open( "alloydb", "host=projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE> user=myuser password=mypass dbname=mydb sslmode=disable", ) //... etc }
Constants
CloudPlatformScope
const CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
CloudPlatformScope is the default OAuth2 scope set on the API client.
Variables
ErrDialerClosed
var (
// ErrDialerClosed is used when a caller invokes Dial after closing the
// Dialer.
ErrDialerClosed = errors.New("alloydbconn: dialer is closed")
)
DialOption
type DialOption func(d *dialCfg)
A DialOption is an option for configuring how a Dialer's Dial call is executed.
func DialOptions
func DialOptions(opts ...DialOption) DialOption
DialOptions turns a list of DialOption instances into an DialOption.
func WithOneOffDialFunc
func WithOneOffDialFunc(dial func(ctx context.Context, network, addr string) (net.Conn, error)) DialOption
WithOneOffDialFunc configures the dial function on a one-off basis for an individual call to Dial. To configure a dial function across all invocations of Dial, use WithDialFunc.
func WithPSC
func WithPSC() DialOption
WithPSC returns a DialOption that specifies a PSC endpoint will be used to connect.
func WithPrivateIP
func WithPrivateIP() DialOption
WithPrivateIP returns a DialOption that specifies a private IP (VPC) will be used to connect.
func WithPublicIP
func WithPublicIP() DialOption
WithPublicIP returns a DialOption that specifies a public IP will be used to connect.
func WithTCPKeepAlive
func WithTCPKeepAlive(d time.Duration) DialOption
WithTCPKeepAlive returns a DialOption that specifies the tcp keep alive period for the connection returned by Dial.
Dialer
type Dialer struct {
// contains filtered or unexported fields
}
A Dialer is used to create connections to AlloyDB instance.
Use NewDialer to initialize a Dialer.
func NewDialer
NewDialer creates a new Dialer.
Initial calls to NewDialer make take longer than normal because generation of an RSA keypair is performed. Calls with a WithRSAKeyPair DialOption or after a default RSA keypair is generated will be faster.
func (*Dialer) Close
Close closes the Dialer; it prevents the Dialer from refreshing the information needed to connect.
func (*Dialer) Dial
func (d *Dialer) Dial(ctx context.Context, instance string, opts ...DialOption) (conn net.Conn, err error)
Dial returns a net.Conn connected to the specified AlloyDB instance. The instance argument must be the instance's URI, which is in the format projects/
Option
type Option func(d *dialerConfig)
An Option is an option for configuring a Dialer.
func WithAdminAPIEndpoint
WithAdminAPIEndpoint configures the underlying AlloyDB Admin API client to use the provided URL.
func WithContextLogger
func WithContextLogger(l debug.ContextLogger) Option
WithContextLogger configures a debug lgoger for reporting on internal operations. By default the debug logger is disabled.
func WithCredentialsFile
WithCredentialsFile returns an Option that specifies a service account or refresh token JSON credentials file to be used as the basis for authentication.
func WithCredentialsJSON
WithCredentialsJSON returns an Option that specifies a service account or refresh token JSON credentials to be used as the basis for authentication.
func WithDebugLogger
WithDebugLogger configures a debug logger for reporting on internal operations. By default the debug logger is disabled. Prefer WithContextLogger.
func WithDefaultDialOptions
func WithDefaultDialOptions(opts ...DialOption) Option
WithDefaultDialOptions returns an Option that specifies the default DialOptions used.
func WithDialFunc
WithDialFunc configures the function used to connect to the address on the named network. This option is generally unnecessary except for advanced use-cases. The function is used for all invocations of Dial. To configure a dial function per individual calls to dial, use WithOneOffDialFunc.
func WithHTTPClient
WithHTTPClient configures the underlying AlloyDB Admin API client with the provided HTTP client. This option is generally unnecessary except for advanced use-cases.
func WithIAMAuthN
func WithIAMAuthN() Option
WithIAMAuthN enables automatic IAM Authentication. If no token source has been configured (such as with WithTokenSource, WithCredentialsFile, etc), the dialer will use the default token source as defined by https://pkg.go.dev/golang.org/x/oauth2/google#FindDefaultCredentialsWithParams.
func WithLazyRefresh
func WithLazyRefresh() Option
WithLazyRefresh configures the dialer to refresh certificates on an as-needed basis. If a certificate is expired when a connection request occurs, the Go Connector will block the attempt and refresh the certificate immediately. This option is useful when running the Go Connector in environments where the CPU may be throttled, thus preventing a background goroutine from running consistently (e.g., in Cloud Run the CPU is throttled outside of a request context causing the background refresh to fail).
func WithOptOutOfAdvancedConnectionCheck
func WithOptOutOfAdvancedConnectionCheck() Option
WithOptOutOfAdvancedConnectionCheck disables the dataplane permission check. It is intended only for clients who are running in an environment where the workload's IP address is otherwise unknown and cannot be allow-listed in a VPC Service Control security perimeter. This option is incompatible with IAM Authentication.
NOTE: This option is for internal usage only and is meant to ease the migration when the advanced check will be required on the server. In future versions this will revert to a no-op and should not be used. If you think you need this option, open an issue on https://github.com/GoogleCloudPlatform/alloydb-go-connector for design advice.
func WithOptions
WithOptions turns a list of Option's into a single Option.
func WithRSAKey
func WithRSAKey(k *rsa.PrivateKey) Option
WithRSAKey returns an Option that specifies a rsa.PrivateKey used to represent the client.
func WithRefreshTimeout
WithRefreshTimeout returns an Option that sets a timeout on refresh operations. Defaults to 60s.
func WithStaticConnectionInfo
WithStaticConnectionInfo specifies an io.Reader from which to read static connection info. This is a dev-only option and should not be used in production as it will result in failed connections after the client certificate expires. It is also subject to breaking changes in the format. NOTE: The static connection info is not refreshed by the dialer. The JSON format supports multiple instances, regardless of cluster.
The reader should hold JSON with the following format:
{
"publicKey": "<PEM Encoded public RSA key>",
"privateKey": "<PEM Encoded private RSA key>",
"projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>": {
"ipAddress": "<PSA-based private IP address>",
"publicIpAddress": "<public IP address>",
"pscInstanceConfig": {
"pscDnsName": "<PSC DNS name>"
},
"pemCertificateChain": [
"<client cert>", "<intermediate cert>", "<CA cert>"
],
"caCert": "<CA cert>"
}
}
func WithTokenSource
func WithTokenSource(s oauth2.TokenSource) Option
WithTokenSource returns an Option that specifies an OAuth2 token source to be used as the basis for authentication.
func WithUserAgent
WithUserAgent returns an Option that sets the User-Agent.