Download a blob with Go

This article shows how to download a blob using the Azure Storage client module for Go. You can download blob data to various destinations, including a local file path, stream, or text string.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows how to set up a project to work with the Azure Blob Storage client module for Go. The steps include module installation, adding import paths, and creating an authorized client object. For details, see Get started with Azure Blob Storage and Go.

Install modules

Install the azblob module using the following command:

go get github.com/Azure/azure-sdk-for-go/sdk/storage/azblob

To authenticate with Microsoft Entra ID (recommended), install the azidentity module using the following command:

go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

Add import paths

In your code file, add the following import paths:

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)

These import paths represent the minimum needed to get started. Some code examples in this article might require additional import paths. For specific details and example usage, see Code samples.

Create a client object

To connect an app to Blob Storage, create a client object using azblob.NewClient. The following example shows how to create a client object using DefaultAzureCredential for authorization:

func getServiceClientTokenCredential(accountURL string) *azblob.Client {
    // Create a new service client with token credential
    credential, err := azidentity.NewDefaultAzureCredential(nil)
    handleError(err)

    client, err := azblob.NewClient(accountURL, credential, nil)
    handleError(err)

    return client
}

Authorization

The authorization mechanism must have the necessary permissions to perform a download operation. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Reader or higher. To learn more, see the authorization guidance for Get Blob (REST API).

Download a blob

You can use any of the following methods to download a blob:

Download to a file path

The following example downloads a blob to a file path:

func downloadBlobToFile(client *azblob.Client, containerName string, blobName string) {
    // Create or open a local file where we can download the blob
    file, err := os.Create("path/to/sample/file")
    handleError(err)

    // Download the blob to the local file
    _, err = client.DownloadFile(context.TODO(), containerName, blobName, file, nil)
    handleError(err)
}

Download to a stream

The following example downloads a blob to a stream, and reads from the stream by calling the NewRetryReader method.

func downloadBlobToStream(client *azblob.Client, containerName string, blobName string) {
    // Download the blob
    get, err := client.DownloadStream(context.TODO(), containerName, blobName, nil)
    handleError(err)

    downloadedData := bytes.Buffer{}
    retryReader := get.NewRetryReader(context.TODO(), &azblob.RetryReaderOptions{})
    _, err = downloadedData.ReadFrom(retryReader)
    handleError(err)

    err = retryReader.Close()
    handleError(err)

    // Print the contents of the blob we created
    fmt.Println("Blob contents:")
    fmt.Println(downloadedData.String())
}

Specify data transfer options for download

You can set configuration options when downloading a blob to optimize performance. The following configuration options are available for download operations:

  • BlockSize: The size of each block when downloading a block blob. The default value is 4 MB.
  • Concurrency: The maximum number of parallel connections to use during download. The default value is 5.

These options are available when downloading using the following methods:

The DownloadStream method doesn't support these options, and downloads data in a single request.

For more information on transfer size limits for Blob Storage, see Scale targets for Blob storage.

The following code example shows how to specify data transfer options using the DownloadFileOptions. The values provided in this sample aren't intended to be a recommendation. To properly tune these values, you need to consider the specific needs of your app.

func downloadBlobTransferOptions(client *azblob.Client, containerName string, blobName string) {
    // Create or open a local file where we can download the blob
    file, err := os.Create("path/to/sample/file")
    handleError(err)

    // Download the blob to the local file
    _, err = client.DownloadFile(context.TODO(), containerName, blobName, file,
        &azblob.DownloadFileOptions{
            BlockSize:   int64(4 * 1024 * 1024), // 4 MiB
            Concurrency: uint16(2),
        })
    handleError(err)
}

To learn more about tuning data transfer options, see Performance tuning for uploads and downloads with Go.

Note

The code samples in this guide are intended to help you get started with Azure Blob Storage and Go. You should modify error handling and Context values to meet the needs of your application.

Resources

To learn more about how to download blobs using the Azure Blob Storage client module for Go, see the following resources.

Code samples

REST API operations

The Azure SDK for Go contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar Go paradigms. The client library methods for downloading blobs use the following REST API operation:

Client module resources

  • This article is part of the Blob Storage developer guide for Go. To learn more, see the full list of developer guide articles at Build your Go app.