azuregoazure-cosmosdb

Unable to create CosmosDB database via go sdk


From Mac OS X, using the emulator for Azure CosmosDB running on a Docker container locally, I am able to use the explorer web portal to create a database. However, I am unable to use the Azure Go SDK to create a database, but the errors don't present that there was an issue creating the db.

Besides this, there are multiple SDKs and a lot of the documentation has mistakes in it, is there a canonical source where I can see a functioning Golang example of utilizing the CosmosDB emulator?


cred, err := azcosmos.NewKeyCredential(cosmosDbKey)
    handle(err)
    client, err := azcosmos.NewClientWithKey(cosmosDbEndpoint, cred, nil)
    handle(err)

    databaseProperties := azcosmos.DatabaseProperties{ID: "databaseName"}
    databaseResponse, err := client.CreateDatabase(context.Background(), databaseProperties, nil)

How can I get better visibility into what is going on here, the client is able to create even if I pass in empty strings instead of the proper key and endpoint.

Tried to use the Go SDK to create a database, was expecting it to appear in the emulator portal. I would also expect NewClientWithKey() to fail when the credentials are invalid, this is not the case.


Solution

  • The code below interacts with Azure Cosmos DB or Azure Cosmos DB Emulator and creates a new database in Azure Cosmos DB or Azure Cosmos DB Emulator.

    Azure Cosmos DB emulator:

    enter image description here

    The package used is "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos".

    go get -u github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos
    
    package main
    
    import (
        "context"
        "log"
    
        "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
    )
    
    func handle(err error) {
        if err != nil {
            log.Fatal(err)
        }
    }
    
    func main() {
        const (
            cosmosDbEndpoint = "your_cosmosdb_endpoint" 
            cosmosDbKey      = "your_cosmosdb_key"
            dbName           = "samdb1"
        )
    
        // Create a new client with the account key
        cred, err := azcosmos.NewKeyCredential(cosmosDbKey)
        handle(err)
        client, err := azcosmos.NewClientWithKey(cosmosDbEndpoint, cred, nil)
        handle(err)
    
        // Create a new database
        databaseProperties := azcosmos.DatabaseProperties{ID: dbName}
        _, err = client.CreateDatabase(context.Background(), databaseProperties, nil)
        handle(err)
    
        log.Println("Database created successfully:", dbName)
    }
    

    Output: enter image description here

    Azure Cosmos DB account:

    enter image description here