Spanner Omni 和 Spanner 使用 Go 用戶端程式庫的方式類似。本文說明如何設定 Go 用戶端程式庫,建立與 Spanner Omni 的安全連線。建立資料庫管理用戶端或資料庫用戶端時,請設定 spanner.ClientConfig,建立這些連線。
Go 用戶端程式庫支援純文字、TLS、TLS (含憑證) 和 mTLS 連線。
詳情請參閱 Spanner 說明文件中的「開始使用 Go 中的 Spanner」。
事前準備
如要搭配 Spanner Omni 使用 Go 用戶端程式庫,請使用 v1.94.0 以上版本的 Go 用戶端程式庫,以及 1.25 以上發布版本的 Go。
如要將 Spanner Go 模組新增至 go.mod 檔案,請執行下列指令:
go get cloud.google.com/go/spanner@v1.94.0
設定 ClientConfig 物件
如要使用 Go 用戶端程式庫建立 Client 或 DatabaseAdminClient,請指定 Type: spanner.OMNI 來設定 ClientConfig 物件,並使用 option.WithEndpoint() 提供端點。
以下範例說明如何為各項支援的安全性設定設定 ClientConfig 物件:
純文字
如要建立純文字連線,請在 spanner.ClientConfig 中將 UsePlainText 設為 true:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
UsePlainText: true,
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
TLS
如要建立 TLS 連線,請使用 CaCertificateFile 指定 CA 憑證的路徑:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
CaCertificateFile: "PATH_TO_CA_CERT",
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
使用認證資訊進行 TLS 驗證
如要透過使用者名稱和密碼驗證建立 TLS 連線,請指定 CaCertificateFile、Username 和 Password:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
CaCertificateFile: "PATH_TO_CA_CERT",
Username: "USERNAME",
Password: []byte("PASSWORD"),
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
mTLS
如要建立相互傳輸層安全標準 (mTLS) 連線,請指定 CaCertificateFile、ClientCertificateFile 和 ClientKeyFile:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
CaCertificateFile: "PATH_TO_CA_CERT",
ClientCertificateFile: "PATH_TO_CLIENT_CERT",
ClientKeyFile: "PATH_TO_CLIENT_KEY",
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
更改下列內容:
PATH_TO_CA_CERT:CA 憑證檔案的路徑。PATH_TO_CLIENT_CERT:用戶端憑證檔案的路徑。PATH_TO_CLIENT_KEY:用戶端金鑰檔案的路徑。