Azure Documentation

Initialize the Azure Cosmos DB SDK for Go

This tutorial will guide you through the process of initializing the Azure Cosmos DB SDK in your Go application. Proper initialization is crucial for establishing a connection to your Cosmos DB account and interacting with your data.

Prerequisites

Step 1: Install the SDK

First, you need to add the Azure Cosmos DB Go SDK to your project's dependencies. Open your terminal or command prompt and run the following command:

go get github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos

Step 2: Import the necessary packages

In your Go application, import the required packages:

import (
    "context"
    "fmt"
    "log"

    "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

Step 3: Get your Cosmos DB Endpoint and Key

You'll need your Cosmos DB account's endpoint and primary key. You can find these in the Azure portal under your Cosmos DB account's "Keys" section.

Security Note: It is highly recommended to use Azure Key Vault to store and retrieve your Cosmos DB keys rather than hardcoding them directly into your application.

Step 4: Authenticate and Create a Client

The most common way to authenticate is by using a credential. For development, you can use a connection string or a primary key. For production environments, consider using Azure Identity for more secure authentication methods like Managed Identity or Service Principal.

Option 1: Using a Connection String (for local development)

If you have your connection string, you can use it directly. Replace the placeholder with your actual connection string.

func main() {
    // Replace with your Cosmos DB connection string
    connectionString := "YOUR_COSMOS_DB_CONNECTION_STRING"

    // Create a Cosmos DB client using the connection string
    client, err := azcosmos.NewClientFromConnectionString(connectionString, nil)
    if err != nil {
        log.Fatalf("Failed to create Cosmos DB client: %v", err)
    }

    fmt.Println("Cosmos DB client initialized successfully!")

    // Now you can use the 'client' to interact with your Cosmos DB account
    // ...
}

Option 2: Using Endpoint and Key (with Azure Identity)

This approach uses Azure Identity to authenticate. It's more secure for production scenarios.

func main() {
    // Replace with your Cosmos DB endpoint and database ID
    cosmosEndpoint := "YOUR_COSMOS_DB_ENDPOINT"
    databaseID := "YOUR_DATABASE_ID" // e.g., "mydatabase"

    // Create a credential using Azure Identity (e.g., DefaultAzureCredential)
    // This will attempt to authenticate using environment variables, managed identity,
    // Azure CLI, etc.
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        log.Fatalf("Failed to create Azure credential: %v", err)
    }

    // Create a Cosmos DB client using the endpoint and credential
    client, err := azcosmos.NewClient(cosmosEndpoint, cred, nil)
    if err != nil {
        log.Fatalf("Failed to create Cosmos DB client: %v", err)
    }

    // Get a handle to the database
    dbClient, err := client.NewDatabase(databaseID)
    if err != nil {
        log.Fatalf("Failed to get database client: %v", err)
    }

    fmt.Printf("Cosmos DB client initialized successfully for database: %s\n", databaseID)

    // Now you can use 'dbClient' to interact with your database
    // ...
}
Tip: For local development, you can set environment variables like AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET to use NewDefaultAzureCredential.

Step 5: Verify Initialization

Once the client is initialized, you can perform a simple operation, like listing databases, to verify the connection.

func main() {
    // ... (Client initialization code from Step 4) ...

    ctx := context.Background()

    // List databases to verify the connection
    pager := client.NewListDatabasesPager(nil)
    fmt.Println("Listing databases:")
    for pager.More() {
        page, err := pager.NextPage(ctx)
        if err != nil {
            log.Fatalf("Failed to advance page: %v", err)
        }
        for _, db := range page.Databases {
            fmt.Printf("  - %s\n", *db.ID)
        }
    }
}

Conclusion

Congratulations! You have successfully initialized the Azure Cosmos DB SDK for Go. You are now ready to proceed with creating databases, containers, and performing data operations.

In the next tutorial, we will cover how to create a database.