Package cloud.google.com/go/alloydbconn (v1.16.0) Stay organized with collections Save and categorize content based on your preferences.
Package alloydbconn provides functions for authorizing and encryptingconnections. These functions can be used with a database driver toconnect to an AlloyDB cluster.
Creating a Dialer
To start working with this package, create a Dialer. There are two ways ofcreating a Dialer, which one you use depends on your database driver.
Users have the option of using thedatabase/sql interface or usingpgx directly.
To use a dialer withpgx, we recommend using connection pooling withpgxpool. To create the dialer use the NewDialer func.
import("context""net""cloud.google.com/go/alloydbconn""github.com/jackc/pgx/v4/pgxpool")funcconnect(){// Configure the driver to connect to the databasedsn:=fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",pgUser,pgPass,pgDB)config,err:=pgxpool.ParseConfig(dsn)iferr!=nil{log.Fatalf("failed to parse pgx config: %v",err)}// Create a new dialer with any optionsd,err:=alloydbconn.NewDialer(ctx)iferr!=nil{log.Fatalf("failed to initialize dialer: %v",err)}deferd.Close()// Tell the driver to use the AlloyDB Go Connector to create connectionsconfig.ConnConfig.DialFunc=func(ctxcontext.Context,_string,instancestring)(net.Conn,error){returnd.Dial(ctx,"projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>")}// Interact with the driver directly as you normally wouldconn,err:=pgxpool.ConnectConfig(context.Background(),config)iferr!=nil{log.Fatalf("failed to connect: %v",connErr)}deferconn.Close()}
To usedatabase/sql, call pgxv4.RegisterDriver with any necessary Dialerconfiguration.
import("database/sql""cloud.google.com/go/alloydbconn""cloud.google.com/go/alloydbconn/driver/pgxv4")funcconnect(){// adjust options as neededcleanup,err:=pgxv4.RegisterDriver("alloydb")iferr!=nil{// ... handle error}defercleanup()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
constCloudPlatformScope="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
typeDialOptionfunc(d*dialCfg)A DialOption is an option for configuring how a Dialer's Dial call isexecuted.
func DialOptions
funcDialOptions(opts...DialOption)DialOptionDialOptions turns a list of DialOption instances into an DialOption.
func WithDialIAMAuthN
funcWithDialIAMAuthN(enabledbool)DialOptionWithDialIAMAuthN allows calls to Dial to enable or disable IAM AuthN on aone-off basis, regardless whether the dialer itself is configured with IAMAuthN. There is no performance penalty to using this option.
func WithOneOffDialFunc
WithOneOffDialFunc configures the dial function on a one-off basis for anindividual call to Dial. To configure a dial function across all invocationsof Dial, use WithDialFunc.
func WithPSC
funcWithPSC()DialOptionWithPSC returns a DialOption that specifies a PSC endpoint will be used toconnect.
func WithPrivateIP
funcWithPrivateIP()DialOptionWithPrivateIP returns a DialOption that specifies a private IP (VPC) will beused to connect.
func WithPublicIP
funcWithPublicIP()DialOptionWithPublicIP returns a DialOption that specifies a public IP will be used toconnect.
func WithTCPKeepAlive
funcWithTCPKeepAlive(dtime.Duration)DialOptionWithTCPKeepAlive returns a DialOption that specifies the tcp keep aliveperiod for the connection returned by Dial.
Dialer
typeDialerstruct{// 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 anRSA keypair is performed. Calls with a WithRSAKeyPair DialOption or after a defaultRSA keypair is generated will be faster.
func (*Dialer) Close
Close closes the Dialer; it prevents the Dialer from refreshing the informationneeded to connect.
func (*Dialer) Dial
Dial returns a net.Conn connected to the specified AlloyDB instance. Theinstance argument must be the instance's URI, which is in the formatprojects/
Option
typeOptionfunc(d*dialerConfig)An Option is an option for configuring a Dialer.
func WithAdminAPIEndpoint
WithAdminAPIEndpoint configures the underlying AlloyDB Admin API client touse the provided URL.
func WithContextLogger
funcWithContextLogger(ldebug.ContextLogger)OptionWithContextLogger configures a debug lgoger for reporting on internaloperations. By default the debug logger is disabled.
func WithCredentialsFile
WithCredentialsFile returns an Option that specifies a service accountor refresh token JSON credentials file to be used as the basis forauthentication.
func WithCredentialsJSON
WithCredentialsJSON returns an Option that specifies a service accountor refresh token JSON credentials to be used as the basis for authentication.
func WithDebugLogger
WithDebugLogger configures a debug logger for reporting on internaloperations. By default the debug logger is disabled.Prefer WithContextLogger.
func WithDefaultDialOptions
funcWithDefaultDialOptions(opts...DialOption)OptionWithDefaultDialOptions returns an Option that specifies the defaultDialOptions used.
func WithDialFunc
WithDialFunc configures the function used to connect to the address on thenamed network. This option is generally unnecessary except for advanceduse-cases. The function is used for all invocations of Dial. To configurea dial function per individual calls to dial, use WithOneOffDialFunc.
func WithHTTPClient
WithHTTPClient configures the underlying AlloyDB Admin API client with theprovided HTTP client. This option is generally unnecessary except foradvanced use-cases.
func WithIAMAuthN
funcWithIAMAuthN()OptionWithIAMAuthN enables automatic IAM Authentication. If no token source hasbeen configured (such as with WithTokenSource, WithCredentialsFile, etc),the dialer will use the default token source as defined byhttps://pkg.go.dev/golang.org/x/oauth2/google#FindDefaultCredentialsWithParams.
func WithLazyRefresh
funcWithLazyRefresh()OptionWithLazyRefresh configures the dialer to refresh certificates on anas-needed basis. If a certificate is expired when a connection requestoccurs, the Go Connector will block the attempt and refresh the certificateimmediately. This option is useful when running the Go Connector inenvironments where the CPU may be throttled, thus preventing a backgroundgoroutine from running consistently (e.g., in Cloud Run the CPU is throttledoutside of a request context causing the background refresh to fail).
func WithOptOutOfAdvancedConnectionCheck
funcWithOptOutOfAdvancedConnectionCheck()OptionWithOptOutOfAdvancedConnectionCheck disables the dataplane permission check.It is intended only for clients who are running in an environment where theworkload's IP address is otherwise unknown and cannot be allow-listed in aVPC Service Control security perimeter. This option is incompatible with IAMAuthentication.
NOTE: This option is for internal usage only and is meant to ease themigration when the advanced check will be required on the server. In futureversions this will revert to a no-op and should not be used. If you thinkyou need this option, open an issue onhttps://github.com/GoogleCloudPlatform/alloydb-go-connector for designadvice.
func WithOptOutOfBuiltInTelemetry
funcWithOptOutOfBuiltInTelemetry()OptionWithOptOutOfBuiltInTelemetry disables the internal metric export. Bydefault, the Dialer will report on its internal operations to thealloydb.googleapis.com system metric prefix. These metrics help AlloyDBimprove performance and identify client connectivity problems. Presently,these metrics aren't public, but will be made public in the future. Todisable this telemetry, provide this option when initializing a Dialer.
func WithOptions
WithOptions turns a list of Option's into a single Option.
func WithRSAKey
funcWithRSAKey(k*rsa.PrivateKey)OptionWithRSAKey returns an Option that specifies a rsa.PrivateKey used torepresent the client.
func WithRefreshTimeout
WithRefreshTimeout returns an Option that sets a timeout on refreshoperations. Defaults to 60s.
func WithStaticConnectionInfo
WithStaticConnectionInfo specifies an io.Reader from which to read staticconnection info. This is adev-only option and should not be used inproduction as it will result in failed connections after the clientcertificate expires. It is also subject to breaking changes in the format.NOTE: The static connection info is not refreshed by the dialer. The JSONformat 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
funcWithTokenSource(soauth2.TokenSource)OptionWithTokenSource returns an Option that specifies an OAuth2 token sourceto be used as the basis for authentication.
func WithUserAgent
WithUserAgent returns an Option that sets the User-Agent.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-10-30 UTC.