Categorygithub.com/Azure/azure-sdk-for-go/sdk/storage/azblob
modulepackage
1.6.1-beta.1
Repository: https://github.com/azure/azure-sdk-for-go.git
Documentation: pkg.go.dev

# README

Azure Blob Storage module for Go

PkgGoDev Build Status Code Coverage

Service Version: 2023-11-03

Azure Blob Storage is Microsoft's object storage solution for the cloud. Blob Storage is optimized for storing massive amounts of unstructured data - data that does not adhere to a particular data model or definition, such as text or binary data. For more information, see Introduction to Azure Blob Storage.

Use the Azure Blob Storage client module github.com/Azure/azure-sdk-for-go/sdk/storage/azblob to:

  • Authenticate clients with Azure Blob Storage
  • Manipulate containers and blobs in an Azure storage account

Key links:

Source code | API reference documentation | REST API documentation | Product documentation | Samples

Getting started

Prerequisites

az storage account create --name MyStorageAccount --resource-group MyResourceGroup --location westus --sku Standard_LRS

Install the package

Install the Azure Blob Storage client module for Go with go get:

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

If you plan to authenticate with Azure Active Directory (recommended), also install the azidentity module.

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

Authenticate the client

To interact with the Azure Blob Storage service, you'll need to create an instance of the azblob.Client type. The azidentity module makes it easy to add Azure Active Directory support for authenticating Azure SDK clients with their corresponding Azure services.

// create a credential for authenticating with Azure Active Directory
cred, err := azidentity.NewDefaultAzureCredential(nil)
// TODO: handle err

// create an azblob.Client for the specified storage account that uses the above credential
client, err := azblob.NewClient("https://MYSTORAGEACCOUNT.blob.core.windows.net/", cred, nil)
// TODO: handle err

Learn more about enabling Azure Active Directory for authentication with Azure Storage:

Other options for authentication include connection strings, shared key, shared access signatures (SAS), and anonymous public access. Use the appropriate client constructor function for the authentication mechanism you wish to use. For examples, see:

Key concepts

Blob Storage is designed for:

  • Serving images or documents directly to a browser.
  • Storing files for distributed access.
  • Streaming video and audio.
  • Writing to log files.
  • Storing data for backup and restore, disaster recovery, and archiving.
  • Storing data for analysis by an on-premises or Azure-hosted service.

Blob Storage offers three types of resources:

  • The storage account
  • One or more containers in a storage account
  • One or more blobs in a container

Instances of the azblob.Client type provide methods for manipulating containers and blobs within a storage account. The storage account is specified when the azblob.Client is constructed.

Specialized clients

The Azure Blob Storage client module for Go also provides specialized clients in various subpackages. Use these clients when you need to interact with a specific kind of blob. Learn more about block blobs, append blobs, and page blobs.

The blob package contains APIs common to all blob types. This includes APIs for deleting and undeleting a blob, setting metadata, and more.

The lease package contains clients for managing leases on blobs and containers. See the REST API reference for general information on leases.

The container package contains APIs specific to containers. This includes APIs for setting access policies or properties, and more.

The service package contains APIs specific to the Blob service. This includes APIs for manipulating containers, retrieving account information, and more.

The sas package contains utilities to aid in the creation and manipulation of shared access signature (SAS) tokens. See the package's documentation for more information.

Goroutine safety

We guarantee that all client instance methods are goroutine-safe and independent of each other (see guideline). This ensures that the recommendation to reuse client instances is always safe, even across goroutines.

Blob metadata

Blob metadata name-value pairs are valid HTTP headers and should adhere to all restrictions governing HTTP headers. Metadata names must be valid HTTP header names, may contain only ASCII characters, and should be treated as case-insensitive. Base64-encode or URL-encode metadata values containing non-ASCII characters.

Additional concepts

Client options | Accessing the response | Handling failures | Logging

Examples

Upload a blob

const (
	account       = "https://MYSTORAGEACCOUNT.blob.core.windows.net/"
	containerName = "sample-container"
	blobName      = "sample-blob"
	sampleFile    = "path/to/sample/file"
)

// authenticate with Azure Active Directory
cred, err := azidentity.NewDefaultAzureCredential(nil)
// TODO: handle error

// create a client for the specified storage account
client, err := azblob.NewClient(account, cred, nil)
// TODO: handle error

// open the file for reading
file, err := os.OpenFile(sampleFile, os.O_RDONLY, 0)
// TODO: handle error
defer file.Close()

// upload the file to the specified container with the specified blob name
_, err = client.UploadFile(context.TODO(), containerName, blobName, file, nil)
// TODO: handle error

Download a blob

// this example accesses a public blob via anonymous access, so no credentials are required
client, err := azblob.NewClientWithNoCredential("https://azurestoragesamples.blob.core.windows.net/", nil)
// TODO: handle error

// create or open a local file where we can download the blob
file, err := os.Create("cloud.jpg")
// TODO: handle error
defer file.Close()

// download the blob
_, err = client.DownloadFile(context.TODO(), "samples", "cloud.jpg", file, nil)
// TODO: handle error

Enumerate blobs

const (
	account       = "https://MYSTORAGEACCOUNT.blob.core.windows.net/"
	containerName = "sample-container"
)

// authenticate with Azure Active Directory
cred, err := azidentity.NewDefaultAzureCredential(nil)
// TODO: handle error

// create a client for the specified storage account
client, err := azblob.NewClient(account, cred, nil)
// TODO: handle error

// blob listings are returned across multiple pages
pager := client.NewListBlobsFlatPager(containerName, nil)

// continue fetching pages until no more remain
for pager.More() {
  // advance to the next page
	page, err := pager.NextPage(context.TODO())
	// TODO: handle error

	// print the blob names for this page
	for _, blob := range page.Segment.BlobItems {
		fmt.Println(*blob.Name)
	}
}

Troubleshooting

All Blob service operations will return an *azcore.ResponseError on failure with a populated ErrorCode field. Many of these errors are recoverable. The bloberror package provides the possible Storage error codes along with helper facilities for error handling.

const (
	connectionString = "<connection_string>"
	containerName    = "sample-container"
)

// create a client with the provided connection string
client, err := azblob.NewClientFromConnectionString(connectionString, nil)
// TODO: handle error

// try to delete the container, avoiding any potential race conditions with an in-progress or completed deletion
_, err = client.DeleteContainer(context.TODO(), containerName, nil)

if bloberror.HasCode(err, bloberror.ContainerBeingDeleted, bloberror.ContainerNotFound) {
	// ignore any errors if the container is being deleted or already has been deleted
} else if err != nil {
	// TODO: some other error
}

Next steps

Get started with our Blob samples. They contain complete examples of the above snippets and more.

Contributing

See the Storage CONTRIBUTING.md for details on building, testing, and contributing to this library.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

NewClient creates an instance of Client with the specified values.
NewClientFromConnectionString creates an instance of Client with the specified values.
NewClientWithNoCredential creates an instance of Client with the specified values.
NewClientWithSharedKeyCredential creates an instance of Client with the specified values.
NewSharedKeyCredential creates an immutable SharedKeyCredential containing the storage account's name and either its primary or secondary key.
ParseURL parses a URL initializing URLParts' fields including any SAS-related & snapshot query parameters.
PossibleDeleteSnapshotsOptionTypeValues returns the possible values for the DeleteSnapshotsOptionType const type.
PossiblePublicAccessTypeValues returns the possible values for the PublicAccessType const type.

# Constants

No description provided by the author
No description provided by the author
EventSubmitBatch is used for logging events related to submit blob batch operation.
EventUpload is used for logging events related to upload operation.
No description provided by the author
No description provided by the author

# Structs

Client represents a URL to an Azure Storage blob; the blob may be a block blob, append blob, or page blob.

# Type aliases

AccessConditions identifies blob-specific access conditions which you optionally set.
ClientOptions contains the optional parameters when creating a Client.
CPKInfo contains a group of parameters for client provided encryption key.
CPKScopeInfo contains a group of parameters for the ContainerClient.Create method.
CreateContainerOptions contains the optional parameters for the ContainerClient.Create method.
CreateContainerResponse contains the response from method container.Client.Create.
DeleteBlobOptions contains the optional parameters for the Client.Delete method.
DeleteBlobResponse contains the response from method blob.Client.Delete.
DeleteContainerOptions contains the optional parameters for the container.Client.Delete method.
DeleteContainerResponse contains the response from method container.Client.Delete.
DeleteSnapshotsOptionType defines values for DeleteSnapshotsOptionType.
DownloadBufferOptions identifies options used by the DownloadBuffer and DownloadFile functions.
DownloadFileOptions identifies options used by the DownloadBuffer and DownloadFile functions.
DownloadStreamOptions contains the optional parameters for the Client.DownloadStream method.
DownloadStreamResponse wraps AutoRest generated BlobDownloadResponse and helps to provide info for retry.
HTTPRange defines a range of bytes within an HTTP resource, starting at offset and ending at offset+count.
ListBlobsFlatOptions contains the optional parameters for the container.Client.ListBlobFlatSegment method.
ListBlobsFlatResponse contains the response from method container.Client.ListBlobFlatSegment.
ListBlobsFlatSegmentResponse - An enumeration of blobs.
ListBlobsInclude indicates what additional information the service should return with each blob.
ListContainersInclude indicates what additional information the service should return with each container.
ListContainersOptions contains the optional parameters for the container.Client.ListContainers operation.
ListContainersResponse contains the response from method service.Client.ListContainersSegment.
ListContainersSegmentResponse - An enumeration of containers.
ObjectReplicationPolicy are deserialized attributes.
PublicAccessType defines values for AccessType - private (default) or blob or container.
RetryReaderOptions contains properties which can help to decide when to do retry.
SharedKeyCredential contains an account's name and its primary or secondary key.
UploadBufferOptions provides set of configurations for UploadBuffer operation.
UploadBufferResponse contains the response from method Client.UploadBuffer/Client.UploadFile.
UploadFileOptions provides set of configurations for UploadFile operation.
UploadFileResponse contains the response from method Client.UploadBuffer/Client.UploadFile.
UploadResponse contains the response from method blockblob.Client.CommitBlockList.
UploadStreamOptions provides set of configurations for UploadStream operation.
UploadStreamResponse contains the response from method Client.CommitBlockList.
URLParts object represents the components that make up an Azure Storage Container/Blob URL.