Documentation
¶
Overview ¶
Example ¶
This example is a quick-starter and demonstrates how to get started using the Azure Blob Storage SDK for Go.
package main
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// Your account name and key can be obtained from the Azure Portal.
accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
if !ok {
panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
}
accountKey, ok := os.LookupEnv("AZURE_STORAGE_PRIMARY_ACCOUNT_KEY")
if !ok {
panic("AZURE_STORAGE_PRIMARY_ACCOUNT_KEY could not be found")
}
cred, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
// The service URL for blob endpoints is usually in the form: http(s)://<account>.blob.core.windows.net/
serviceClient, err := azblob.NewServiceClientWithSharedKey(fmt.Sprintf("https://%s.blob.core.windows.net/", accountName), cred, nil)
if err != nil {
log.Fatal(err)
}
// ===== 1. Create a container =====
// First, create a container client, and use the Create method to create a new container in your account
containerClient, err := serviceClient.NewContainerClient("testcontainer")
if err != nil {
log.Fatal(err)
}
// All APIs have an options' bag struct as a parameter.
// The options' bag struct allows you to specify optional parameters such as metadata, public access types, etc.
// If you want to use the default options, pass in nil.
_, err = containerClient.Create(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// ===== 2. Upload and Download a block blob =====
uploadData := "Hello world!"
// Create a new blockBlobClient from the containerClient
blockBlobClient, err := containerClient.NewBlockBlobClient("HelloWorld.txt")
if err != nil {
log.Fatal(err)
}
// Upload data to the block blob
blockBlobUploadOptions := azblob.BlockBlobUploadOptions{
Metadata: map[string]string{"Foo": "Bar"},
TagsMap: map[string]string{"Year": "2022"},
}
_, err = blockBlobClient.Upload(context.TODO(), streaming.NopCloser(strings.NewReader(uploadData)), &blockBlobUploadOptions)
if err != nil {
log.Fatal(err)
}
// Download the blob's contents and ensure that the download worked properly
blobDownloadResponse, err := blockBlobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Use the bytes.Buffer object to read the downloaded data.
// RetryReaderOptions has a lot of in-depth tuning abilities, but for the sake of simplicity, we'll omit those here.
reader := blobDownloadResponse.Body(nil)
downloadData, err := ioutil.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
if string(downloadData) != uploadData {
log.Fatal("Uploaded data should be same as downloaded data")
}
err = reader.Close()
if err != nil {
return
}
// ===== 3. List blobs =====
// List methods returns a pager object which can be used to iterate over the results of a paging operation.
// To iterate over a page use the NextPage(context.Context) to fetch the next page of results.
// PageResponse() can be used to iterate over the results of the specific page.
// Always check the Err() method after paging to see if an error was returned by the pager. A pager will return either an error or the page of results.
pager := containerClient.ListBlobsFlat(nil)
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, v := range resp.Segment.BlobItems {
fmt.Println(*v.Name)
}
}
if err = pager.Err(); err != nil {
log.Fatal(err)
}
// Delete the blob.
_, err = blockBlobClient.Delete(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Delete the container.
_, err = containerClient.Delete(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
}
Example (BlobSnapshots) ¶
This example show how to create a blob, take a snapshot of it, update the base blob, read from the blob snapshot, list blobs with their snapshots, and delete blob snapshots.
package main
import (
"bytes"
"context"
"fmt"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
u := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName)
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClientWithSharedKey(u, credential, nil)
if err != nil {
log.Fatal(err)
}
// Create a blockBlobClient object to a blob in the container.
baseBlobClient, _ := containerClient.NewBlockBlobClient("Original.txt")
// Create the original blob:
_, err = baseBlobClient.Upload(context.TODO(), streaming.NopCloser(streaming.NopCloser(strings.NewReader("Some text"))), nil)
if err != nil {
log.Fatal(err)
}
// Create a snapshot of the original blob & save its timestamp:
createSnapshot, err := baseBlobClient.CreateSnapshot(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
snapshot := *createSnapshot.Snapshot
// Modify the original blob:
_, err = baseBlobClient.Upload(context.TODO(), streaming.NopCloser(strings.NewReader("New text")), nil)
if err != nil {
log.Fatal(err)
}
// Download the modified blob:
get, err := baseBlobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
b := bytes.Buffer{}
reader := get.Body(nil)
_, err = b.ReadFrom(reader)
if err != nil {
return
}
err = reader.Close()
if err != nil {
return
}
fmt.Println(b.String())
// Show snapshot blob via original blob URI & snapshot time:
snapshotBlobClient, _ := baseBlobClient.WithSnapshot(snapshot)
get, err = snapshotBlobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
b.Reset()
reader = get.Body(nil)
_, err = b.ReadFrom(reader)
if err != nil {
return
}
err = reader.Close()
if err != nil {
return
}
fmt.Println(b.String())
// FYI: You can get the base blob URL from one of its snapshot by passing "" to WithSnapshot:
baseBlobClient, _ = snapshotBlobClient.WithSnapshot("")
// Show all blobs in the container with their snapshots:
// List the blob(s) in our container; since a container may hold millions of blobs, this is done 1 segment at a time.
pager := containerClient.ListBlobsFlat(nil)
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, blob := range resp.Segment.BlobItems {
// Process the blobs returned
snapTime := "N/A"
if blob.Snapshot != nil {
snapTime = *blob.Snapshot
}
fmt.Printf("Blob name: %s, Snapshot: %s\n", *blob.Name, snapTime)
}
}
if err := pager.Err(); err != nil {
log.Fatal(err)
}
// Promote read-only snapshot to writable base blob:
_, err = baseBlobClient.StartCopyFromURL(context.TODO(), snapshotBlobClient.URL(), nil)
if err != nil {
log.Fatal(err)
}
// When calling Delete on a base blob:
// DeleteSnapshotsOptionOnly deletes all the base blob's snapshots but not the base blob itself
// DeleteSnapshotsOptionInclude deletes the base blob & all its snapshots.
// DeleteSnapshotOptionNone produces an error if the base blob has any snapshots.
_, err = baseBlobClient.Delete(context.TODO(), &azblob.BlobDeleteOptions{DeleteSnapshots: azblob.DeleteSnapshotsOptionTypeInclude.ToPtr()})
if err != nil {
log.Fatal(err)
}
}
Example (ProgressUploadDownload) ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// Create a credentials object with your Azure Storage Account name and key.
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
// From the Azure portal, get your Storage account blob service URL endpoint.
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName)
// Create an serviceClient object that wraps the service URL and a request pipeline to making requests.
containerClient, err := azblob.NewContainerClientWithSharedKey(containerURL, credential, nil)
if err != nil {
log.Fatal(err)
}
// Here's how to create a blob with HTTP headers and metadata (I'm using the same metadata that was put on the container):
blobClient, _ := containerClient.NewBlockBlobClient("Data.bin")
// requestBody is the stream of data to write
requestBody := streaming.NopCloser(strings.NewReader("Some text to write"))
// Wrap the request body in a RequestBodyProgress and pass a callback function for progress reporting.
requestProgress := streaming.NewRequestProgress(streaming.NopCloser(requestBody), func(bytesTransferred int64) {
fmt.Printf("Wrote %d of %d bytes.", bytesTransferred, requestBody)
})
_, err = blobClient.Upload(context.TODO(), requestProgress, &azblob.BlockBlobUploadOptions{
HTTPHeaders: &azblob.BlobHTTPHeaders{
BlobContentType: to.Ptr("text/html; charset=utf-8"),
BlobContentDisposition: to.Ptr("attachment"),
},
})
if err != nil {
log.Fatal(err)
}
// Here's how to read the blob's data with progress reporting:
get, err := blobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Wrap the response body in a ResponseBodyProgress and pass a callback function for progress reporting.
responseBody := streaming.NewResponseProgress(
get.Body(nil),
func(bytesTransferred int64) {
fmt.Printf("Read %d of %d bytes.", bytesTransferred, *get.ContentLength)
},
)
downloadedData := &bytes.Buffer{}
_, err = downloadedData.ReadFrom(responseBody)
if err != nil {
return
}
err = responseBody.Close()
if err != nil {
return
}
fmt.Printf("Downloaded data: %s\n", downloadedData.String())
}
Index ¶
- Constants
- Variables
- func DoBatchTransfer(ctx context.Context, o BatchTransferOptions) error
- func FormatTimesForSASSigning(startTime, expiryTime, snapshotTime time.Time) (string, string, string)
- func NewRetryReader(ctx context.Context, initialResponse *http.Response, info HTTPGetterInfo, ...) io.ReadCloser
- type AccessPolicy
- type AccessPolicyPermission
- type AccessTier
- type AccountKind
- type AccountSASPermissions
- type AccountSASResourceTypes
- type AccountSASServices
- type AccountSASSignatureValues
- type AppendBlobAppendBlockFromURLOptions
- type AppendBlobAppendBlockFromURLResponse
- type AppendBlobAppendBlockOptions
- type AppendBlobAppendBlockResponse
- type AppendBlobClient
- func NewAppendBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*AppendBlobClient, error)
- func NewAppendBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*AppendBlobClient, error)
- func NewAppendBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*AppendBlobClient, error)
- func (ab *AppendBlobClient) AppendBlock(ctx context.Context, body io.ReadSeekCloser, ...) (AppendBlobAppendBlockResponse, error)
- func (ab *AppendBlobClient) AppendBlockFromURL(ctx context.Context, source string, o *AppendBlobAppendBlockFromURLOptions) (AppendBlobAppendBlockFromURLResponse, error)
- func (ab *AppendBlobClient) Create(ctx context.Context, options *AppendBlobCreateOptions) (AppendBlobCreateResponse, error)
- func (ab *AppendBlobClient) SealAppendBlob(ctx context.Context, options *AppendBlobSealOptions) (AppendBlobSealResponse, error)
- func (ab *AppendBlobClient) WithSnapshot(snapshot string) (*AppendBlobClient, error)
- func (ab *AppendBlobClient) WithVersionID(versionID string) (*AppendBlobClient, error)
- type AppendBlobCreateOptions
- type AppendBlobCreateResponse
- type AppendBlobSealOptions
- type AppendBlobSealResponse
- type AppendPositionAccessConditions
- type ArchiveStatus
- type ArrowConfiguration
- type ArrowField
- type BatchTransferOptions
- type BlobAbortCopyFromURLResponse
- type BlobAbortCopyOptions
- type BlobAccessConditions
- type BlobAcquireLeaseOptions
- type BlobAcquireLeaseResponse
- type BlobBreakLeaseOptions
- type BlobBreakLeaseResponse
- type BlobChangeLeaseOptions
- type BlobChangeLeaseResponse
- type BlobClient
- func NewBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*BlobClient, error)
- func NewBlobClientFromConnectionString(connectionString, containerName, blobName string, options *ClientOptions) (*BlobClient, error)
- func NewBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*BlobClient, error)
- func NewBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*BlobClient, error)
- func (b *BlobClient) AbortCopyFromURL(ctx context.Context, copyID string, options *BlobAbortCopyOptions) (BlobAbortCopyFromURLResponse, error)
- func (b *BlobClient) CreateSnapshot(ctx context.Context, options *BlobCreateSnapshotOptions) (BlobCreateSnapshotResponse, error)
- func (b *BlobClient) Delete(ctx context.Context, o *BlobDeleteOptions) (BlobDeleteResponse, error)
- func (b *BlobClient) Download(ctx context.Context, options *BlobDownloadOptions) (BlobDownloadResponse, error)
- func (b *BlobClient) DownloadToBuffer(ctx context.Context, offset int64, count int64, _bytes []byte, ...) error
- func (b *BlobClient) DownloadToFile(ctx context.Context, offset int64, count int64, file *os.File, ...) error
- func (b *BlobClient) DownloadToWriterAt(ctx context.Context, offset int64, count int64, writer io.WriterAt, ...) error
- func (b *BlobClient) GetProperties(ctx context.Context, options *BlobGetPropertiesOptions) (BlobGetPropertiesResponse, error)
- func (b *BlobClient) GetSASToken(permissions BlobSASPermissions, start time.Time, expiry time.Time) (SASQueryParameters, error)
- func (b *BlobClient) GetTags(ctx context.Context, options *BlobGetTagsOptions) (BlobGetTagsResponse, error)
- func (b *BlobClient) NewBlobLeaseClient(leaseID *string) (*BlobLeaseClient, error)
- func (b *BlobClient) SetHTTPHeaders(ctx context.Context, blobHttpHeaders BlobHTTPHeaders, ...) (BlobSetHTTPHeadersResponse, error)
- func (b *BlobClient) SetMetadata(ctx context.Context, metadata map[string]string, ...) (BlobSetMetadataResponse, error)
- func (b *BlobClient) SetTags(ctx context.Context, options *BlobSetTagsOptions) (BlobSetTagsResponse, error)
- func (b *BlobClient) SetTier(ctx context.Context, tier AccessTier, options *BlobSetTierOptions) (BlobSetTierResponse, error)
- func (b *BlobClient) StartCopyFromURL(ctx context.Context, copySource string, options *BlobStartCopyOptions) (BlobStartCopyFromURLResponse, error)
- func (b *BlobClient) URL() string
- func (b *BlobClient) Undelete(ctx context.Context, o *BlobUndeleteOptions) (BlobUndeleteResponse, error)
- func (b *BlobClient) WithSnapshot(snapshot string) (*BlobClient, error)
- func (b *BlobClient) WithVersionID(versionID string) (*BlobClient, error)
- type BlobCreateSnapshotOptions
- type BlobCreateSnapshotResponse
- type BlobDeleteOptions
- type BlobDeleteResponse
- type BlobDeleteType
- type BlobDownloadOptions
- type BlobDownloadResponse
- type BlobExpiryOptions
- type BlobFlatListSegment
- type BlobGeoReplicationStatus
- type BlobGetPropertiesOptions
- type BlobGetPropertiesResponse
- type BlobGetTagsOptions
- type BlobGetTagsResponse
- type BlobHTTPHeaders
- type BlobHierarchyListSegment
- type BlobImmutabilityPolicyMode
- type BlobItemInternal
- type BlobLeaseClient
- func (blc *BlobLeaseClient) AcquireLease(ctx context.Context, options *BlobAcquireLeaseOptions) (BlobAcquireLeaseResponse, error)
- func (blc *BlobLeaseClient) BreakLease(ctx context.Context, options *BlobBreakLeaseOptions) (BlobBreakLeaseResponse, error)
- func (blc *BlobLeaseClient) ChangeLease(ctx context.Context, options *BlobChangeLeaseOptions) (BlobChangeLeaseResponse, error)
- func (blc *BlobLeaseClient) ReleaseLease(ctx context.Context, options *ReleaseLeaseBlobOptions) (BlobReleaseLeaseResponse, error)
- func (blc *BlobLeaseClient) RenewLease(ctx context.Context, options *BlobRenewLeaseOptions) (BlobRenewLeaseResponse, error)
- type BlobPrefix
- type BlobPropertiesInternal
- type BlobReleaseLeaseResponse
- type BlobRenewLeaseOptions
- type BlobRenewLeaseResponse
- type BlobSASPermissions
- type BlobSASSignatureValues
- type BlobSetHTTPHeadersOptions
- type BlobSetHTTPHeadersResponse
- type BlobSetMetadataOptions
- type BlobSetMetadataResponse
- type BlobSetTagsOptions
- type BlobSetTagsResponse
- type BlobSetTierOptions
- type BlobSetTierResponse
- type BlobStartCopyFromURLResponse
- type BlobStartCopyOptions
- type BlobTag
- type BlobTags
- type BlobType
- type BlobURLParts
- type BlobUndeleteOptions
- type BlobUndeleteResponse
- type Block
- type BlockBlobClient
- func NewBlockBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*BlockBlobClient, error)
- func NewBlockBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*BlockBlobClient, error)
- func NewBlockBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*BlockBlobClient, error)
- func (bb *BlockBlobClient) CommitBlockList(ctx context.Context, base64BlockIDs []string, ...) (BlockBlobCommitBlockListResponse, error)
- func (bb *BlockBlobClient) CopyFromURL(ctx context.Context, source string, options *BlockBlobCopyFromURLOptions) (BlockBlobCopyFromURLResponse, error)
- func (bb *BlockBlobClient) GetBlockList(ctx context.Context, listType BlockListType, ...) (BlockBlobGetBlockListResponse, error)
- func (bb *BlockBlobClient) StageBlock(ctx context.Context, base64BlockID string, body io.ReadSeekCloser, ...) (BlockBlobStageBlockResponse, error)
- func (bb *BlockBlobClient) StageBlockFromURL(ctx context.Context, base64BlockID string, sourceURL string, ...) (BlockBlobStageBlockFromURLResponse, error)
- func (bb *BlockBlobClient) Upload(ctx context.Context, body io.ReadSeekCloser, options *BlockBlobUploadOptions) (BlockBlobUploadResponse, error)
- func (bb *BlockBlobClient) UploadBuffer(ctx context.Context, b []byte, o UploadOption) (*http.Response, error)
- func (bb *BlockBlobClient) UploadFile(ctx context.Context, file *os.File, o UploadOption) (*http.Response, error)
- func (bb *BlockBlobClient) UploadStream(ctx context.Context, body io.Reader, o UploadStreamOptions) (BlockBlobCommitBlockListResponse, error)
- func (bb *BlockBlobClient) WithSnapshot(snapshot string) (*BlockBlobClient, error)
- func (bb *BlockBlobClient) WithVersionID(versionID string) (*BlockBlobClient, error)
- type BlockBlobCommitBlockListOptions
- type BlockBlobCommitBlockListResponse
- type BlockBlobCopyFromURLOptions
- type BlockBlobCopyFromURLResponse
- type BlockBlobGetBlockListOptions
- type BlockBlobGetBlockListResponse
- type BlockBlobStageBlockFromURLOptions
- type BlockBlobStageBlockFromURLResponse
- type BlockBlobStageBlockOptions
- type BlockBlobStageBlockResponse
- type BlockBlobUploadOptions
- type BlockBlobUploadResponse
- type BlockList
- type BlockListType
- type BlockLookupList
- type ClearRange
- type ClientOptions
- type ContainerAccessConditions
- type ContainerAcquireLeaseOptions
- type ContainerAcquireLeaseResponse
- type ContainerBreakLeaseOptions
- type ContainerBreakLeaseResponse
- type ContainerChangeLeaseOptions
- type ContainerChangeLeaseResponse
- type ContainerClient
- func NewContainerClient(containerURL string, cred azcore.TokenCredential, options *ClientOptions) (*ContainerClient, error)
- func NewContainerClientFromConnectionString(connectionString string, containerName string, options *ClientOptions) (*ContainerClient, error)
- func NewContainerClientWithNoCredential(containerURL string, options *ClientOptions) (*ContainerClient, error)
- func NewContainerClientWithSharedKey(containerURL string, cred *SharedKeyCredential, options *ClientOptions) (*ContainerClient, error)
- func (c *ContainerClient) Create(ctx context.Context, options *ContainerCreateOptions) (ContainerCreateResponse, error)
- func (c *ContainerClient) Delete(ctx context.Context, o *ContainerDeleteOptions) (ContainerDeleteResponse, error)
- func (c *ContainerClient) GetAccessPolicy(ctx context.Context, o *ContainerGetAccessPolicyOptions) (ContainerGetAccessPolicyResponse, error)
- func (c *ContainerClient) GetProperties(ctx context.Context, o *ContainerGetPropertiesOptions) (ContainerGetPropertiesResponse, error)
- func (c *ContainerClient) GetSASURL(permissions ContainerSASPermissions, start time.Time, expiry time.Time) (string, error)
- func (c *ContainerClient) ListBlobsFlat(o *ContainerListBlobsFlatOptions) *ContainerListBlobFlatPager
- func (c *ContainerClient) ListBlobsHierarchy(delimiter string, o *ContainerListBlobsHierarchyOptions) *ContainerListBlobHierarchyPager
- func (c *ContainerClient) NewAppendBlobClient(blobName string) (*AppendBlobClient, error)
- func (c *ContainerClient) NewBlobClient(blobName string) (*BlobClient, error)
- func (c *ContainerClient) NewBlockBlobClient(blobName string) (*BlockBlobClient, error)
- func (c *ContainerClient) NewContainerLeaseClient(leaseID *string) (*ContainerLeaseClient, error)
- func (c *ContainerClient) NewPageBlobClient(blobName string) (*PageBlobClient, error)
- func (c *ContainerClient) SetAccessPolicy(ctx context.Context, o *ContainerSetAccessPolicyOptions) (ContainerSetAccessPolicyResponse, error)
- func (c *ContainerClient) SetMetadata(ctx context.Context, o *ContainerSetMetadataOptions) (ContainerSetMetadataResponse, error)
- func (c *ContainerClient) URL() string
- type ContainerCpkScopeInfo
- type ContainerCreateOptions
- type ContainerCreateResponse
- type ContainerDeleteOptions
- type ContainerDeleteResponse
- type ContainerGetAccessPolicyOptions
- type ContainerGetAccessPolicyResponse
- type ContainerGetPropertiesOptions
- type ContainerGetPropertiesResponse
- type ContainerItem
- type ContainerLeaseClient
- func (clc *ContainerLeaseClient) AcquireLease(ctx context.Context, options *ContainerAcquireLeaseOptions) (ContainerAcquireLeaseResponse, error)
- func (clc *ContainerLeaseClient) BreakLease(ctx context.Context, options *ContainerBreakLeaseOptions) (ContainerBreakLeaseResponse, error)
- func (clc *ContainerLeaseClient) ChangeLease(ctx context.Context, options *ContainerChangeLeaseOptions) (ContainerChangeLeaseResponse, error)
- func (clc *ContainerLeaseClient) ReleaseLease(ctx context.Context, options *ContainerReleaseLeaseOptions) (ContainerReleaseLeaseResponse, error)
- func (clc *ContainerLeaseClient) RenewLease(ctx context.Context, options *ContainerRenewLeaseOptions) (ContainerRenewLeaseResponse, error)
- type ContainerListBlobFlatPager
- type ContainerListBlobHierarchyPager
- type ContainerListBlobsFlatOptions
- type ContainerListBlobsHierarchyOptions
- type ContainerProperties
- type ContainerReleaseLeaseOptions
- type ContainerReleaseLeaseResponse
- type ContainerRenewLeaseOptions
- type ContainerRenewLeaseResponse
- type ContainerSASPermissions
- type ContainerSetAccessPolicyOptions
- type ContainerSetAccessPolicyResponse
- type ContainerSetMetadataOptions
- type ContainerSetMetadataResponse
- type CopyStatusType
- type CorsRule
- type CpkInfo
- type CpkScopeInfo
- type DeleteSnapshotsOptionType
- type DelimitedTextConfiguration
- type DownloadOptions
- type EncryptionAlgorithmType
- type FailedReadNotifier
- type FilterBlobItem
- type FilterBlobSegment
- type GeoReplication
- type HTTPGetter
- type HTTPGetterInfo
- type HttpRange
- type IPEndpointStyleInfo
- type IPRange
- type InternalError
- type JSONTextConfiguration
- type KeyInfo
- type LeaseAccessConditions
- type LeaseDurationType
- type LeaseStateType
- type LeaseStatusType
- type ListBlobsFlatSegmentResponse
- type ListBlobsHierarchySegmentResponse
- type ListBlobsIncludeItem
- type ListContainersDetail
- type ListContainersIncludeType
- type ListContainersOptions
- type ListContainersSegmentResponse
- type Logging
- type Metrics
- type ModifiedAccessConditions
- type ObjectReplicationPolicy
- type ObjectReplicationRules
- type PageBlobClearPagesOptions
- type PageBlobClearPagesResponse
- type PageBlobClient
- func NewPageBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*PageBlobClient, error)
- func NewPageBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*PageBlobClient, error)
- func NewPageBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*PageBlobClient, error)
- func (pb *PageBlobClient) ClearPages(ctx context.Context, pageRange HttpRange, options *PageBlobClearPagesOptions) (PageBlobClearPagesResponse, error)
- func (pb *PageBlobClient) Create(ctx context.Context, size int64, o *PageBlobCreateOptions) (PageBlobCreateResponse, error)
- func (pb *PageBlobClient) GetPageRanges(options *PageBlobGetPageRangesOptions) *PageBlobGetPageRangesPager
- func (pb *PageBlobClient) GetPageRangesDiff(options *PageBlobGetPageRangesDiffOptions) *PageBlobGetPageRangesDiffPager
- func (pb *PageBlobClient) Resize(ctx context.Context, size int64, options *PageBlobResizeOptions) (PageBlobResizeResponse, error)
- func (pb *PageBlobClient) StartCopyIncremental(ctx context.Context, copySource string, prevSnapshot string, ...) (PageBlobCopyIncrementalResponse, error)
- func (pb *PageBlobClient) UpdateSequenceNumber(ctx context.Context, options *PageBlobUpdateSequenceNumberOptions) (PageBlobUpdateSequenceNumberResponse, error)
- func (pb *PageBlobClient) UploadPages(ctx context.Context, body io.ReadSeekCloser, ...) (PageBlobUploadPagesResponse, error)
- func (pb *PageBlobClient) UploadPagesFromURL(ctx context.Context, source string, sourceOffset, destOffset, count int64, ...) (PageBlobUploadPagesFromURLResponse, error)
- func (pb *PageBlobClient) WithSnapshot(snapshot string) (*PageBlobClient, error)
- func (pb *PageBlobClient) WithVersionID(versionID string) (*PageBlobClient, error)
- type PageBlobCopyIncrementalOptions
- type PageBlobCopyIncrementalResponse
- type PageBlobCreateOptions
- type PageBlobCreateResponse
- type PageBlobGetPageRangesDiffOptions
- type PageBlobGetPageRangesDiffPager
- type PageBlobGetPageRangesOptions
- type PageBlobGetPageRangesPager
- type PageBlobResizeOptions
- type PageBlobResizeResponse
- type PageBlobUpdateSequenceNumberOptions
- type PageBlobUpdateSequenceNumberResponse
- type PageBlobUploadPagesFromURLOptions
- type PageBlobUploadPagesFromURLResponse
- type PageBlobUploadPagesOptions
- type PageBlobUploadPagesResponse
- type PageList
- type PageRange
- type PremiumPageBlobAccessTier
- type PublicAccessType
- type QueryFormat
- type QueryFormatType
- type QueryRequest
- type QuerySerialization
- type RehydratePriority
- type ReleaseLeaseBlobOptions
- type ResponseError
- type RetentionPolicy
- type RetryReaderOptions
- type SASProtocol
- type SASQueryParameters
- func (p *SASQueryParameters) AgentObjectId() string
- func (p *SASQueryParameters) CacheControl() string
- func (p *SASQueryParameters) ContentDisposition() string
- func (p *SASQueryParameters) ContentEncoding() string
- func (p *SASQueryParameters) ContentLanguage() string
- func (p *SASQueryParameters) ContentType() string
- func (p *SASQueryParameters) Encode() string
- func (p *SASQueryParameters) ExpiryTime() time.Time
- func (p *SASQueryParameters) IPRange() IPRange
- func (p *SASQueryParameters) Identifier() string
- func (p *SASQueryParameters) Permissions() string
- func (p *SASQueryParameters) PreauthorizedAgentObjectId() string
- func (p *SASQueryParameters) Protocol() SASProtocol
- func (p *SASQueryParameters) Resource() string
- func (p *SASQueryParameters) ResourceTypes() string
- func (p *SASQueryParameters) Services() string
- func (p *SASQueryParameters) Signature() string
- func (p *SASQueryParameters) SignedCorrelationId() string
- func (p *SASQueryParameters) SignedDirectoryDepth() string
- func (p *SASQueryParameters) SignedExpiry() time.Time
- func (p *SASQueryParameters) SignedService() string
- func (p *SASQueryParameters) SignedStart() time.Time
- func (p *SASQueryParameters) SignedTid() string
- func (p *SASQueryParameters) SignedVersion() string
- func (p *SASQueryParameters) SnapshotTime() time.Time
- func (p *SASQueryParameters) StartTime() time.Time
- func (p *SASQueryParameters) Version() string
- type SKUName
- type SequenceNumberAccessConditions
- type SequenceNumberActionType
- type ServiceClient
- func NewServiceClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*ServiceClient, error)
- func NewServiceClientFromConnectionString(connectionString string, options *ClientOptions) (*ServiceClient, error)
- func NewServiceClientWithNoCredential(serviceURL string, options *ClientOptions) (*ServiceClient, error)
- func NewServiceClientWithSharedKey(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*ServiceClient, error)
- func (s *ServiceClient) CanGetAccountSASToken() bool
- func (s *ServiceClient) CreateContainer(ctx context.Context, containerName string, options *ContainerCreateOptions) (ContainerCreateResponse, error)
- func (s *ServiceClient) DeleteContainer(ctx context.Context, containerName string, options *ContainerDeleteOptions) (ContainerDeleteResponse, error)
- func (s *ServiceClient) FindBlobsByTags(ctx context.Context, o *ServiceFilterBlobsOptions) (ServiceFilterBlobsResponse, error)
- func (s *ServiceClient) GetAccountInfo(ctx context.Context, o *ServiceGetAccountInfoOptions) (ServiceGetAccountInfoResponse, error)
- func (s *ServiceClient) GetProperties(ctx context.Context, o *ServiceGetPropertiesOptions) (ServiceGetPropertiesResponse, error)
- func (s *ServiceClient) GetSASURL(resources AccountSASResourceTypes, permissions AccountSASPermissions, ...) (string, error)
- func (s *ServiceClient) GetStatistics(ctx context.Context, o *ServiceGetStatisticsOptions) (ServiceGetStatisticsResponse, error)
- func (s *ServiceClient) ListContainers(o *ListContainersOptions) *ServiceListContainersSegmentPager
- func (s *ServiceClient) NewContainerClient(containerName string) (*ContainerClient, error)
- func (s *ServiceClient) SetProperties(ctx context.Context, o *ServiceSetPropertiesOptions) (ServiceSetPropertiesResponse, error)
- func (s ServiceClient) URL() string
- type ServiceFilterBlobsOptions
- type ServiceFilterBlobsResponse
- type ServiceGetAccountInfoOptions
- type ServiceGetAccountInfoResponse
- type ServiceGetPropertiesOptions
- type ServiceGetPropertiesResponse
- type ServiceGetStatisticsOptions
- type ServiceGetStatisticsResponse
- type ServiceListContainersSegmentPager
- type ServiceSetPropertiesOptions
- type ServiceSetPropertiesResponse
- type SharedKeyCredential
- type SignedIdentifier
- type SourceModifiedAccessConditions
- type StaticWebsite
- type StorageError
- type StorageErrorCode
- type StorageServiceProperties
- type StorageServiceStats
- type TransferManager
- type UploadOption
- type UploadStreamOptions
- type UserDelegationKey
Examples ¶
- Package
- Package (BlobSnapshots)
- Package (ProgressUploadDownload)
- AccountSASSignatureValues.Sign
- AppendBlobClient
- BlobAccessConditions
- BlobClient (StartCopy)
- BlobClient.Download
- BlobClient.SetMetadata
- BlobHTTPHeaders
- BlobSASSignatureValues
- BlobURLParts
- BlockBlobClient
- ContainerClient.Create
- ContainerClient.Delete
- ContainerClient.GetSASURL
- ContainerClient.ListBlobsFlat
- ContainerClient.ListBlobsHierarchy
- ContainerClient.NewAppendBlobClient
- ContainerClient.NewBlobClient
- ContainerClient.NewBlockBlobClient
- ContainerClient.NewPageBlobClient
- ContainerClient.SetAccessPolicy
- ContainerClient.SetMetadata
- ContainerLeaseClient
- NewContainerClient
- NewContainerClientFromConnectionString
- NewContainerClientWithNoCredential
- NewContainerClientWithSharedKey
- NewServiceClient
- NewServiceClientFromConnectionString
- NewServiceClientWithNoCredential
- NewServiceClientWithSharedKey
- PageBlobClient
- ServiceClient.CreateContainer
- ServiceClient.DeleteContainer
- ServiceClient.GetProperties
- ServiceClient.GetSASURL
- ServiceClient.ListContainers
- ServiceClient.SetProperties
- StorageError
Constants ¶
const ( // BlockBlobMaxUploadBlobBytes indicates the maximum number of bytes that can be sent in a call to Upload. BlockBlobMaxUploadBlobBytes = 256 * 1024 * 1024 // 256MB // BlockBlobMaxStageBlockBytes indicates the maximum number of bytes that can be sent in a call to StageBlock. BlockBlobMaxStageBlockBytes = 4000 * 1024 * 1024 // 4GB // BlockBlobMaxBlocks indicates the maximum number of blocks allowed in a block blob. BlockBlobMaxBlocks = 50000 // PageBlobPageBytes indicates the number of bytes in a page (512). PageBlobPageBytes = 512 // BlobDefaultDownloadBlockSize is default block size BlobDefaultDownloadBlockSize = int64(4 * 1024 * 1024) // 4MB )
nolint
const ( // ContainerNameRoot is the special Azure Storage name used to identify a storage account's root container. ContainerNameRoot = "$root" // ContainerNameLogs is the special Azure Storage name used to identify a storage account's logs container. ContainerNameLogs = "$logs" )
nolint
const ( // ETagNone represents an empty entity tag. ETagNone = "" // ETagAny matches any entity tag. ETagAny = "*" )
const CountToEnd = 0
const LeaseBreakNaturally = -1
LeaseBreakNaturally tells ContainerClient's or BlobClient's BreakLease method to break the lease using service semantics.
const ReadOnClosedBodyMessage = "read on closed response body"
const SASTimeFormat = "2006-01-02T15:04:05Z" //"2017-07-27T00:00:00Z" // ISO 8601
SASTimeFormat represents the format of a SAS start or expiry time. Use it when formatting/parsing a time.Time.
const (
SnapshotTimeFormat = "2006-01-02T15:04:05.0000000Z07:00"
)
Variables ¶
var SASTimeFormats = []string{"2006-01-02T15:04:05.0000000Z", SASTimeFormat, "2006-01-02T15:04Z", "2006-01-02"} // ISO 8601 formats, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas for more details.
var SASVersion = "2019-12-12"
Functions ¶
func DoBatchTransfer ¶
func DoBatchTransfer(ctx context.Context, o BatchTransferOptions) error
DoBatchTransfer helps to execute operations in a batch manner. Can be used by users to customize batch works (for other scenarios that the SDK does not provide)
func FormatTimesForSASSigning ¶
func FormatTimesForSASSigning(startTime, expiryTime, snapshotTime time.Time) (string, string, string)
FormatTimesForSASSigning converts a time.Time to a snapshotTimeFormat string suitable for a SASField's StartTime or ExpiryTime fields. Returns "" if value.IsZero().
func NewRetryReader ¶
func NewRetryReader(ctx context.Context, initialResponse *http.Response, info HTTPGetterInfo, o RetryReaderOptions, getter HTTPGetter) io.ReadCloser
NewRetryReader creates a retry reader.
Types ¶
type AccessPolicy ¶
type AccessPolicy struct {
// the date-time the policy expires
Expiry *time.Time `xml:"Expiry"`
// the permissions for the acl policy
Permission *string `xml:"Permission"`
// the date-time the policy is active
Start *time.Time `xml:"Start"`
}
AccessPolicy - An Access policy
func (AccessPolicy) MarshalXML ¶
func (a AccessPolicy) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type AccessPolicy.
func (*AccessPolicy) UnmarshalXML ¶
func (a *AccessPolicy) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type AccessPolicy.
type AccessPolicyPermission ¶
type AccessPolicyPermission struct {
Read, Add, Create, Write, Delete, List bool
}
AccessPolicyPermission type simplifies creating the permissions string for a container's access policy. Initialize an instance of this type and then call its String method to set AccessPolicy's Permission field.
func (*AccessPolicyPermission) Parse ¶
func (p *AccessPolicyPermission) Parse(s string) error
Parse initializes the AccessPolicyPermission's fields from a string.
func (AccessPolicyPermission) String ¶
func (p AccessPolicyPermission) String() string
String produces the access policy permission string for an Azure Storage container. Call this method to set AccessPolicy's Permission field.
type AccessTier ¶
type AccessTier string
AccessTier enum
const ( AccessTierArchive AccessTier = "Archive" AccessTierCool AccessTier = "Cool" AccessTierHot AccessTier = "Hot" AccessTierP10 AccessTier = "P10" AccessTierP15 AccessTier = "P15" AccessTierP20 AccessTier = "P20" AccessTierP30 AccessTier = "P30" AccessTierP4 AccessTier = "P4" AccessTierP40 AccessTier = "P40" AccessTierP50 AccessTier = "P50" AccessTierP6 AccessTier = "P6" AccessTierP60 AccessTier = "P60" AccessTierP70 AccessTier = "P70" AccessTierP80 AccessTier = "P80" )
func PossibleAccessTierValues ¶
func PossibleAccessTierValues() []AccessTier
PossibleAccessTierValues returns the possible values for the AccessTier const type.
func (AccessTier) ToPtr ¶
func (c AccessTier) ToPtr() *AccessTier
ToPtr returns a *AccessTier pointing to the current value.
type AccountKind ¶
type AccountKind string
AccountKind enum
const ( AccountKindStorage AccountKind = "Storage" AccountKindBlobStorage AccountKind = "BlobStorage" AccountKindStorageV2 AccountKind = "StorageV2" AccountKindFileStorage AccountKind = "FileStorage" AccountKindBlockBlobStorage AccountKind = "BlockBlobStorage" )
func PossibleAccountKindValues ¶
func PossibleAccountKindValues() []AccountKind
PossibleAccountKindValues returns the possible values for the AccountKind const type.
func (AccountKind) ToPtr ¶
func (c AccountKind) ToPtr() *AccountKind
ToPtr returns a *AccountKind pointing to the current value.
type AccountSASPermissions ¶
type AccountSASPermissions struct {
Read, Write, Delete, DeletePreviousVersion, List, Add, Create, Update, Process, Tag, FilterByTags bool
}
AccountSASPermissions type simplifies creating the permissions string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's Permissions field.
func (*AccountSASPermissions) Parse ¶
func (p *AccountSASPermissions) Parse(s string) error
Parse initializes the AccountSASPermissions's fields from a string.
func (AccountSASPermissions) String ¶
func (p AccountSASPermissions) String() string
String produces the SAS permissions string for an Azure Storage account. Call this method to set AccountSASSignatureValues's Permissions field.
type AccountSASResourceTypes ¶
type AccountSASResourceTypes struct {
Service, Container, Object bool
}
AccountSASResourceTypes type simplifies creating the resource types string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's ResourceTypes field.
func (*AccountSASResourceTypes) Parse ¶
func (rt *AccountSASResourceTypes) Parse(s string) error
Parse initializes the AccountSASResourceType's fields from a string.
func (AccountSASResourceTypes) String ¶
func (rt AccountSASResourceTypes) String() string
String produces the SAS resource types string for an Azure Storage account. Call this method to set AccountSASSignatureValues's ResourceTypes field.
type AccountSASServices ¶
type AccountSASServices struct {
Blob, Queue, File bool
}
AccountSASServices type simplifies creating the services string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's Services field.
func (*AccountSASServices) Parse ¶
func (s *AccountSASServices) Parse(str string) error
Parse initializes the AccountSASServices' fields from a string.
func (AccountSASServices) String ¶
func (s AccountSASServices) String() string
String produces the SAS services string for an Azure Storage account. Call this method to set AccountSASSignatureValues's Services field.
type AccountSASSignatureValues ¶
type AccountSASSignatureValues struct {
Version string `param:"sv"` // If not specified, this defaults to SASVersion
Protocol SASProtocol `param:"spr"` // See the SASProtocol* constants
StartTime time.Time `param:"st"` // Not specified if IsZero
ExpiryTime time.Time `param:"se"` // Not specified if IsZero
Permissions string `param:"sp"` // Create by initializing a AccountSASPermissions and then call String()
IPRange IPRange `param:"sip"`
Services string `param:"ss"` // Create by initializing AccountSASServices and then call String()
ResourceTypes string `param:"srt"` // Create by initializing AccountSASResourceTypes and then call String()
}
AccountSASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage account. For more information, see https://docs.microsoft.com/rest/api/storageservices/constructing-an-account-sas
func (AccountSASSignatureValues) Sign ¶
func (v AccountSASSignatureValues) Sign(sharedKeyCredential *SharedKeyCredential) (SASQueryParameters, error)
Sign uses an account's shared key credential to sign this signature values to produce the proper SAS query parameters.
Example ¶
This example shows how to create and use an Azure Storage account Shared Access Signature (SAS).
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
sasQueryParams, err := azblob.AccountSASSignatureValues{
Protocol: azblob.SASProtocolHTTPS,
ExpiryTime: time.Now().UTC().Add(48 * time.Hour),
Permissions: azblob.AccountSASPermissions{Read: true, List: true}.String(),
Services: azblob.AccountSASServices{Blob: true}.String(),
ResourceTypes: azblob.AccountSASResourceTypes{Container: true, Object: true}.String(),
}.Sign(credential)
if err != nil {
log.Fatal(err)
}
queryParams := sasQueryParams.Encode()
sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, queryParams)
// This URL can be used to authenticate requests now
serviceClient, err := azblob.NewServiceClientWithNoCredential(sasURL, nil)
if err != nil {
log.Fatal(err)
}
// You can also break a blob URL up into it's constituent parts
blobURLParts, _ := azblob.NewBlobURLParts(serviceClient.URL())
fmt.Printf("SAS expiry time = %s\n", blobURLParts.SAS.ExpiryTime())
}
type AppendBlobAppendBlockFromURLOptions ¶
type AppendBlobAppendBlockFromURLOptions struct {
// Specify the md5 calculated for the range of bytes that must be read from the copy source.
SourceContentMD5 []byte
// Specify the crc64 calculated for the range of bytes that must be read from the copy source.
SourceContentCRC64 []byte
// Specify the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 []byte
AppendPositionAccessConditions *AppendPositionAccessConditions
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
SourceModifiedAccessConditions *SourceModifiedAccessConditions
BlobAccessConditions *BlobAccessConditions
// Optional, you can specify whether a particular range of the blob is read
Offset *int64
Count *int64
}
AppendBlobAppendBlockFromURLOptions provides set of configurations for AppendBlockFromURL operation
type AppendBlobAppendBlockFromURLResponse ¶
type AppendBlobAppendBlockFromURLResponse struct {
// contains filtered or unexported fields
}
AppendBlobAppendBlockFromURLResponse contains the response from method AppendBlobClient.AppendBlockFromURL.
type AppendBlobAppendBlockOptions ¶
type AppendBlobAppendBlockOptions struct {
// Specify the transactional crc64 for the body, to be validated by the service.
TransactionalContentCRC64 []byte
// Specify the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 []byte
AppendPositionAccessConditions *AppendPositionAccessConditions
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
BlobAccessConditions *BlobAccessConditions
}
AppendBlobAppendBlockOptions provides set of configurations for AppendBlock operation
type AppendBlobAppendBlockResponse ¶
type AppendBlobAppendBlockResponse struct {
// contains filtered or unexported fields
}
AppendBlobAppendBlockResponse contains the response from method AppendBlobClient.AppendBlock.
type AppendBlobClient ¶
type AppendBlobClient struct {
BlobClient
// contains filtered or unexported fields
}
AppendBlobClient represents a client to an Azure Storage append blob;
Example ¶
ExampleAppendBlobClient shows how to append data (in blocks) to an append blob. An append blob can have a maximum of 50,000 blocks; each block can have a maximum of 100MB. The maximum size of an append blob is slightly more than 4.75 TB (100 MB X 50,000 blocks).
package main
import (
"bytes"
"context"
"fmt"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
blobName := "test_append_blob.txt"
blobURL := fmt.Sprintf("https://%s.blob.core.windows.net/testcontainer/%s", accountName, blobName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
appendBlobClient, err := azblob.NewAppendBlobClient(blobURL, cred, nil)
if err != nil {
log.Fatal(err)
}
_, err = appendBlobClient.Create(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
for i := 0; i < 5; i++ { // Append 5 blocks to the append blob
_, err := appendBlobClient.AppendBlock(context.TODO(), streaming.NopCloser(strings.NewReader(fmt.Sprintf("Appending block #%d\n", i))), nil)
if err != nil {
log.Fatal(err)
}
}
// Download the entire append blob's contents and read into a bytes.Buffer.
get, err := appendBlobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
b := bytes.Buffer{}
reader := get.Body(nil)
_, err = b.ReadFrom(reader)
if err != nil {
return
}
err = reader.Close()
if err != nil {
return
}
fmt.Println(b.String())
}
func NewAppendBlobClient ¶
func NewAppendBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*AppendBlobClient, error)
NewAppendBlobClient creates an AppendBlobClient with the specified URL, Azure AD credential, and options.
func NewAppendBlobClientWithNoCredential ¶ added in v0.2.0
func NewAppendBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*AppendBlobClient, error)
NewAppendBlobClientWithNoCredential creates an AppendBlobClient with the specified URL and options.
func NewAppendBlobClientWithSharedKey ¶ added in v0.2.0
func NewAppendBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*AppendBlobClient, error)
NewAppendBlobClientWithSharedKey creates an AppendBlobClient with the specified URL, shared key, and options.
func (*AppendBlobClient) AppendBlock ¶
func (ab *AppendBlobClient) AppendBlock(ctx context.Context, body io.ReadSeekCloser, options *AppendBlobAppendBlockOptions) (AppendBlobAppendBlockResponse, error)
AppendBlock writes a stream to a new block of data to the end of the existing append blob. This method panics if the stream is not at position 0. Note that the http client closes the body stream after the request is sent to the service. For more information, see https://docs.microsoft.com/rest/api/storageservices/append-block.
func (*AppendBlobClient) AppendBlockFromURL ¶
func (ab *AppendBlobClient) AppendBlockFromURL(ctx context.Context, source string, o *AppendBlobAppendBlockFromURLOptions) (AppendBlobAppendBlockFromURLResponse, error)
AppendBlockFromURL copies a new block of data from source URL to the end of the existing append blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/append-block-from-url.
func (*AppendBlobClient) Create ¶
func (ab *AppendBlobClient) Create(ctx context.Context, options *AppendBlobCreateOptions) (AppendBlobCreateResponse, error)
Create creates a 0-size append blob. Call AppendBlock to append data to an append blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-blob.
func (*AppendBlobClient) SealAppendBlob ¶
func (ab *AppendBlobClient) SealAppendBlob(ctx context.Context, options *AppendBlobSealOptions) (AppendBlobSealResponse, error)
SealAppendBlob - The purpose of Append Blob Seal is to allow users and applications to seal append blobs, marking them as read only. https://docs.microsoft.com/en-us/rest/api/storageservices/append-blob-seal
func (*AppendBlobClient) WithSnapshot ¶
func (ab *AppendBlobClient) WithSnapshot(snapshot string) (*AppendBlobClient, error)
WithSnapshot creates a new AppendBlobURL object identical to the source but with the specified snapshot timestamp. Pass "" to remove the snapshot returning a URL to the base blob.
func (*AppendBlobClient) WithVersionID ¶
func (ab *AppendBlobClient) WithVersionID(versionID string) (*AppendBlobClient, error)
WithVersionID creates a new AppendBlobURL object identical to the source but with the specified version id. Pass "" to remove the versionID returning a URL to the base blob.
type AppendBlobCreateOptions ¶
type AppendBlobCreateOptions struct {
// Specifies the date time when the blobs immutability policy is set to expire.
ImmutabilityPolicyExpiry *time.Time
// Specifies the immutability policy mode to set on the blob.
ImmutabilityPolicyMode *BlobImmutabilityPolicyMode
// Specified if a legal hold should be set on the blob.
LegalHold *bool
BlobAccessConditions *BlobAccessConditions
HTTPHeaders *BlobHTTPHeaders
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
// Optional. Used to set blob tags in various blob operations.
TagsMap map[string]string
// Optional. Specifies a user-defined name-value pair associated with the blob. If no name-value pairs are specified, the
// operation will copy the metadata from the source blob or file to the destination blob. If one or more name-value pairs
// are specified, the destination blob is created with the specified metadata, and metadata is not copied from the source
// blob or file. Note that beginning with version 2009-09-19, metadata names must adhere to the naming rules for C# identifiers.
// See Naming and Referencing Containers, Blobs, and Metadata for more information.
Metadata map[string]string
}
AppendBlobCreateOptions provides set of configurations for Create Append Blob operation
type AppendBlobCreateResponse ¶
type AppendBlobCreateResponse struct {
// contains filtered or unexported fields
}
AppendBlobCreateResponse contains the response from method AppendBlobClient.Create.
type AppendBlobSealOptions ¶
type AppendBlobSealOptions struct {
BlobAccessConditions *BlobAccessConditions
AppendPositionAccessConditions *AppendPositionAccessConditions
}
AppendBlobSealOptions provides set of configurations for SealAppendBlob operation
type AppendBlobSealResponse ¶
type AppendBlobSealResponse struct {
// contains filtered or unexported fields
}
AppendBlobSealResponse contains the response from method AppendBlobClient.Seal.
type AppendPositionAccessConditions ¶
type AppendPositionAccessConditions struct {
// Optional conditional header, used only for the Append Block operation. A number indicating the byte offset to compare.
// Append Block will succeed only if the append position is equal to this number. If
// it is not, the request will fail with the AppendPositionConditionNotMet error (HTTP status code 412 - Precondition Failed).
AppendPosition *int64
// Optional conditional header. The max length in bytes permitted for the append blob. If the Append Block operation would
// cause the blob to exceed that limit or if the blob size is already greater than
// the value specified in this header, the request will fail with MaxBlobSizeConditionNotMet error (HTTP status code 412 -
// Precondition Failed).
MaxSize *int64
}
AppendPositionAccessConditions contains a group of parameters for the appendBlobClient.AppendBlock method.
type ArchiveStatus ¶
type ArchiveStatus string
ArchiveStatus enum
const ( ArchiveStatusRehydratePendingToCool ArchiveStatus = "rehydrate-pending-to-cool" ArchiveStatusRehydratePendingToHot ArchiveStatus = "rehydrate-pending-to-hot" )
func PossibleArchiveStatusValues ¶
func PossibleArchiveStatusValues() []ArchiveStatus
PossibleArchiveStatusValues returns the possible values for the ArchiveStatus const type.
func (ArchiveStatus) ToPtr ¶
func (c ArchiveStatus) ToPtr() *ArchiveStatus
ToPtr returns a *ArchiveStatus pointing to the current value.
type ArrowConfiguration ¶ added in v0.4.0
type ArrowConfiguration struct {
// REQUIRED
Schema []*ArrowField `xml:"Schema>Field"`
}
ArrowConfiguration - Groups the settings used for formatting the response if the response should be Arrow formatted.
func (ArrowConfiguration) MarshalXML ¶ added in v0.4.0
func (a ArrowConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type ArrowConfiguration.
type ArrowField ¶ added in v0.4.0
type ArrowField struct {
// REQUIRED
Type *string `xml:"Type"`
Name *string `xml:"Name"`
Precision *int32 `xml:"Precision"`
Scale *int32 `xml:"Scale"`
}
ArrowField - Groups settings regarding specific field of an arrow schema
type BatchTransferOptions ¶
type BatchTransferOptions struct {
TransferSize int64
ChunkSize int64
Parallelism uint16
Operation func(offset int64, chunkSize int64, ctx context.Context) error
OperationName string
}
BatchTransferOptions identifies options used by DoBatchTransfer.
type BlobAbortCopyFromURLResponse ¶
type BlobAbortCopyFromURLResponse struct {
// contains filtered or unexported fields
}
BlobAbortCopyFromURLResponse contains the response from method BlobClient.AbortCopyFromURL
type BlobAbortCopyOptions ¶ added in v0.4.0
type BlobAbortCopyOptions struct {
LeaseAccessConditions *LeaseAccessConditions
}
BlobAbortCopyOptions provides set of configurations for AbortCopyFromURL operation
type BlobAccessConditions ¶
type BlobAccessConditions struct {
LeaseAccessConditions *LeaseAccessConditions
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobAccessConditions identifies blob-specific access conditions which you optionally set.
Example ¶
This example shows how to perform operations on blob conditionally.
package main
import (
"context"
"errors"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"log"
"os"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
blockBlob, err := azblob.NewBlockBlobClientWithSharedKey(fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/Data.txt", accountName), credential, nil)
if err != nil {
log.Fatal(err)
}
// This function displays the results of an operation
showResult := func(response *azblob.BlobDownloadResponse, err error) {
if err != nil {
var stgErr *azblob.StorageError
if errors.As(err, &stgErr) {
log.Fatalf("Failure: %s\n", stgErr.Error())
} else {
log.Fatal(err) // Network failure
}
} else {
err := response.Body(nil).Close()
if err != nil {
log.Fatal(err)
}
// The client must close the response body when finished with it
fmt.Printf("Success: %s\n", response.RawResponse.Status)
}
// Close the response
if err != nil {
return
}
fmt.Printf("Success: %s\n", response.RawResponse.Status)
}
showResultUpload := func(upload azblob.BlockBlobUploadResponse, err error) {
if err != nil {
var stgErr *azblob.StorageError
if errors.As(err, &stgErr) {
log.Fatalf("Failure: " + stgErr.Error() + "\n")
} else {
log.Fatal(err) // Network failure
}
}
fmt.Print("Success: " + upload.RawResponse.Status + "\n")
}
// Create the blob
upload, err := blockBlob.Upload(context.TODO(), streaming.NopCloser(strings.NewReader("Text-1")), nil)
showResultUpload(upload, err)
// Download blob content if the blob has been modified since we uploaded it (fails):
downloadResp, err := blockBlob.Download(
context.TODO(),
&azblob.BlobDownloadOptions{
BlobAccessConditions: &azblob.BlobAccessConditions{
ModifiedAccessConditions: &azblob.ModifiedAccessConditions{
IfModifiedSince: upload.LastModified,
},
},
},
)
showResult(&downloadResp, err)
// Download blob content if the blob hasn't been modified in the last 24 hours (fails):
downloadResp, err = blockBlob.Download(
context.TODO(),
&azblob.BlobDownloadOptions{
BlobAccessConditions: &azblob.BlobAccessConditions{
ModifiedAccessConditions: &azblob.ModifiedAccessConditions{
IfUnmodifiedSince: to.Ptr(time.Now().UTC().Add(time.Hour * -24))},
},
},
)
showResult(&downloadResp, err)
// Upload new content if the blob hasn't changed since the version identified by ETag (succeeds):
showResultUpload(blockBlob.Upload(
context.TODO(),
streaming.NopCloser(strings.NewReader("Text-2")),
&azblob.BlockBlobUploadOptions{
BlobAccessConditions: &azblob.BlobAccessConditions{
ModifiedAccessConditions: &azblob.ModifiedAccessConditions{IfMatch: upload.ETag},
},
},
))
// Download content if it has changed since the version identified by ETag (fails):
downloadResp, err = blockBlob.Download(
context.TODO(),
&azblob.BlobDownloadOptions{
BlobAccessConditions: &azblob.BlobAccessConditions{
ModifiedAccessConditions: &azblob.ModifiedAccessConditions{IfNoneMatch: upload.ETag}},
})
showResult(&downloadResp, err)
// Upload content if the blob doesn't already exist (fails):
showResultUpload(blockBlob.Upload(
context.TODO(),
streaming.NopCloser(strings.NewReader("Text-3")),
&azblob.BlockBlobUploadOptions{
BlobAccessConditions: &azblob.BlobAccessConditions{
ModifiedAccessConditions: &azblob.ModifiedAccessConditions{IfNoneMatch: to.Ptr(string(azcore.ETagAny))},
},
}))
}
type BlobAcquireLeaseOptions ¶
type BlobAcquireLeaseOptions struct {
// Specifies the Duration of the lease, in seconds, or negative one (-1) for a lease that never expires. A non-infinite lease
// can be between 15 and 60 seconds. A lease Duration cannot be changed using renew or change.
Duration *int32
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobAcquireLeaseOptions provides set of configurations for AcquireLeaseBlob operation
type BlobAcquireLeaseResponse ¶
type BlobAcquireLeaseResponse struct {
// contains filtered or unexported fields
}
BlobAcquireLeaseResponse contains the response from method BlobLeaseClient.AcquireLease.
type BlobBreakLeaseOptions ¶
type BlobBreakLeaseOptions struct {
// For a break operation, proposed Duration the lease should continue before it is broken, in seconds, between 0 and 60. This
// break period is only used if it is shorter than the time remaining on the lease. If longer, the time remaining on the lease
// is used. A new lease will not be available before the break period has expired, but the lease may be held for longer than
// the break period. If this header does not appear with a break operation, a fixed-Duration lease breaks after the remaining
// lease period elapses, and an infinite lease breaks immediately.
BreakPeriod *int32
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobBreakLeaseOptions provides set of configurations for BreakLeaseBlob operation
type BlobBreakLeaseResponse ¶
type BlobBreakLeaseResponse struct {
// contains filtered or unexported fields
}
BlobBreakLeaseResponse contains the response from method BlobLeaseClient.BreakLease.
type BlobChangeLeaseOptions ¶
type BlobChangeLeaseOptions struct {
ProposedLeaseID *string
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobChangeLeaseOptions provides set of configurations for ChangeLeaseBlob operation
type BlobChangeLeaseResponse ¶
type BlobChangeLeaseResponse struct {
// contains filtered or unexported fields
}
BlobChangeLeaseResponse contains the response from method BlobLeaseClient.ChangeLease
type BlobClient ¶
type BlobClient struct {
// contains filtered or unexported fields
}
BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, append blob, or page blob.
Example (StartCopy) ¶
This example shows how to copy a source document on the Internet to a blob.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
// Create a containerClient object to a container where we'll create a blob and its snapshot.
// Create a blockBlobClient object to a blob in the container.
blobURL := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/CopiedBlob.bin", accountName)
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
blobClient, err := azblob.NewBlobClientWithSharedKey(blobURL, credential, nil)
if err != nil {
log.Fatal(err)
}
src := "https://cdn2.auth0.com/docs/media/addons/azure_blob.svg"
startCopy, err := blobClient.StartCopyFromURL(context.TODO(), src, nil)
if err != nil {
log.Fatal(err)
}
copyID := *startCopy.CopyID
copyStatus := *startCopy.CopyStatus
for copyStatus == azblob.CopyStatusTypePending {
time.Sleep(time.Second * 2)
getMetadata, err := blobClient.GetProperties(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
copyStatus = *getMetadata.CopyStatus
}
fmt.Printf("Copy from %s to %s: ID=%s, Status=%s\n", src, blobClient.URL(), copyID, copyStatus)
}
func NewBlobClient ¶
func NewBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*BlobClient, error)
NewBlobClient creates a BlobClient object using the specified URL, Azure AD credential, and options.
func NewBlobClientFromConnectionString ¶
func NewBlobClientFromConnectionString(connectionString, containerName, blobName string, options *ClientOptions) (*BlobClient, error)
NewBlobClientFromConnectionString creates BlobClient from a connection String nolint
func NewBlobClientWithNoCredential ¶ added in v0.2.0
func NewBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*BlobClient, error)
NewBlobClientWithNoCredential creates a BlobClient object using the specified URL and options.
func NewBlobClientWithSharedKey ¶ added in v0.2.0
func NewBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*BlobClient, error)
NewBlobClientWithSharedKey creates a BlobClient object using the specified URL, shared key, and options.
func (*BlobClient) AbortCopyFromURL ¶
func (b *BlobClient) AbortCopyFromURL(ctx context.Context, copyID string, options *BlobAbortCopyOptions) (BlobAbortCopyFromURLResponse, error)
AbortCopyFromURL stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. For more information, see https://docs.microsoft.com/rest/api/storageservices/abort-copy-blob.
func (*BlobClient) CreateSnapshot ¶
func (b *BlobClient) CreateSnapshot(ctx context.Context, options *BlobCreateSnapshotOptions) (BlobCreateSnapshotResponse, error)
CreateSnapshot creates a read-only snapshot of a blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/snapshot-blob.
func (*BlobClient) Delete ¶
func (b *BlobClient) Delete(ctx context.Context, o *BlobDeleteOptions) (BlobDeleteResponse, error)
Delete marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. Note that deleting a blob also deletes all its snapshots. For more information, see https://docs.microsoft.com/rest/api/storageservices/delete-blob.
func (*BlobClient) Download ¶
func (b *BlobClient) Download(ctx context.Context, options *BlobDownloadOptions) (BlobDownloadResponse, error)
Download reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-blob.
Example ¶
This example shows how to download a large stream with intelligent retries. Specifically, if the connection fails while reading, continuing to read from this stream initiates a new GetBlob call passing a range that starts from the last byte successfully read before the failure.
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// From the Azure portal, get your Storage account blob service URL endpoint.
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
// Create a blobClient object to a blob in the container (we assume the container & blob already exist).
blobURL := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/BigBlob.bin", accountName)
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
blobClient, err := azblob.NewBlobClientWithSharedKey(blobURL, credential, nil)
if err != nil {
log.Fatal(err)
}
contentLength := int64(0) // Used for progress reporting to report the total number of bytes being downloaded.
// Download returns an intelligent retryable stream around a blob; it returns an io.ReadCloser.
dr, err := blobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
rs := dr.Body(nil)
// NewResponseBodyProgress wraps the GetRetryStream with progress reporting; it returns an io.ReadCloser.
stream := streaming.NewResponseProgress(
rs,
func(bytesTransferred int64) {
fmt.Printf("Downloaded %d of %d bytes.\n", bytesTransferred, contentLength)
},
)
defer func(stream io.ReadCloser) {
err := stream.Close()
if err != nil {
log.Fatal(err)
}
}(stream) // The client must close the response body when finished with it
file, err := os.Create("BigFile.bin") // Create the file to hold the downloaded blob contents.
if err != nil {
log.Fatal(err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
}
}(file)
written, err := io.Copy(file, stream) // Write to the file by reading from the blob (with intelligent retries).
if err != nil {
log.Fatal(err)
}
fmt.Printf("Wrote %d bytes.\n", written)
}
func (*BlobClient) DownloadToBuffer ¶ added in v0.4.0
func (b *BlobClient) DownloadToBuffer(ctx context.Context, offset int64, count int64, _bytes []byte, o DownloadOptions) error
DownloadToBuffer downloads an Azure blob to a buffer with parallel. Offset and count are optional, pass 0 for both to download the entire blob.
func (*BlobClient) DownloadToFile ¶ added in v0.4.0
func (b *BlobClient) DownloadToFile(ctx context.Context, offset int64, count int64, file *os.File, o DownloadOptions) error
DownloadToFile downloads an Azure blob to a local file. The file would be truncated if the size doesn't match. Offset and count are optional, pass 0 for both to download the entire blob.
func (*BlobClient) DownloadToWriterAt ¶ added in v0.4.0
func (b *BlobClient) DownloadToWriterAt(ctx context.Context, offset int64, count int64, writer io.WriterAt, o DownloadOptions) error
DownloadToWriterAt downloads an Azure blob to a WriterAt with parallel. Offset and count are optional, pass 0 for both to download the entire blob.
func (*BlobClient) GetProperties ¶
func (b *BlobClient) GetProperties(ctx context.Context, options *BlobGetPropertiesOptions) (BlobGetPropertiesResponse, error)
GetProperties returns the blob's properties. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-blob-properties.
func (*BlobClient) GetSASToken ¶
func (b *BlobClient) GetSASToken(permissions BlobSASPermissions, start time.Time, expiry time.Time) (SASQueryParameters, error)
GetSASToken is a convenience method for generating a SAS token for the currently pointed at blob. It can only be used if the credential supplied during creation was a SharedKeyCredential.
func (*BlobClient) GetTags ¶
func (b *BlobClient) GetTags(ctx context.Context, options *BlobGetTagsOptions) (BlobGetTagsResponse, error)
GetTags operation enables users to get tags on a blob or specific blob version, or snapshot. https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-tags
func (*BlobClient) NewBlobLeaseClient ¶
func (b *BlobClient) NewBlobLeaseClient(leaseID *string) (*BlobLeaseClient, error)
NewBlobLeaseClient is constructor for BlobLeaseClient
func (*BlobClient) SetHTTPHeaders ¶
func (b *BlobClient) SetHTTPHeaders(ctx context.Context, blobHttpHeaders BlobHTTPHeaders, options *BlobSetHTTPHeadersOptions) (BlobSetHTTPHeadersResponse, error)
SetHTTPHeaders changes a blob's HTTP headers. For more information, see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties.
func (*BlobClient) SetMetadata ¶
func (b *BlobClient) SetMetadata(ctx context.Context, metadata map[string]string, options *BlobSetMetadataOptions) (BlobSetMetadataResponse, error)
SetMetadata changes a blob's metadata. https://docs.microsoft.com/rest/api/storageservices/set-blob-metadata.
Example ¶
This example shows how to create a blob with metadata, read blob metadata, and update a blob's read-only properties and metadata.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
// Create a blob client
u := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/ReadMe.txt", accountName)
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
blobClient, err := azblob.NewBlockBlobClientWithSharedKey(u, credential, nil)
if err != nil {
log.Fatal(err)
}
// Create a blob with metadata (string key/value pairs)
// Metadata key names are always converted to lowercase before being sent to the Storage Service.
// Always use lowercase letters; especially when querying a map for a metadata key.
creatingApp, err := os.Executable()
if err != nil {
log.Fatal(err)
}
_, err = blobClient.Upload(
context.TODO(),
streaming.NopCloser(strings.NewReader("Some text")),
&azblob.BlockBlobUploadOptions{Metadata: map[string]string{"author": "Jeffrey", "app": creatingApp}},
)
if err != nil {
log.Fatal(err)
}
// Query the blob's properties and metadata
get, err := blobClient.GetProperties(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Show some of the blob's read-only properties
fmt.Printf("BlobType: %s\nETag: %s\nLastModified: %s\n", *get.BlobType, *get.ETag, *get.LastModified)
// Show the blob's metadata
if get.Metadata == nil {
log.Fatal("No metadata returned")
}
for k, v := range get.Metadata {
fmt.Print(k + "=" + v + "\n")
}
// Update the blob's metadata and write it back to the blob
get.Metadata["editor"] = "Grant"
_, err = blobClient.SetMetadata(context.TODO(), get.Metadata, nil)
if err != nil {
log.Fatal(err)
}
}
func (*BlobClient) SetTags ¶
func (b *BlobClient) SetTags(ctx context.Context, options *BlobSetTagsOptions) (BlobSetTagsResponse, error)
SetTags operation enables users to set tags on a blob or specific blob version, but not snapshot. Each call to this operation replaces all existing tags attached to the blob. To remove all tags from the blob, call this operation with no tags set. https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tags
func (*BlobClient) SetTier ¶
func (b *BlobClient) SetTier(ctx context.Context, tier AccessTier, options *BlobSetTierOptions) (BlobSetTierResponse, error)
SetTier operation sets the tier on a blob. The operation is allowed on a page blob in a premium storage account and on a block blob in a blob storage account (locally redundant storage only). A premium page blob's tier determines the allowed size, IOPS, and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's ETag. For detailed information about block blob level tiering see https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-storage-tiers.
func (*BlobClient) StartCopyFromURL ¶
func (b *BlobClient) StartCopyFromURL(ctx context.Context, copySource string, options *BlobStartCopyOptions) (BlobStartCopyFromURLResponse, error)
StartCopyFromURL copies the data at the source URL to a blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/copy-blob.
func (*BlobClient) URL ¶
func (b *BlobClient) URL() string
URL returns the URL endpoint used by the BlobClient object.
func (*BlobClient) Undelete ¶
func (b *BlobClient) Undelete(ctx context.Context, o *BlobUndeleteOptions) (BlobUndeleteResponse, error)
Undelete restores the contents and metadata of a soft-deleted blob and any associated soft-deleted snapshots. For more information, see https://docs.microsoft.com/rest/api/storageservices/undelete-blob.
func (*BlobClient) WithSnapshot ¶
func (b *BlobClient) WithSnapshot(snapshot string) (*BlobClient, error)
WithSnapshot creates a new BlobClient object identical to the source but with the specified snapshot timestamp. Pass "" to remove the snapshot returning a URL to the base blob.
func (*BlobClient) WithVersionID ¶
func (b *BlobClient) WithVersionID(versionID string) (*BlobClient, error)
WithVersionID creates a new AppendBlobURL object identical to the source but with the specified version id. Pass "" to remove the versionID returning a URL to the base blob.
type BlobCreateSnapshotOptions ¶
type BlobCreateSnapshotOptions struct {
Metadata map[string]string
LeaseAccessConditions *LeaseAccessConditions
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobCreateSnapshotOptions provides set of configurations for CreateSnapshot of blob operation
type BlobCreateSnapshotResponse ¶
type BlobCreateSnapshotResponse struct {
// contains filtered or unexported fields
}
BlobCreateSnapshotResponse contains the response from method BlobClient.CreateSnapshot
type BlobDeleteOptions ¶
type BlobDeleteOptions struct {
// Required if the blob has associated snapshots. Specify one of the following two options: include: Delete the base blob
// and all of its snapshots. only: Delete only the blob's snapshots and not the blob itself
DeleteSnapshots *DeleteSnapshotsOptionType
BlobAccessConditions *BlobAccessConditions
}
BlobDeleteOptions provides set of configurations for Delete blob operation
type BlobDeleteResponse ¶
type BlobDeleteResponse struct {
// contains filtered or unexported fields
}
BlobDeleteResponse contains the response from method BlobClient.Delete.
type BlobDeleteType ¶ added in v0.4.0
type BlobDeleteType string
BlobDeleteType enum
const ( BlobDeleteTypeNone BlobDeleteType = "None" BlobDeleteTypePermanent BlobDeleteType = "Permanent" )
func PossibleBlobDeleteTypeValues ¶ added in v0.4.0
func PossibleBlobDeleteTypeValues() []BlobDeleteType
PossibleBlobDeleteTypeValues returns the possible values for the BlobDeleteType const type.
func (BlobDeleteType) ToPtr ¶ added in v0.4.0
func (c BlobDeleteType) ToPtr() *BlobDeleteType
ToPtr returns a *BlobDeleteType pointing to the current value.
type BlobDownloadOptions ¶
type BlobDownloadOptions struct {
// When set to true and specified together with the Range, the service returns the MD5 hash for the range, as long as the
// range is less than or equal to 4 MB in size.
RangeGetContentMD5 *bool
// Optional, you can specify whether a particular range of the blob is read
Offset *int64
Count *int64
BlobAccessConditions *BlobAccessConditions
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
}
BlobDownloadOptions provides set of configurations for Download blob operation
type BlobDownloadResponse ¶
type BlobDownloadResponse struct {
ObjectReplicationRules []ObjectReplicationPolicy
// contains filtered or unexported fields
}
BlobDownloadResponse wraps AutoRest generated BlobDownloadResponse and helps to provide info for retry.
func (*BlobDownloadResponse) Body ¶ added in v0.4.0
func (r *BlobDownloadResponse) Body(options *RetryReaderOptions) io.ReadCloser
Body constructs new RetryReader stream for reading data. If a connection fails while reading, it will make additional requests to reestablish a connection and continue reading. Specifying a RetryReaderOption's with MaxRetryRequests set to 0 (the default), returns the original response body and no retries will be performed. Pass in nil for options to accept the default options.
func (BlobDownloadResponse) GetHTTPHeaders ¶
func (r BlobDownloadResponse) GetHTTPHeaders() BlobHTTPHeaders
GetHTTPHeaders returns the user-modifiable properties for this blob.
type BlobExpiryOptions ¶
type BlobExpiryOptions string
BlobExpiryOptions enum
const ( BlobExpiryOptionsAbsolute BlobExpiryOptions = "Absolute" BlobExpiryOptionsNeverExpire BlobExpiryOptions = "NeverExpire" BlobExpiryOptionsRelativeToCreation BlobExpiryOptions = "RelativeToCreation" BlobExpiryOptionsRelativeToNow BlobExpiryOptions = "RelativeToNow" )
func PossibleBlobExpiryOptionsValues ¶
func PossibleBlobExpiryOptionsValues() []BlobExpiryOptions
PossibleBlobExpiryOptionsValues returns the possible values for the BlobExpiryOptions const type.
func (BlobExpiryOptions) ToPtr ¶
func (c BlobExpiryOptions) ToPtr() *BlobExpiryOptions
ToPtr returns a *BlobExpiryOptions pointing to the current value.
type BlobFlatListSegment ¶
type BlobFlatListSegment struct {
// REQUIRED
BlobItems []*BlobItemInternal `xml:"Blob"`
}
BlobFlatListSegment struct
func (BlobFlatListSegment) MarshalXML ¶
func (b BlobFlatListSegment) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type BlobFlatListSegment.
type BlobGeoReplicationStatus ¶ added in v0.4.0
type BlobGeoReplicationStatus string
BlobGeoReplicationStatus - The status of the secondary location
const ( BlobGeoReplicationStatusLive BlobGeoReplicationStatus = "live" BlobGeoReplicationStatusBootstrap BlobGeoReplicationStatus = "bootstrap" )
func PossibleBlobGeoReplicationStatusValues ¶ added in v0.4.0
func PossibleBlobGeoReplicationStatusValues() []BlobGeoReplicationStatus
PossibleBlobGeoReplicationStatusValues returns the possible values for the BlobGeoReplicationStatus const type.
func (BlobGeoReplicationStatus) ToPtr ¶ added in v0.4.0
func (c BlobGeoReplicationStatus) ToPtr() *BlobGeoReplicationStatus
ToPtr returns a *BlobGeoReplicationStatus pointing to the current value.
type BlobGetPropertiesOptions ¶
type BlobGetPropertiesOptions struct {
BlobAccessConditions *BlobAccessConditions
CpkInfo *CpkInfo
}
BlobGetPropertiesOptions provides set of configurations for GetProperties blob operation
type BlobGetPropertiesResponse ¶
type BlobGetPropertiesResponse struct {
// deserialized attributes
ObjectReplicationRules []ObjectReplicationPolicy
// contains filtered or unexported fields
}
BlobGetPropertiesResponse reformat the GetPropertiesResponse object for easy consumption
func (BlobGetPropertiesResponse) GetHTTPHeaders ¶
func (bgpr BlobGetPropertiesResponse) GetHTTPHeaders() BlobHTTPHeaders
GetHTTPHeaders returns the user-modifiable properties for this blob.
type BlobGetTagsOptions ¶
type BlobGetTagsOptions struct {
// The snapshot parameter is an opaque DateTime value that, when present, specifies the blob snapshot to retrieve.
Snapshot *string
// The version id parameter is an opaque DateTime value that, when present, specifies the version of the blob to operate on.
// It's for service version 2019-10-10 and newer.
VersionID *string
BlobAccessConditions *BlobAccessConditions
}
BlobGetTagsOptions provides set of configurations for GetTags operation
type BlobGetTagsResponse ¶
type BlobGetTagsResponse struct {
// contains filtered or unexported fields
}
BlobGetTagsResponse contains the response from method BlobClient.GetTags
type BlobHTTPHeaders ¶
type BlobHTTPHeaders struct {
// Optional. Sets the blob's cache control. If specified, this property is stored with the blob and returned with a read request.
BlobCacheControl *string
// Optional. Sets the blob's Content-Disposition header.
BlobContentDisposition *string
// Optional. Sets the blob's content encoding. If specified, this property is stored with the blob and returned with a read
// request.
BlobContentEncoding *string
// Optional. Set the blob's content language. If specified, this property is stored with the blob and returned with a read
// request.
BlobContentLanguage *string
// Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for the individual blocks
// were validated when each was uploaded.
BlobContentMD5 []byte
// Optional. Sets the blob's content type. If specified, this property is stored with the blob and returned with a read request.
BlobContentType *string
}
BlobHTTPHeaders contains a group of parameters for the blobClient.SetHTTPHeaders method.
Example ¶
This examples shows how to create a blob with HTTP Headers, how to read, and how to update the blob's HTTP headers.
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
// Create a blob client
u := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer/ReadMe.txt", accountName)
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
blobClient, err := azblob.NewBlockBlobClientWithSharedKey(u, credential, nil)
if err != nil {
log.Fatal(err)
}
// Create a blob with HTTP headers
_, err = blobClient.Upload(
context.TODO(),
streaming.NopCloser(strings.NewReader("Some text")),
&azblob.BlockBlobUploadOptions{HTTPHeaders: &azblob.BlobHTTPHeaders{
BlobContentType: to.Ptr("text/html; charset=utf-8"),
BlobContentDisposition: to.Ptr("attachment"),
}},
)
if err != nil {
log.Fatal(err)
}
// GetMetadata returns the blob's properties, HTTP headers, and metadata
get, err := blobClient.GetProperties(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Show some of the blob's read-only properties
fmt.Printf("BlobType: %s\nETag: %s\nLastModified: %s\n", *get.BlobType, *get.ETag, *get.LastModified)
// Shows some of the blob's HTTP Headers
httpHeaders := get.GetHTTPHeaders()
fmt.Println(httpHeaders.BlobContentType, httpHeaders.BlobContentDisposition)
// Update the blob's HTTP Headers and write them back to the blob
httpHeaders.BlobContentType = to.Ptr("text/plain")
_, err = blobClient.SetHTTPHeaders(context.TODO(), httpHeaders, nil)
if err != nil {
log.Fatal(err)
}
}
type BlobHierarchyListSegment ¶
type BlobHierarchyListSegment struct {
// REQUIRED
BlobItems []*BlobItemInternal `xml:"Blob"`
BlobPrefixes []*BlobPrefix `xml:"BlobPrefix"`
}
BlobHierarchyListSegment struct
func (BlobHierarchyListSegment) MarshalXML ¶
func (b BlobHierarchyListSegment) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type BlobHierarchyListSegment.
type BlobImmutabilityPolicyMode ¶ added in v0.4.0
type BlobImmutabilityPolicyMode string
BlobImmutabilityPolicyMode enum
const ( BlobImmutabilityPolicyModeMutable BlobImmutabilityPolicyMode = "Mutable" BlobImmutabilityPolicyModeUnlocked BlobImmutabilityPolicyMode = "Unlocked" BlobImmutabilityPolicyModeLocked BlobImmutabilityPolicyMode = "Locked" )
func PossibleBlobImmutabilityPolicyModeValues ¶ added in v0.4.0
func PossibleBlobImmutabilityPolicyModeValues() []BlobImmutabilityPolicyMode
PossibleBlobImmutabilityPolicyModeValues returns the possible values for the BlobImmutabilityPolicyMode const type.
func (BlobImmutabilityPolicyMode) ToPtr ¶ added in v0.4.0
func (c BlobImmutabilityPolicyMode) ToPtr() *BlobImmutabilityPolicyMode
ToPtr returns a *BlobImmutabilityPolicyMode pointing to the current value.
type BlobItemInternal ¶
type BlobItemInternal struct {
// REQUIRED
Deleted *bool `xml:"Deleted"`
// REQUIRED
Name *string `xml:"Name"`
// REQUIRED; Properties of a blob
Properties *BlobPropertiesInternal `xml:"Properties"`
// REQUIRED
Snapshot *string `xml:"Snapshot"`
// Blob tags
BlobTags *BlobTags `xml:"Tags"`
HasVersionsOnly *bool `xml:"HasVersionsOnly"`
IsCurrentVersion *bool `xml:"IsCurrentVersion"`
// Dictionary of
Metadata map[string]*string `xml:"Metadata"`
// Dictionary of
OrMetadata map[string]*string `xml:"OrMetadata"`
VersionID *string `xml:"VersionId"`
}
BlobItemInternal - An Azure Storage blob
func (*BlobItemInternal) UnmarshalXML ¶
func (b *BlobItemInternal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type BlobItemInternal.
type BlobLeaseClient ¶
type BlobLeaseClient struct {
BlobClient
// contains filtered or unexported fields
}
BlobLeaseClient represents lease client on blob
func (*BlobLeaseClient) AcquireLease ¶
func (blc *BlobLeaseClient) AcquireLease(ctx context.Context, options *BlobAcquireLeaseOptions) (BlobAcquireLeaseResponse, error)
AcquireLease acquires a lease on the blob for write and delete operations. The lease Duration must be between 15 and 60 seconds, or infinite (-1). For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-blob.
func (*BlobLeaseClient) BreakLease ¶
func (blc *BlobLeaseClient) BreakLease(ctx context.Context, options *BlobBreakLeaseOptions) (BlobBreakLeaseResponse, error)
BreakLease breaks the blob's previously-acquired lease (if it exists). Pass the LeaseBreakDefault (-1) constant to break a fixed-Duration lease when it expires or an infinite lease immediately. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-blob.
func (*BlobLeaseClient) ChangeLease ¶
func (blc *BlobLeaseClient) ChangeLease(ctx context.Context, options *BlobChangeLeaseOptions) (BlobChangeLeaseResponse, error)
ChangeLease changes the blob's lease ID. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-blob.
func (*BlobLeaseClient) ReleaseLease ¶
func (blc *BlobLeaseClient) ReleaseLease(ctx context.Context, options *ReleaseLeaseBlobOptions) (BlobReleaseLeaseResponse, error)
ReleaseLease releases the blob's previously-acquired lease. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-blob.
func (*BlobLeaseClient) RenewLease ¶
func (blc *BlobLeaseClient) RenewLease(ctx context.Context, options *BlobRenewLeaseOptions) (BlobRenewLeaseResponse, error)
RenewLease renews the blob's previously-acquired lease. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-blob.
type BlobPrefix ¶
type BlobPrefix struct {
// REQUIRED
Name *string `xml:"Name"`
}
BlobPrefix struct
type BlobPropertiesInternal ¶
type BlobPropertiesInternal struct {
// REQUIRED
Etag *string `xml:"Etag"`
// REQUIRED
LastModified *time.Time `xml:"Last-Modified"`
AccessTier *AccessTier `xml:"AccessTier"`
AccessTierChangeTime *time.Time `xml:"AccessTierChangeTime"`
AccessTierInferred *bool `xml:"AccessTierInferred"`
ArchiveStatus *ArchiveStatus `xml:"ArchiveStatus"`
BlobSequenceNumber *int64 `xml:"x-ms-blob-sequence-number"`
BlobType *BlobType `xml:"BlobType"`
CacheControl *string `xml:"Cache-Control"`
ContentDisposition *string `xml:"Content-Disposition"`
ContentEncoding *string `xml:"Content-Encoding"`
ContentLanguage *string `xml:"Content-Language"`
// Size in bytes
ContentLength *int64 `xml:"Content-Length"`
ContentMD5 []byte `xml:"Content-MD5"`
ContentType *string `xml:"Content-Type"`
CopyCompletionTime *time.Time `xml:"CopyCompletionTime"`
CopyID *string `xml:"CopyId"`
CopyProgress *string `xml:"CopyProgress"`
CopySource *string `xml:"CopySource"`
CopyStatus *CopyStatusType `xml:"CopyStatus"`
CopyStatusDescription *string `xml:"CopyStatusDescription"`
CreationTime *time.Time `xml:"Creation-Time"`
CustomerProvidedKeySHA256 *string `xml:"CustomerProvidedKeySha256"`
DeletedTime *time.Time `xml:"DeletedTime"`
DestinationSnapshot *string `xml:"DestinationSnapshot"`
// The name of the encryption scope under which the blob is encrypted.
EncryptionScope *string `xml:"EncryptionScope"`
ExpiresOn *time.Time `xml:"Expiry-Time"`
ImmutabilityPolicyExpiresOn *time.Time `xml:"ImmutabilityPolicyUntilDate"`
ImmutabilityPolicyMode *BlobImmutabilityPolicyMode `xml:"ImmutabilityPolicyMode"`
IncrementalCopy *bool `xml:"IncrementalCopy"`
IsSealed *bool `xml:"Sealed"`
LastAccessedOn *time.Time `xml:"LastAccessTime"`
LeaseDuration *LeaseDurationType `xml:"LeaseDuration"`
LeaseState *LeaseStateType `xml:"LeaseState"`
LeaseStatus *LeaseStatusType `xml:"LeaseStatus"`
LegalHold *bool `xml:"LegalHold"`
// If an object is in rehydrate pending state then this header is returned with priority of rehydrate. Valid values are High
// and Standard.
RehydratePriority *RehydratePriority `xml:"RehydratePriority"`
RemainingRetentionDays *int32 `xml:"RemainingRetentionDays"`
ServerEncrypted *bool `xml:"ServerEncrypted"`
TagCount *int32 `xml:"TagCount"`
}
BlobPropertiesInternal - Properties of a blob
func (BlobPropertiesInternal) MarshalXML ¶
func (b BlobPropertiesInternal) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type BlobPropertiesInternal.
func (*BlobPropertiesInternal) UnmarshalXML ¶
func (b *BlobPropertiesInternal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type BlobPropertiesInternal.
type BlobReleaseLeaseResponse ¶
type BlobReleaseLeaseResponse struct {
// contains filtered or unexported fields
}
BlobReleaseLeaseResponse contains the response from method BlobClient.ReleaseLease.
type BlobRenewLeaseOptions ¶
type BlobRenewLeaseOptions struct {
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobRenewLeaseOptions provides set of configurations for RenewLeaseBlob operation
type BlobRenewLeaseResponse ¶
type BlobRenewLeaseResponse struct {
// contains filtered or unexported fields
}
BlobRenewLeaseResponse contains the response from method BlobClient.RenewLease.
type BlobSASPermissions ¶
type BlobSASPermissions struct {
Read, Add, Create, Write, Delete, DeletePreviousVersion, Tag, List, Move, Execute, Ownership, Permissions bool
}
BlobSASPermissions type simplifies creating the permissions string for an Azure Storage blob SAS. Initialize an instance of this type and then call its String method to set BlobSASSignatureValues's Permissions field.
func (*BlobSASPermissions) Parse ¶
func (p *BlobSASPermissions) Parse(s string) error
Parse initializes the BlobSASPermissions's fields from a string.
func (BlobSASPermissions) String ¶
func (p BlobSASPermissions) String() string
String produces the SAS permissions string for an Azure Storage blob. Call this method to set BlobSASSignatureValues's Permissions field.
type BlobSASSignatureValues ¶
type BlobSASSignatureValues struct {
Version string `param:"sv"` // If not specified, this defaults to SASVersion
Protocol SASProtocol `param:"spr"` // See the SASProtocol* constants
StartTime time.Time `param:"st"` // Not specified if IsZero
ExpiryTime time.Time `param:"se"` // Not specified if IsZero
SnapshotTime time.Time
Permissions string `param:"sp"` // Create by initializing a ContainerSASPermissions or BlobSASPermissions and then call String()
IPRange IPRange `param:"sip"`
Identifier string `param:"si"`
ContainerName string
BlobName string // Use "" to create a Container SAS
Directory string // Not nil for a directory SAS (ie sr=d)
CacheControl string // rscc
ContentDisposition string // rscd
ContentEncoding string // rsce
ContentLanguage string // rscl
ContentType string // rsct
BlobVersion string // sr=bv
AgentObjectId string
CorrelationId string
}
BlobSASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage container or blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/constructing-a-service-sas
Example ¶
This example demonstrates how to create and use a Blob service Shared Access Signature (SAS)
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
containerName := "mycontainer"
blobName := "HelloWorld.txt"
sasQueryParams, err := azblob.BlobSASSignatureValues{
Protocol: azblob.SASProtocolHTTPS,
ExpiryTime: time.Now().UTC().Add(48 * time.Hour),
ContainerName: containerName,
BlobName: blobName,
Permissions: azblob.BlobSASPermissions{Add: true, Read: true, Write: true}.String(),
}.NewSASQueryParameters(credential)
if err != nil {
log.Fatal(err)
}
// Create the SAS URL for the resource you wish to access, and append the SAS query parameters.
qp := sasQueryParams.Encode()
sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s?%s", accountName, containerName, blobName, qp)
// Access the SAS-protected resource
blob, err := azblob.NewBlobClientWithNoCredential(sasURL, nil)
if err != nil {
log.Fatal(err)
}
// if you have a SAS query parameter string, you can parse it into it's parts.
blobURLParts, _ := azblob.NewBlobURLParts(blob.URL())
fmt.Printf("SAS expiry time=%v", blobURLParts.SAS.ExpiryTime())
}
func (BlobSASSignatureValues) NewSASQueryParameters ¶
func (v BlobSASSignatureValues) NewSASQueryParameters(sharedKeyCredential *SharedKeyCredential) (SASQueryParameters, error)
NewSASQueryParameters uses an account's StorageAccountCredential to sign this signature values to produce the proper SAS query parameters. See: StorageAccountCredential. Compatible with both UserDelegationCredential and SharedKeyCredential
type BlobSetHTTPHeadersOptions ¶
type BlobSetHTTPHeadersOptions struct {
LeaseAccessConditions *LeaseAccessConditions
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobSetHTTPHeadersOptions provides set of configurations for SetHTTPHeaders on blob operation
type BlobSetHTTPHeadersResponse ¶
type BlobSetHTTPHeadersResponse struct {
// contains filtered or unexported fields
}
BlobSetHTTPHeadersResponse contains the response from method BlobClient.SetHTTPHeaders.
type BlobSetMetadataOptions ¶
type BlobSetMetadataOptions struct {
LeaseAccessConditions *LeaseAccessConditions
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobSetMetadataOptions provides set of configurations for Set Metadata on blob operation
type BlobSetMetadataResponse ¶
type BlobSetMetadataResponse struct {
// contains filtered or unexported fields
}
BlobSetMetadataResponse contains the response from method BlobClient.SetMetadata.
type BlobSetTagsOptions ¶
type BlobSetTagsOptions struct {
// The version id parameter is an opaque DateTime value that, when present,
// specifies the version of the blob to operate on. It's for service version 2019-10-10 and newer.
VersionID *string
// Optional header, Specifies the transactional crc64 for the body, to be validated by the service.
TransactionalContentCRC64 []byte
// Optional header, Specifies the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 []byte
TagsMap map[string]string
ModifiedAccessConditions *ModifiedAccessConditions
LeaseAccessConditions *LeaseAccessConditions
}
BlobSetTagsOptions provides set of configurations for SetTags operation
type BlobSetTagsResponse ¶
type BlobSetTagsResponse struct {
// contains filtered or unexported fields
}
BlobSetTagsResponse contains the response from method BlobClient.SetTags
type BlobSetTierOptions ¶
type BlobSetTierOptions struct {
// Optional: Indicates the priority with which to rehydrate an archived blob.
RehydratePriority *RehydratePriority
LeaseAccessConditions *LeaseAccessConditions
ModifiedAccessConditions *ModifiedAccessConditions
}
BlobSetTierOptions provides set of configurations for SetTier on blob operation
type BlobSetTierResponse ¶
type BlobSetTierResponse struct {
// contains filtered or unexported fields
}
BlobSetTierResponse contains the response from method BlobClient.SetTier.
type BlobStartCopyFromURLResponse ¶
type BlobStartCopyFromURLResponse struct {
// contains filtered or unexported fields
}
BlobStartCopyFromURLResponse contains the response from method BlobClient.StartCopyFromURL.
type BlobStartCopyOptions ¶ added in v0.4.0
type BlobStartCopyOptions struct {
// Specifies the date time when the blobs immutability policy is set to expire.
ImmutabilityPolicyExpiry *time.Time
// Specifies the immutability policy mode to set on the blob.
ImmutabilityPolicyMode *BlobImmutabilityPolicyMode
// Specified if a legal hold should be set on the blob.
LegalHold *bool
// Optional. Used to set blob tags in various blob operations.
TagsMap map[string]string
// Optional. Specifies a user-defined name-value pair associated with the blob. If no name-value pairs are specified, the
// operation will copy the metadata from the source blob or file to the destination blob. If one or more name-value pairs
// are specified, the destination blob is created with the specified metadata, and metadata is not copied from the source
// blob or file. Note that beginning with version 2009-09-19, metadata names must adhere to the naming rules for C# identifiers.
// See Naming and Referencing Containers, Blobs, and Metadata for more information.
Metadata map[string]string
// Optional: Indicates the priority with which to rehydrate an archived blob.
RehydratePriority *RehydratePriority
// Overrides the sealed state of the destination blob. Service version 2019-12-12 and newer.
SealBlob *bool
// Optional. Indicates the tier to be set on the blob.
Tier *AccessTier
SourceModifiedAccessConditions *SourceModifiedAccessConditions
ModifiedAccessConditions *ModifiedAccessConditions
LeaseAccessConditions *LeaseAccessConditions
}
BlobStartCopyOptions provides set of configurations for StartCopyFromURL blob operation
type BlobTags ¶
type BlobTags struct {
// REQUIRED
BlobTagSet []*BlobTag `xml:"TagSet>Tag"`
}
BlobTags - Blob tags
func (BlobTags) MarshalXML ¶
MarshalXML implements the xml.Marshaller interface for type BlobTags.
type BlobType ¶
type BlobType string
BlobType enum
func PossibleBlobTypeValues ¶
func PossibleBlobTypeValues() []BlobType
PossibleBlobTypeValues returns the possible values for the BlobType const type.
type BlobURLParts ¶
type BlobURLParts struct {
Scheme string // Ex: "https://"
Host string // Ex: "account.blob.core.windows.net", "10.132.141.33", "10.132.141.33:80"
IPEndpointStyleInfo IPEndpointStyleInfo
ContainerName string // "" if no container
BlobName string // "" if no blob
Snapshot string // "" if not a snapshot
SAS SASQueryParameters
UnparsedParams string
VersionID string // "" if not versioning enabled
}
BlobURLParts object represents the components that make up an Azure Storage Container/Blob URL. You parse an existing URL into its parts by calling NewBlobURLParts(). You construct a URL from parts by calling URL(). NOTE: Changing any SAS-related field requires computing a new SAS signature.
Example ¶
This example demonstrates splitting a URL into its parts so you can examine and modify the URL in an Azure Storage fluent way.
package main
import (
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// Here is an example of a blob snapshot.
u := "https://myaccount.blob.core.windows.net/mycontainter/ReadMe.txt?" +
"snapshot=2011-03-09T01:42:34Z&" +
"sv=2015-02-21&sr=b&st=2111-01-09T01:42:34.936Z&se=2222-03-09T01:42:34.936Z&sp=rw&sip=168.1.5.60-168.1.5.70&" +
"spr=https,http&si=myIdentifier&ss=bf&srt=s&sig=92836758923659283652983562=="
// Breaking the URL down into it's parts by conversion to BlobURLParts
parts, _ := azblob.NewBlobURLParts(u)
// The BlobURLParts allows access to individual portions of a Blob URL
fmt.Printf("Host: %s\nContainerName: %s\nBlobName: %s\nSnapshot: %s\n", parts.Host, parts.ContainerName, parts.BlobName, parts.Snapshot)
fmt.Printf("Version: %s\nResource: %s\nStartTime: %s\nExpiryTime: %s\nPermissions: %s\n", parts.SAS.Version(), parts.SAS.Resource(), parts.SAS.StartTime(), parts.SAS.ExpiryTime(), parts.SAS.Permissions())
// You can alter fields to construct a new URL:
// Note: SAS tokens may be limited to a specific container or blob, be careful modifying SAS tokens, you might take them outside of their original scope accidentally.
parts.SAS = azblob.SASQueryParameters{}
parts.Snapshot = ""
parts.ContainerName = "othercontainer"
// construct a new URL from the parts
fmt.Print(parts.URL())
}
func NewBlobURLParts ¶
func NewBlobURLParts(u string) (BlobURLParts, error)
NewBlobURLParts parses a URL initializing BlobURLParts' fields including any SAS-related & snapshot query parameters. Any other query parameters remain in the UnparsedParams field. This method overwrites all fields in the BlobURLParts object.
func (BlobURLParts) URL ¶
func (up BlobURLParts) URL() string
URL returns a URL object whose fields are initialized from the BlobURLParts fields. The URL's RawQuery field contains the SAS, snapshot, and unparsed query parameters.
type BlobUndeleteOptions ¶
type BlobUndeleteOptions struct {
}
BlobUndeleteOptions provides set of configurations for Blob Undelete operation
type BlobUndeleteResponse ¶
type BlobUndeleteResponse struct {
// contains filtered or unexported fields
}
BlobUndeleteResponse contains the response from method BlobClient.Undelete.
type Block ¶
type Block struct {
// REQUIRED; The base64 encoded block ID.
Name *string `xml:"Name"`
// REQUIRED; The block size in bytes.
Size *int64 `xml:"Size"`
}
Block - Represents a single block in a block blob. It describes the block's ID and size.
type BlockBlobClient ¶
type BlockBlobClient struct {
BlobClient
// contains filtered or unexported fields
}
BlockBlobClient defines a set of operations applicable to block blobs.
Example ¶
ExampleBlockBlobClient shows how to upload data (in blocks) to a blob. A block blob can have a maximum of 50,000 blocks; each block can have a maximum of 100MB. The maximum size of a block blob is slightly more than 4.75 TB (100 MB X 50,000 blocks).
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"fmt"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
blobName := "test_block_blob.txt"
blobURL := fmt.Sprintf("https://%s.blob.core.windows.net/testcontainer/%s", accountName, blobName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
blockBlobClient, err := azblob.NewBlockBlobClient(blobURL, cred, nil)
if err != nil {
log.Fatal(err)
}
// NOTE: The blockID must be <= 64 bytes and ALL blockIDs for the block must be the same length
blockIDBinaryToBase64 := func(blockID []byte) string { return base64.StdEncoding.EncodeToString(blockID) }
blockIDBase64ToBinary := func(blockID string) []byte { _binary, _ := base64.StdEncoding.DecodeString(blockID); return _binary }
// These helper functions convert an int block ID to a base-64 string and vice versa
blockIDIntToBase64 := func(blockID int) string {
binaryBlockID := &[4]byte{} // All block IDs are 4 bytes long
binary.LittleEndian.PutUint32(binaryBlockID[:], uint32(blockID))
return blockIDBinaryToBase64(binaryBlockID[:])
}
blockIDBase64ToInt := func(blockID string) int {
blockIDBase64ToBinary(blockID)
return int(binary.LittleEndian.Uint32(blockIDBase64ToBinary(blockID)))
}
// Upload 4 blocks to the blob (these blocks are tiny; they can be up to 100MB each)
words := []string{"Azure ", "Storage ", "Block ", "Blob."}
base64BlockIDs := make([]string, len(words)) // The collection of block IDs (base 64 strings)
// Upload each block sequentially (one after the other)
for index, word := range words {
// This example uses the index as the block ID; convert the index/ID into a base-64 encoded string as required by the service.
// NOTE: Over the lifetime of a blob, all block IDs (before base 64 encoding) must be the same length (this example uses 4 byte block IDs).
base64BlockIDs[index] = blockIDIntToBase64(index)
// Upload a block to this blob specifying the Block ID and its content (up to 100MB); this block is uncommitted.
_, err := blockBlobClient.StageBlock(context.TODO(), base64BlockIDs[index], streaming.NopCloser(strings.NewReader(word)), nil)
if err != nil {
log.Fatal(err)
}
}
// After all the blocks are uploaded, atomically commit them to the blob.
_, err = blockBlobClient.CommitBlockList(context.TODO(), base64BlockIDs, nil)
if err != nil {
log.Fatal(err)
}
// For the blob, show each block (ID and size) that is a committed part of it.
getBlock, err := blockBlobClient.GetBlockList(context.TODO(), azblob.BlockListTypeAll, nil)
if err != nil {
log.Fatal(err)
}
for _, block := range getBlock.BlockList.CommittedBlocks {
fmt.Printf("Block ID=%d, Size=%d\n", blockIDBase64ToInt(*block.Name), block.Size)
}
// Download the blob in its entirety; download operations do not take blocks into account.
blobDownloadResponse, err := blockBlobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
blobData := &bytes.Buffer{}
reader := blobDownloadResponse.Body(nil)
_, err = blobData.ReadFrom(reader)
if err != nil {
return
}
err = reader.Close()
if err != nil {
return
}
fmt.Println(blobData)
}
func NewBlockBlobClient ¶
func NewBlockBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*BlockBlobClient, error)
NewBlockBlobClient creates a BlockBlobClient object using the specified URL, Azure AD credential, and options.
func NewBlockBlobClientWithNoCredential ¶ added in v0.2.0
func NewBlockBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*BlockBlobClient, error)
NewBlockBlobClientWithNoCredential creates a BlockBlobClient object using the specified URL and options.
func NewBlockBlobClientWithSharedKey ¶ added in v0.2.0
func NewBlockBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*BlockBlobClient, error)
NewBlockBlobClientWithSharedKey creates a BlockBlobClient object using the specified URL, shared key, and options.
func (*BlockBlobClient) CommitBlockList ¶
func (bb *BlockBlobClient) CommitBlockList(ctx context.Context, base64BlockIDs []string, options *BlockBlobCommitBlockListOptions) (BlockBlobCommitBlockListResponse, error)
CommitBlockList writes a blob by specifying the list of block IDs that make up the blob. In order to be written as part of a blob, a block must have been successfully written to the server in a prior PutBlock operation. You can call PutBlockList to update a blob by uploading only those blocks that have changed, then committing the new and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-block-list.
func (*BlockBlobClient) CopyFromURL ¶
func (bb *BlockBlobClient) CopyFromURL(ctx context.Context, source string, options *BlockBlobCopyFromURLOptions) (BlockBlobCopyFromURLResponse, error)
CopyFromURL synchronously copies the data at the source URL to a block blob, with sizes up to 256 MB. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url.
func (*BlockBlobClient) GetBlockList ¶
func (bb *BlockBlobClient) GetBlockList(ctx context.Context, listType BlockListType, options *BlockBlobGetBlockListOptions) (BlockBlobGetBlockListResponse, error)
GetBlockList returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-block-list.
func (*BlockBlobClient) StageBlock ¶
func (bb *BlockBlobClient) StageBlock(ctx context.Context, base64BlockID string, body io.ReadSeekCloser, options *BlockBlobStageBlockOptions) (BlockBlobStageBlockResponse, error)
StageBlock uploads the specified block to the block blob's "staging area" to be later committed by a call to CommitBlockList. Note that the http client closes the body stream after the request is sent to the service. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-block.
func (*BlockBlobClient) StageBlockFromURL ¶
func (bb *BlockBlobClient) StageBlockFromURL(ctx context.Context, base64BlockID string, sourceURL string, contentLength int64, options *BlockBlobStageBlockFromURLOptions) (BlockBlobStageBlockFromURLResponse, error)
StageBlockFromURL copies the specified block from a source URL to the block blob's "staging area" to be later committed by a call to CommitBlockList. If count is CountToEnd (0), then data is read from specified offset to the end. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url.
func (*BlockBlobClient) Upload ¶
func (bb *BlockBlobClient) Upload(ctx context.Context, body io.ReadSeekCloser, options *BlockBlobUploadOptions) (BlockBlobUploadResponse, error)
Upload creates a new block blob or overwrites an existing block blob. Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported with Upload; the content of the existing blob is overwritten with the new content. To perform a partial update of a block blob, use StageBlock and CommitBlockList. This method panics if the stream is not at position 0. Note that the http client closes the body stream after the request is sent to the service. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-blob.
func (*BlockBlobClient) UploadBuffer ¶ added in v0.4.0
func (bb *BlockBlobClient) UploadBuffer(ctx context.Context, b []byte, o UploadOption) (*http.Response, error)
UploadBuffer uploads a buffer in blocks to a block blob.
func (*BlockBlobClient) UploadFile ¶ added in v0.4.0
func (bb *BlockBlobClient) UploadFile(ctx context.Context, file *os.File, o UploadOption) (*http.Response, error)
UploadFile uploads a file in blocks to a block blob.
func (*BlockBlobClient) UploadStream ¶ added in v0.4.0
func (bb *BlockBlobClient) UploadStream(ctx context.Context, body io.Reader, o UploadStreamOptions) (BlockBlobCommitBlockListResponse, error)
UploadStream copies the file held in io.Reader to the Blob at blockBlobClient. A Context deadline or cancellation will cause this to error.
func (*BlockBlobClient) WithSnapshot ¶
func (bb *BlockBlobClient) WithSnapshot(snapshot string) (*BlockBlobClient, error)
WithSnapshot creates a new BlockBlobClient object identical to the source but with the specified snapshot timestamp. Pass "" to remove the snapshot returning a URL to the base blob.
func (*BlockBlobClient) WithVersionID ¶
func (bb *BlockBlobClient) WithVersionID(versionID string) (*BlockBlobClient, error)
WithVersionID creates a new AppendBlobURL object identical to the source but with the specified version id. Pass "" to remove the versionID returning a URL to the base blob.
type BlockBlobCommitBlockListOptions ¶
type BlockBlobCommitBlockListOptions struct {
BlobTagsMap map[string]string
Metadata map[string]string
RequestID *string
Tier *AccessTier
Timeout *int32
TransactionalContentCRC64 []byte
TransactionalContentMD5 []byte
BlobHTTPHeaders *BlobHTTPHeaders
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
BlobAccessConditions *BlobAccessConditions
}
BlockBlobCommitBlockListOptions provides set of configurations for CommitBlockList operation
type BlockBlobCommitBlockListResponse ¶
type BlockBlobCommitBlockListResponse struct {
// contains filtered or unexported fields
}
BlockBlobCommitBlockListResponse contains the response from method BlockBlobClient.CommitBlockList.
type BlockBlobCopyFromURLOptions ¶ added in v0.4.0
type BlockBlobCopyFromURLOptions struct {
// Optional. Used to set blob tags in various blob operations.
BlobTagsMap map[string]string
// Only Bearer type is supported. Credentials should be a valid OAuth access token to copy source.
CopySourceAuthorization *string
// Specifies the date time when the blobs immutability policy is set to expire.
ImmutabilityPolicyExpiry *time.Time
// Specifies the immutability policy mode to set on the blob.
ImmutabilityPolicyMode *BlobImmutabilityPolicyMode
// Specified if a legal hold should be set on the blob.
LegalHold *bool
// Optional. Specifies a user-defined name-value pair associated with the blob. If no name-value pairs are specified, the
// operation will copy the metadata from the source blob or file to the destination
// blob. If one or more name-value pairs are specified, the destination blob is created with the specified metadata, and metadata
// is not copied from the source blob or file. Note that beginning with
// version 2009-09-19, metadata names must adhere to the naming rules for C# identifiers. See Naming and Referencing Containers,
// Blobs, and Metadata for more information.
Metadata map[string]string
// Specify the md5 calculated for the range of bytes that must be read from the copy source.
SourceContentMD5 []byte
// Optional. Indicates the tier to be set on the blob.
Tier *AccessTier
SourceModifiedAccessConditions *SourceModifiedAccessConditions
BlobAccessConditions *BlobAccessConditions
}
BlockBlobCopyFromURLOptions provides set of configurations for CopyBlockBlobFromURL operation
type BlockBlobCopyFromURLResponse ¶ added in v0.4.0
type BlockBlobCopyFromURLResponse struct {
// contains filtered or unexported fields
}
BlockBlobCopyFromURLResponse contains the response from method BlockBlobClient.CopyFromURL.
type BlockBlobGetBlockListOptions ¶
type BlockBlobGetBlockListOptions struct {
Snapshot *string
BlobAccessConditions *BlobAccessConditions
}
BlockBlobGetBlockListOptions provides set of configurations for GetBlockList operation
type BlockBlobGetBlockListResponse ¶
type BlockBlobGetBlockListResponse struct {
// contains filtered or unexported fields
}
BlockBlobGetBlockListResponse contains the response from method BlockBlobClient.GetBlockList.
type BlockBlobStageBlockFromURLOptions ¶
type BlockBlobStageBlockFromURLOptions struct {
// Only Bearer type is supported. Credentials should be a valid OAuth access token to copy source.
CopySourceAuthorization *string
LeaseAccessConditions *LeaseAccessConditions
SourceModifiedAccessConditions *SourceModifiedAccessConditions
// Specify the md5 calculated for the range of bytes that must be read from the copy source.
SourceContentMD5 []byte
// Specify the crc64 calculated for the range of bytes that must be read from the copy source.
SourceContentCRC64 []byte
Offset *int64
Count *int64
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
}
BlockBlobStageBlockFromURLOptions provides set of configurations for StageBlockFromURL operation
type BlockBlobStageBlockFromURLResponse ¶
type BlockBlobStageBlockFromURLResponse struct {
// contains filtered or unexported fields
}
BlockBlobStageBlockFromURLResponse contains the response from method BlockBlobClient.StageBlockFromURL.
type BlockBlobStageBlockOptions ¶
type BlockBlobStageBlockOptions struct {
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
LeaseAccessConditions *LeaseAccessConditions
// Specify the transactional crc64 for the body, to be validated by the service.
TransactionalContentCRC64 []byte
// Specify the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 []byte
}
BlockBlobStageBlockOptions provides set of configurations for StageBlock operation
type BlockBlobStageBlockResponse ¶
type BlockBlobStageBlockResponse struct {
// contains filtered or unexported fields
}
BlockBlobStageBlockResponse contains the response from method BlockBlobClient.StageBlock.
type BlockBlobUploadOptions ¶
type BlockBlobUploadOptions struct {
// Optional. Used to set blob tags in various blob operations.
TagsMap map[string]string
// Optional. Specifies a user-defined name-value pair associated with the blob.
Metadata map[string]string
// Optional. Indicates the tier to be set on the blob.
Tier *AccessTier
// Specify the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 []byte
HTTPHeaders *BlobHTTPHeaders
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
BlobAccessConditions *BlobAccessConditions
}
BlockBlobUploadOptions provides set of configurations for UploadBlockBlob operation
type BlockBlobUploadResponse ¶
type BlockBlobUploadResponse struct {
// contains filtered or unexported fields
}
BlockBlobUploadResponse contains the response from method BlockBlobClient.Upload.
type BlockList ¶
type BlockList struct {
CommittedBlocks []*Block `xml:"CommittedBlocks>Block"`
UncommittedBlocks []*Block `xml:"UncommittedBlocks>Block"`
}
BlockList struct
func (BlockList) MarshalXML ¶
MarshalXML implements the xml.Marshaller interface for type BlockList.
type BlockListType ¶
type BlockListType string
BlockListType enum
const ( BlockListTypeCommitted BlockListType = "committed" BlockListTypeUncommitted BlockListType = "uncommitted" BlockListTypeAll BlockListType = "all" )
func PossibleBlockListTypeValues ¶
func PossibleBlockListTypeValues() []BlockListType
PossibleBlockListTypeValues returns the possible values for the BlockListType const type.
func (BlockListType) ToPtr ¶
func (c BlockListType) ToPtr() *BlockListType
ToPtr returns a *BlockListType pointing to the current value.
type BlockLookupList ¶
type BlockLookupList struct {
Committed []*string `xml:"Committed"`
Latest []*string `xml:"Latest"`
Uncommitted []*string `xml:"Uncommitted"`
}
BlockLookupList struct
func (BlockLookupList) MarshalXML ¶
func (b BlockLookupList) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type BlockLookupList.
type ClearRange ¶
type ClearRange struct {
// REQUIRED
End *int64 `xml:"End"`
// REQUIRED
Start *int64 `xml:"Start"`
}
ClearRange enum
type ClientOptions ¶
type ClientOptions struct {
// Logging configures the built-in logging policy.
Logging policy.LogOptions
// Retry configures the built-in retry policy.
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy.
Telemetry policy.TelemetryOptions
// Transport sets the transport for HTTP requests.
Transport policy.Transporter
// PerCallPolicies contains custom policies to inject into the pipeline.
// Each policy is executed once per request.
PerCallPolicies []policy.Policy
// PerRetryPolicies contains custom policies to inject into the pipeline.
// Each policy is executed once per request, and for each retry of that request.
PerRetryPolicies []policy.Policy
}
ClientOptions adds additional client options while constructing connection
type ContainerAccessConditions ¶
type ContainerAccessConditions struct {
ModifiedAccessConditions *ModifiedAccessConditions
LeaseAccessConditions *LeaseAccessConditions
}
ContainerAccessConditions identifies container-specific access conditions which you optionally set.
type ContainerAcquireLeaseOptions ¶
type ContainerAcquireLeaseOptions struct {
Duration *int32
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerAcquireLeaseOptions provides set of configurations for AcquireLeaseContainer operation
type ContainerAcquireLeaseResponse ¶
type ContainerAcquireLeaseResponse struct {
// contains filtered or unexported fields
}
ContainerAcquireLeaseResponse contains the response from method ContainerLeaseClient.AcquireLease.
type ContainerBreakLeaseOptions ¶
type ContainerBreakLeaseOptions struct {
BreakPeriod *int32
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerBreakLeaseOptions provides set of configurations for BreakLeaseContainer operation
type ContainerBreakLeaseResponse ¶
type ContainerBreakLeaseResponse struct {
// contains filtered or unexported fields
}
ContainerBreakLeaseResponse contains the response from method ContainerLeaseClient.BreakLease.
type ContainerChangeLeaseOptions ¶
type ContainerChangeLeaseOptions struct {
ProposedLeaseID *string
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerChangeLeaseOptions provides set of configurations for ChangeLeaseContainer operation
type ContainerChangeLeaseResponse ¶
type ContainerChangeLeaseResponse struct {
// contains filtered or unexported fields
}
ContainerChangeLeaseResponse contains the response from method ContainerLeaseClient.ChangeLease.
type ContainerClient ¶
type ContainerClient struct {
// contains filtered or unexported fields
}
ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs.
func NewContainerClient ¶
func NewContainerClient(containerURL string, cred azcore.TokenCredential, options *ClientOptions) (*ContainerClient, error)
NewContainerClient creates a ContainerClient object using the specified URL, Azure AD credential, and options.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(containerClient)
}
func NewContainerClientFromConnectionString ¶
func NewContainerClientFromConnectionString(connectionString string, containerName string, options *ClientOptions) (*ContainerClient, error)
NewContainerClientFromConnectionString creates a ContainerClient object using connection string of an account
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// Your connection string can be obtained from the Azure Portal.
connectionString, ok := os.LookupEnv("BLOB_STORAGE_CONNECTION_STRING")
if !ok {
log.Fatal("the environment variable 'AZURE_STORAGE_CONNECTION_STRING' could not be found")
}
containerName := "testcontainer"
containerClient, err := azblob.NewContainerClientFromConnectionString(connectionString, containerName, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(containerClient)
}
func NewContainerClientWithNoCredential ¶ added in v0.2.0
func NewContainerClientWithNoCredential(containerURL string, options *ClientOptions) (*ContainerClient, error)
NewContainerClientWithNoCredential creates a ContainerClient object using the specified URL and options.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
sharedAccessSignature, ok := os.LookupEnv("BLOB_STORAGE_SHARED_ACCESS_SIGNATURE")
if !ok {
panic("BLOB_STORAGE_SHARED_ACCESS_SIGNATURE could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s?%s", accountName, containerName, sharedAccessSignature)
containerClient, err := azblob.NewContainerClientWithNoCredential(containerURL, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(containerClient)
}
func NewContainerClientWithSharedKey ¶ added in v0.2.0
func NewContainerClientWithSharedKey(containerURL string, cred *SharedKeyCredential, options *ClientOptions) (*ContainerClient, error)
NewContainerClientWithSharedKey creates a ContainerClient object using the specified URL, shared key, and options.
func (*ContainerClient) Create ¶
func (c *ContainerClient) Create(ctx context.Context, options *ContainerCreateOptions) (ContainerCreateResponse, error)
Create creates a new container within a storage account. If a container with the same name already exists, the operation fails. For more information, see https://docs.microsoft.com/rest/api/storageservices/create-container.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
containerCreateResponse, err := containerClient.Create(context.TODO(), &azblob.ContainerCreateOptions{
Metadata: map[string]string{"Foo": "Bar"},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(containerCreateResponse)
}
func (*ContainerClient) Delete ¶
func (c *ContainerClient) Delete(ctx context.Context, o *ContainerDeleteOptions) (ContainerDeleteResponse, error)
Delete marks the specified container for deletion. The container and any blobs contained within it are later deleted during garbage collection. For more information, see https://docs.microsoft.com/rest/api/storageservices/delete-container.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
containerDeleteResponse, err := containerClient.Delete(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(containerDeleteResponse)
}
func (*ContainerClient) GetAccessPolicy ¶
func (c *ContainerClient) GetAccessPolicy(ctx context.Context, o *ContainerGetAccessPolicyOptions) (ContainerGetAccessPolicyResponse, error)
GetAccessPolicy returns the container's access policy. The access policy indicates whether container's blobs may be accessed publicly. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-container-acl.
func (*ContainerClient) GetProperties ¶
func (c *ContainerClient) GetProperties(ctx context.Context, o *ContainerGetPropertiesOptions) (ContainerGetPropertiesResponse, error)
GetProperties returns the container's properties. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-container-metadata.
func (*ContainerClient) GetSASURL ¶ added in v0.4.0
func (c *ContainerClient) GetSASURL(permissions ContainerSASPermissions, start time.Time, expiry time.Time) (string, error)
GetSASURL is a convenience method for generating a SAS token for the currently pointed at container. It can only be used if the credential supplied during creation was a SharedKeyCredential.
Example ¶
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
permission := azblob.ContainerSASPermissions{Read: true}
start := time.Now()
expiry := start.AddDate(1, 0, 0)
sasURL, err := containerClient.GetSASURL(permission, start, expiry)
if err != nil {
log.Fatal(err)
}
_ = sasURL
}
func (*ContainerClient) ListBlobsFlat ¶
func (c *ContainerClient) ListBlobsFlat(o *ContainerListBlobsFlatOptions) *ContainerListBlobFlatPager
ListBlobsFlat returns a pager for blobs starting from the specified Marker. Use an empty Marker to start enumeration from the beginning. Blob names are returned in lexicographic order. For more information, see https://docs.microsoft.com/rest/api/storageservices/list-blobs.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
pager := containerClient.ListBlobsFlat(&azblob.ContainerListBlobsFlatOptions{
Include: []azblob.ListBlobsIncludeItem{azblob.ListBlobsIncludeItemSnapshots, azblob.ListBlobsIncludeItemVersions},
})
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, blob := range resp.Segment.BlobItems {
fmt.Println(*blob.Name)
}
}
if pager.Err() != nil {
log.Fatal(pager.Err())
}
}
func (*ContainerClient) ListBlobsHierarchy ¶
func (c *ContainerClient) ListBlobsHierarchy(delimiter string, o *ContainerListBlobsHierarchyOptions) *ContainerListBlobHierarchyPager
ListBlobsHierarchy returns a channel of blobs starting from the specified Marker. Use an empty Marker to start enumeration from the beginning. Blob names are returned in lexicographic order. After getting a segment, process it, and then call ListBlobsHierarchicalSegment again (passing the the previously-returned Marker) to get the next segment. For more information, see https://docs.microsoft.com/rest/api/storageservices/list-blobs. AutoPagerTimeout specifies the amount of time with no read operations before the channel times out and closes. Specify no time and it will be ignored. AutoPagerBufferSize specifies the channel's buffer size. Both the blob item channel and error channel should be watched. Only one error will be released via this channel (or a nil error, to register a clean exit.)
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
maxResults := int32(5)
pager := containerClient.ListBlobsHierarchy("/", &azblob.ContainerListBlobsHierarchyOptions{
Include: []azblob.ListBlobsIncludeItem{
azblob.ListBlobsIncludeItemMetadata,
azblob.ListBlobsIncludeItemTags,
},
MaxResults: &maxResults,
})
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, blob := range resp.ListBlobsHierarchySegmentResponse.Segment.BlobItems {
fmt.Println(*blob.Name)
}
}
if pager.Err() != nil {
log.Fatal(pager.Err())
}
}
func (*ContainerClient) NewAppendBlobClient ¶
func (c *ContainerClient) NewAppendBlobClient(blobName string) (*AppendBlobClient, error)
NewAppendBlobClient creates a new AppendBlobURL object by concatenating blobName to the end of ContainerClient's URL. The new AppendBlobURL uses the same request policy pipeline as the ContainerClient. To change the pipeline, create the AppendBlobURL and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewAppendBlobClient instead of calling this object's NewAppendBlobClient method.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
appendBlobClient, err := containerClient.NewAppendBlobClient("test_append_blob")
if err != nil {
log.Fatal(err)
}
fmt.Println(appendBlobClient)
}
func (*ContainerClient) NewBlobClient ¶
func (c *ContainerClient) NewBlobClient(blobName string) (*BlobClient, error)
NewBlobClient creates a new BlobClient object by concatenating blobName to the end of ContainerClient's URL. The new BlobClient uses the same request policy pipeline as the ContainerClient. To change the pipeline, create the BlobClient and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewBlobClient instead of calling this object's NewBlobClient method.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
blobClient, err := containerClient.NewBlobClient("test_blob")
if err != nil {
log.Fatal(err)
}
fmt.Println(blobClient)
}
func (*ContainerClient) NewBlockBlobClient ¶
func (c *ContainerClient) NewBlockBlobClient(blobName string) (*BlockBlobClient, error)
NewBlockBlobClient creates a new BlockBlobClient object by concatenating blobName to the end of ContainerClient's URL. The new BlockBlobClient uses the same request policy pipeline as the ContainerClient. To change the pipeline, create the BlockBlobClient and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewBlockBlobClient instead of calling this object's NewBlockBlobClient method.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
blockBlobClient, err := containerClient.NewBlockBlobClient("test_block_blob")
if err != nil {
log.Fatal(err)
}
fmt.Println(blockBlobClient)
}
func (*ContainerClient) NewContainerLeaseClient ¶
func (c *ContainerClient) NewContainerLeaseClient(leaseID *string) (*ContainerLeaseClient, error)
NewContainerLeaseClient is constructor of ContainerLeaseClient
func (*ContainerClient) NewPageBlobClient ¶
func (c *ContainerClient) NewPageBlobClient(blobName string) (*PageBlobClient, error)
NewPageBlobClient creates a new PageBlobURL object by concatenating blobName to the end of ContainerClient's URL. The new PageBlobURL uses the same request policy pipeline as the ContainerClient. To change the pipeline, create the PageBlobURL and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewPageBlobClient instead of calling this object's NewPageBlobClient method.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
pageBlobClient, err := containerClient.NewPageBlobClient("test_page_blob")
if err != nil {
log.Fatal(err)
}
fmt.Println(pageBlobClient)
}
func (*ContainerClient) SetAccessPolicy ¶
func (c *ContainerClient) SetAccessPolicy(ctx context.Context, o *ContainerSetAccessPolicyOptions) (ContainerSetAccessPolicyResponse, error)
SetAccessPolicy sets the container's permissions. The access policy indicates whether blobs in a container may be accessed publicly. For more information, see https://docs.microsoft.com/rest/api/storageservices/set-container-acl.
Example ¶
This example shows how to manipulate a container's permissions.
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
// Create the container
_, err = containerClient.Create(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Upload a simple blob.
blockBlobClient, err := containerClient.NewBlockBlobClient("HelloWorld.txt")
if err != nil {
log.Fatal(err)
}
_, err = blockBlobClient.Upload(context.TODO(), streaming.NopCloser(strings.NewReader("Hello World!")), nil)
if err != nil {
log.Fatal(err)
}
// Attempt to read the blob
get, err := http.Get(blockBlobClient.URL())
if err != nil {
log.Fatal(err)
}
if get.StatusCode == http.StatusNotFound {
// Change the blob to be public access blob
_, err := containerClient.SetAccessPolicy(
context.TODO(),
&azblob.ContainerSetAccessPolicyOptions{
Access: azblob.PublicAccessTypeBlob.ToPtr(),
},
)
if err != nil {
log.Fatal(err)
}
// Now, this works
get, err = http.Get(blockBlobClient.URL())
if err != nil {
log.Fatal(err)
}
var text bytes.Buffer
_, err = text.ReadFrom(get.Body)
if err != nil {
return
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(get.Body)
fmt.Println("Public access blob data: ", text.String())
}
}
func (*ContainerClient) SetMetadata ¶
func (c *ContainerClient) SetMetadata(ctx context.Context, o *ContainerSetMetadataOptions) (ContainerSetMetadataResponse, error)
SetMetadata sets the container's metadata. For more information, see https://docs.microsoft.com/rest/api/storageservices/set-container-metadata.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
containerName := "testcontainer"
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
containerClient, err := azblob.NewContainerClient(containerURL, cred, nil)
if err != nil {
log.Fatal(err)
}
// Create a container with some metadata, key names are converted to lowercase before being sent to the service.
// You should always use lowercase letters, especially when querying a map for a metadata key.
creatingApp, err := os.Executable()
if err != nil {
log.Fatal(err)
}
_, err = containerClient.Create(context.TODO(), &azblob.ContainerCreateOptions{Metadata: map[string]string{"author": "azblob", "app": creatingApp}})
if err != nil {
log.Fatal(err)
}
// Query the container's metadata
containerGetPropertiesResponse, err := containerClient.GetProperties(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
if containerGetPropertiesResponse.Metadata == nil {
log.Fatal("metadata is empty!")
}
for k, v := range containerGetPropertiesResponse.Metadata {
fmt.Printf("%s=%s\n", k, v)
}
// Update the metadata and write it back to the container
containerGetPropertiesResponse.Metadata["author"] = "Mohit"
_, err = containerClient.SetMetadata(context.TODO(), &azblob.ContainerSetMetadataOptions{Metadata: containerGetPropertiesResponse.Metadata})
if err != nil {
log.Fatal(err)
}
// NOTE: SetMetadata & SetProperties methods update the container's ETag & LastModified properties
}
func (*ContainerClient) URL ¶
func (c *ContainerClient) URL() string
URL returns the URL endpoint used by the ContainerClient object.
type ContainerCpkScopeInfo ¶
type ContainerCpkScopeInfo struct {
// Optional. Version 2019-07-07 and later. Specifies the default encryption scope to set on the container and use for all
// future writes.
DefaultEncryptionScope *string
// Optional. Version 2019-07-07 and newer. If true, prevents any request from specifying a different encryption scope than
// the scope set on the container.
PreventEncryptionScopeOverride *bool
}
ContainerCpkScopeInfo contains a group of parameters for the containerClient.Create method.
type ContainerCreateOptions ¶
type ContainerCreateOptions struct {
// Specifies whether data in the container may be accessed publicly and the level of access
Access *PublicAccessType
// Optional. Specifies a user-defined name-value pair associated with the blob.
Metadata map[string]string
// Optional. Specifies the encryption scope settings to set on the container.
CpkScope *ContainerCpkScopeInfo
}
ContainerCreateOptions provides set of configurations for CreateContainer operation
type ContainerCreateResponse ¶
type ContainerCreateResponse struct {
// contains filtered or unexported fields
}
ContainerCreateResponse is wrapper around containerClientCreateResponse
type ContainerDeleteOptions ¶
type ContainerDeleteOptions struct {
LeaseAccessConditions *LeaseAccessConditions
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerDeleteOptions provides set of configurations for DeleteContainer operation
type ContainerDeleteResponse ¶
type ContainerDeleteResponse struct {
// contains filtered or unexported fields
}
ContainerDeleteResponse contains the response from method ContainerClient.Delete.
type ContainerGetAccessPolicyOptions ¶
type ContainerGetAccessPolicyOptions struct {
LeaseAccessConditions *LeaseAccessConditions
}
ContainerGetAccessPolicyOptions provides set of configurations for GetAccessPolicy operation
type ContainerGetAccessPolicyResponse ¶
type ContainerGetAccessPolicyResponse struct {
// contains filtered or unexported fields
}
ContainerGetAccessPolicyResponse contains the response from method ContainerClient.GetAccessPolicy.
type ContainerGetPropertiesOptions ¶
type ContainerGetPropertiesOptions struct {
LeaseAccessConditions *LeaseAccessConditions
}
ContainerGetPropertiesOptions provides set of configurations for GetPropertiesContainer operation
type ContainerGetPropertiesResponse ¶
type ContainerGetPropertiesResponse struct {
// contains filtered or unexported fields
}
ContainerGetPropertiesResponse contains the response from method ContainerClient.GetProperties
type ContainerItem ¶
type ContainerItem struct {
// REQUIRED
Name *string `xml:"Name"`
// REQUIRED; Properties of a container
Properties *ContainerProperties `xml:"Properties"`
Deleted *bool `xml:"Deleted"`
// Dictionary of
Metadata map[string]*string `xml:"Metadata"`
Version *string `xml:"Version"`
}
ContainerItem - An Azure Storage container
func (*ContainerItem) UnmarshalXML ¶
func (c *ContainerItem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type ContainerItem.
type ContainerLeaseClient ¶
type ContainerLeaseClient struct {
ContainerClient
// contains filtered or unexported fields
}
ContainerLeaseClient represents lease client of container
Example ¶
This example shows how to perform various lease operations on a container. The same lease operations can be performed on individual blobs as well. A lease on a container prevents it from being deleted by others, while a lease on a blob protects it from both modifications and deletions.
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// From the Azure portal, get your Storage account's name and account key.
accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")
// Use your Storage account's name and key to create a credential object; this is used to access your account.
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
log.Fatal(err)
}
// Create an containerClient object that wraps the container's URL and a default pipeline.
containerURL := fmt.Sprintf("https://%s.blob.core.windows.net/mycontainer", accountName)
containerClient, err := azblob.NewContainerClientWithSharedKey(containerURL, credential, nil)
if err != nil {
log.Fatal(err)
}
// Create a unique ID for the lease
// A lease ID can be any valid GUID string format. To generate UUIDs, consider the github.com/google/uuid package
leaseID := "36b1a876-cf98-4eb2-a5c3-6d68489658ff"
containerLeaseClient, err := containerClient.NewContainerLeaseClient(to.Ptr(leaseID))
if err != nil {
log.Fatal(err)
}
// Now acquire a lease on the container.
// You can choose to pass an empty string for proposed ID so that the service automatically assigns one for you.
duration := int32(60)
acquireLeaseResponse, err := containerLeaseClient.AcquireLease(context.TODO(), &azblob.ContainerAcquireLeaseOptions{Duration: &duration})
if err != nil {
log.Fatal(err)
}
fmt.Println("The container is leased for delete operations with lease ID", *acquireLeaseResponse.LeaseID)
// The container cannot be deleted without providing the lease ID.
_, err = containerLeaseClient.Delete(context.TODO(), nil)
if err == nil {
log.Fatal("delete should have failed")
}
fmt.Println("The container cannot be deleted while there is an active lease")
// We can release the lease now and the container can be deleted.
_, err = containerLeaseClient.ReleaseLease(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("The lease on the container is now released")
// Acquire a lease again to perform other operations.
// Duration is still 60
acquireLeaseResponse, err = containerLeaseClient.AcquireLease(context.TODO(), &azblob.ContainerAcquireLeaseOptions{Duration: &duration})
if err != nil {
log.Fatal(err)
}
fmt.Println("The container is leased again with lease ID", *acquireLeaseResponse.LeaseID)
// We can change the ID of an existing lease.
newLeaseID := "6b3e65e5-e1bb-4a3f-8b72-13e9bc9cd3bf"
changeLeaseResponse, err := containerLeaseClient.ChangeLease(context.TODO(),
&azblob.ContainerChangeLeaseOptions{ProposedLeaseID: to.Ptr(newLeaseID)})
if err != nil {
log.Fatal(err)
}
fmt.Println("The lease ID was changed to", *changeLeaseResponse.LeaseID)
// The lease can be renewed.
renewLeaseResponse, err := containerLeaseClient.RenewLease(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("The lease was renewed with the same ID", *renewLeaseResponse.LeaseID)
// Finally, the lease can be broken and we could prevent others from acquiring a lease for a period of time
_, err = containerLeaseClient.BreakLease(context.TODO(), &azblob.ContainerBreakLeaseOptions{BreakPeriod: to.Ptr(int32(60))})
if err != nil {
log.Fatal(err)
}
fmt.Println("The lease was broken, and nobody can acquire a lease for 60 seconds")
}
func (*ContainerLeaseClient) AcquireLease ¶
func (clc *ContainerLeaseClient) AcquireLease(ctx context.Context, options *ContainerAcquireLeaseOptions) (ContainerAcquireLeaseResponse, error)
AcquireLease acquires a lease on the container for delete operations. The lease Duration must be between 15 to 60 seconds, or infinite (-1). For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-container.
func (*ContainerLeaseClient) BreakLease ¶
func (clc *ContainerLeaseClient) BreakLease(ctx context.Context, options *ContainerBreakLeaseOptions) (ContainerBreakLeaseResponse, error)
BreakLease breaks the container's previously-acquired lease (if it exists). For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-container.
func (*ContainerLeaseClient) ChangeLease ¶
func (clc *ContainerLeaseClient) ChangeLease(ctx context.Context, options *ContainerChangeLeaseOptions) (ContainerChangeLeaseResponse, error)
ChangeLease changes the container's lease ID. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-container.
func (*ContainerLeaseClient) ReleaseLease ¶
func (clc *ContainerLeaseClient) ReleaseLease(ctx context.Context, options *ContainerReleaseLeaseOptions) (ContainerReleaseLeaseResponse, error)
ReleaseLease releases the container's previously-acquired lease. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-container.
func (*ContainerLeaseClient) RenewLease ¶
func (clc *ContainerLeaseClient) RenewLease(ctx context.Context, options *ContainerRenewLeaseOptions) (ContainerRenewLeaseResponse, error)
RenewLease renews the container's previously-acquired lease. For more information, see https://docs.microsoft.com/rest/api/storageservices/lease-container.
type ContainerListBlobFlatPager ¶ added in v0.4.0
type ContainerListBlobFlatPager struct {
// contains filtered or unexported fields
}
ContainerListBlobFlatPager provides operations for iterating over paged responses
func (ContainerListBlobFlatPager) Err ¶ added in v0.4.0
func (p ContainerListBlobFlatPager) Err() error
Err returns the last error encountered while paging.
func (ContainerListBlobFlatPager) NextPage ¶ added in v0.4.0
NextPage returns true if the pager advanced to the next page. Returns false if there are no more pages or an error occurred.
func (ContainerListBlobFlatPager) PageResponse ¶ added in v0.4.0
func (p ContainerListBlobFlatPager) PageResponse() containerClientListBlobFlatSegmentResponse
PageResponse returns the current containerClientListBlobFlatSegmentResponse page.
type ContainerListBlobHierarchyPager ¶ added in v0.4.0
type ContainerListBlobHierarchyPager struct {
// contains filtered or unexported fields
}
ContainerListBlobHierarchyPager provides operations for iterating over paged responses.
func (*ContainerListBlobHierarchyPager) Err ¶ added in v0.4.0
func (p *ContainerListBlobHierarchyPager) Err() error
Err returns the last error encountered while paging.
func (*ContainerListBlobHierarchyPager) NextPage ¶ added in v0.4.0
NextPage returns true if the pager advanced to the next page. Returns false if there are no more pages or an error occurred.
func (*ContainerListBlobHierarchyPager) PageResponse ¶ added in v0.4.0
func (p *ContainerListBlobHierarchyPager) PageResponse() containerClientListBlobHierarchySegmentResponse
PageResponse returns the current containerClientListBlobHierarchySegmentResponse page.
type ContainerListBlobsFlatOptions ¶ added in v0.4.0
type ContainerListBlobsFlatOptions struct {
// Include this parameter to specify one or more datasets to include in the response.
Include []ListBlobsIncludeItem
// A string value that identifies the portion of the list of containers to be returned with the next listing operation. The
// operation returns the NextMarker value within the response body if the listing
// operation did not return all containers remaining to be listed with the current page. The NextMarker value can be used
// as the value for the marker parameter in a subsequent call to request the next
// page of list items. The marker value is opaque to the client.
Marker *string
// Specifies the maximum number of containers to return. If the request does not specify maxresults, or specifies a value
// greater than 5000, the server will return up to 5000 items. Note that if the
// listing operation crosses a partition boundary, then the service will return a continuation token for retrieving the remainder
// of the results. For this reason, it is possible that the service will
// return fewer results than specified by maxresults, or than the default of 5000.
MaxResults *int32
// Filters the results to return only containers whose name begins with the specified prefix.
Prefix *string
}
ContainerListBlobsFlatOptions provides set of configurations for SetAccessPolicy operation
type ContainerListBlobsHierarchyOptions ¶ added in v0.4.0
type ContainerListBlobsHierarchyOptions struct {
// Include this parameter to specify one or more datasets to include in the response.
Include []ListBlobsIncludeItem
// A string value that identifies the portion of the list of containers to be returned with the next listing operation. The
// operation returns the NextMarker value within the response body if the listing
// operation did not return all containers remaining to be listed with the current page. The NextMarker value can be used
// as the value for the marker parameter in a subsequent call to request the next
// page of list items. The marker value is opaque to the client.
Marker *string
// Specifies the maximum number of containers to return. If the request does not specify maxresults, or specifies a value
// greater than 5000, the server will return up to 5000 items. Note that if the
// listing operation crosses a partition boundary, then the service will return a continuation token for retrieving the remainder
// of the results. For this reason, it is possible that the service will
// return fewer results than specified by maxresults, or than the default of 5000.
MaxResults *int32
// Filters the results to return only containers whose name begins with the specified prefix.
Prefix *string
}
ContainerListBlobsHierarchyOptions provides set of configurations for ContainerClient.ListBlobsHierarchy
type ContainerProperties ¶
type ContainerProperties struct {
// REQUIRED
Etag *string `xml:"Etag"`
// REQUIRED
LastModified *time.Time `xml:"Last-Modified"`
DefaultEncryptionScope *string `xml:"DefaultEncryptionScope"`
DeletedTime *time.Time `xml:"DeletedTime"`
HasImmutabilityPolicy *bool `xml:"HasImmutabilityPolicy"`
HasLegalHold *bool `xml:"HasLegalHold"`
// Indicates if version level worm is enabled on this container.
IsImmutableStorageWithVersioningEnabled *bool `xml:"ImmutableStorageWithVersioningEnabled"`
LeaseDuration *LeaseDurationType `xml:"LeaseDuration"`
LeaseState *LeaseStateType `xml:"LeaseState"`
LeaseStatus *LeaseStatusType `xml:"LeaseStatus"`
PreventEncryptionScopeOverride *bool `xml:"DenyEncryptionScopeOverride"`
PublicAccess *PublicAccessType `xml:"PublicAccess"`
RemainingRetentionDays *int32 `xml:"RemainingRetentionDays"`
}
ContainerProperties - Properties of a container
func (ContainerProperties) MarshalXML ¶
func (c ContainerProperties) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type ContainerProperties.
func (*ContainerProperties) UnmarshalXML ¶
func (c *ContainerProperties) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type ContainerProperties.
type ContainerReleaseLeaseOptions ¶
type ContainerReleaseLeaseOptions struct {
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerReleaseLeaseOptions provides set of configurations for ReleaseLeaseContainer operation
type ContainerReleaseLeaseResponse ¶
type ContainerReleaseLeaseResponse struct {
// contains filtered or unexported fields
}
ContainerReleaseLeaseResponse contains the response from method ContainerLeaseClient.ReleaseLease.
type ContainerRenewLeaseOptions ¶
type ContainerRenewLeaseOptions struct {
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerRenewLeaseOptions provides set of configurations for RenewLeaseContainer operation
type ContainerRenewLeaseResponse ¶
type ContainerRenewLeaseResponse struct {
// contains filtered or unexported fields
}
ContainerRenewLeaseResponse contains the response from method ContainerLeaseClient.RenewLease.
type ContainerSASPermissions ¶
type ContainerSASPermissions struct {
Read, Add, Create, Write, Delete, DeletePreviousVersion, List, Tag bool
Execute, ModifyOwnership, ModifyPermissions bool // Hierarchical Namespace only
}
ContainerSASPermissions type simplifies creating the permissions string for an Azure Storage container SAS. Initialize an instance of this type and then call its String method to set BlobSASSignatureValues's Permissions field. All permissions descriptions can be found here: https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas#permissions-for-a-directory-container-or-blob
func (*ContainerSASPermissions) Parse ¶
func (p *ContainerSASPermissions) Parse(s string) error
Parse initializes the ContainerSASPermissions's fields from a string.
func (ContainerSASPermissions) String ¶
func (p ContainerSASPermissions) String() string
String produces the SAS permissions string for an Azure Storage container. Call this method to set BlobSASSignatureValues's Permissions field.
type ContainerSetAccessPolicyOptions ¶
type ContainerSetAccessPolicyOptions struct {
AccessConditions *ContainerAccessConditions
// Specifies whether data in the container may be accessed publicly and the level of access
Access *PublicAccessType
// the acls for the container
ContainerACL []*SignedIdentifier
// Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage
// analytics logging is enabled.
RequestID *string
// The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for Blob Service Operations.
// [https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting-timeouts-for-blob-service-operations]
Timeout *int32
}
ContainerSetAccessPolicyOptions provides set of configurations for ContainerClient.SetAccessPolicy operation
type ContainerSetAccessPolicyResponse ¶
type ContainerSetAccessPolicyResponse struct {
// contains filtered or unexported fields
}
ContainerSetAccessPolicyResponse contains the response from method ContainerClient.SetAccessPolicy
type ContainerSetMetadataOptions ¶
type ContainerSetMetadataOptions struct {
Metadata map[string]string
LeaseAccessConditions *LeaseAccessConditions
ModifiedAccessConditions *ModifiedAccessConditions
}
ContainerSetMetadataOptions provides set of configurations for SetMetadataContainer operation
type ContainerSetMetadataResponse ¶
type ContainerSetMetadataResponse struct {
// contains filtered or unexported fields
}
ContainerSetMetadataResponse contains the response from method containerClient.SetMetadata
type CopyStatusType ¶
type CopyStatusType string
CopyStatusType enum
const ( CopyStatusTypePending CopyStatusType = "pending" CopyStatusTypeSuccess CopyStatusType = "success" CopyStatusTypeAborted CopyStatusType = "aborted" CopyStatusTypeFailed CopyStatusType = "failed" )
func PossibleCopyStatusTypeValues ¶
func PossibleCopyStatusTypeValues() []CopyStatusType
PossibleCopyStatusTypeValues returns the possible values for the CopyStatusType const type.
func (CopyStatusType) ToPtr ¶
func (c CopyStatusType) ToPtr() *CopyStatusType
ToPtr returns a *CopyStatusType pointing to the current value.
type CorsRule ¶
type CorsRule struct {
// REQUIRED; the request headers that the origin domain may specify on the CORS request.
AllowedHeaders *string `xml:"AllowedHeaders"`
// REQUIRED; The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated)
AllowedMethods *string `xml:"AllowedMethods"`
// REQUIRED; The origin domains that are permitted to make a request against the storage service via CORS. The origin domain
// is the domain from which the request originates. Note that the origin must be an exact
// case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*'
// to allow all origin domains to make requests via CORS.
AllowedOrigins *string `xml:"AllowedOrigins"`
// REQUIRED; The response headers that may be sent in the response to the CORS request and exposed by the browser to the request
// issuer
ExposedHeaders *string `xml:"ExposedHeaders"`
// REQUIRED; The maximum amount time that a browser should cache the preflight OPTIONS request.
MaxAgeInSeconds *int32 `xml:"MaxAgeInSeconds"`
}
CorsRule - CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain
type CpkInfo ¶
type CpkInfo struct {
// The algorithm used to produce the encryption key hash. Currently, the only accepted value is "AES256". Must be provided
// if the x-ms-encryption-key header is provided.
EncryptionAlgorithm *EncryptionAlgorithmType
// Optional. Specifies the encryption key to use to encrypt the data provided in the request. If not specified, encryption
// is performed with the root account encryption key. For more information, see
// Encryption at Rest for Azure Storage Services.
EncryptionKey *string
// The SHA-256 hash of the provided encryption key. Must be provided if the x-ms-encryption-key header is provided.
EncryptionKeySHA256 *string
}
CpkInfo contains a group of parameters for the blobClient.Download method.
type CpkScopeInfo ¶
type CpkScopeInfo struct {
// Optional. Version 2019-07-07 and later. Specifies the name of the encryption scope to use to encrypt the data provided
// in the request. If not specified, encryption is performed with the default
// account encryption scope. For more information, see Encryption at Rest for Azure Storage Services.
EncryptionScope *string
}
CpkScopeInfo contains a group of parameters for the blobClient.SetMetadata method.
type DeleteSnapshotsOptionType ¶
type DeleteSnapshotsOptionType string
DeleteSnapshotsOptionType enum
const ( DeleteSnapshotsOptionTypeInclude DeleteSnapshotsOptionType = "include" DeleteSnapshotsOptionTypeOnly DeleteSnapshotsOptionType = "only" )
func PossibleDeleteSnapshotsOptionTypeValues ¶
func PossibleDeleteSnapshotsOptionTypeValues() []DeleteSnapshotsOptionType
PossibleDeleteSnapshotsOptionTypeValues returns the possible values for the DeleteSnapshotsOptionType const type.
func (DeleteSnapshotsOptionType) ToPtr ¶
func (c DeleteSnapshotsOptionType) ToPtr() *DeleteSnapshotsOptionType
ToPtr returns a *DeleteSnapshotsOptionType pointing to the current value.
type DelimitedTextConfiguration ¶
type DelimitedTextConfiguration struct {
// The string used to separate columns.
ColumnSeparator *string `xml:"ColumnSeparator"`
// The string used as an escape character.
EscapeChar *string `xml:"EscapeChar"`
// The string used to quote a specific field.
FieldQuote *string `xml:"FieldQuote"`
// Represents whether the data has headers.
HeadersPresent *bool `xml:"HasHeaders"`
// The string used to separate records.
RecordSeparator *string `xml:"RecordSeparator"`
}
DelimitedTextConfiguration - Groups the settings used for interpreting the blob data if the blob is delimited text formatted.
type DownloadOptions ¶ added in v0.4.0
type DownloadOptions struct {
// BlockSize specifies the block size to use for each parallel download; the default size is BlobDefaultDownloadBlockSize.
BlockSize int64
// Progress is a function that is invoked periodically as bytes are received.
Progress func(bytesTransferred int64)
// BlobAccessConditions indicates the access conditions used when making HTTP GET requests against the blob.
BlobAccessConditions *BlobAccessConditions
// ClientProvidedKeyOptions indicates the client provided key by name and/or by value to encrypt/decrypt data.
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
// Parallelism indicates the maximum number of blocks to download in parallel (0=default)
Parallelism uint16
// RetryReaderOptionsPerBlock is used when downloading each block.
RetryReaderOptionsPerBlock RetryReaderOptions
}
DownloadOptions identifies options used by the DownloadToBuffer and DownloadToFile functions.
type EncryptionAlgorithmType ¶ added in v0.4.0
type EncryptionAlgorithmType string
EncryptionAlgorithmType enum
const ( EncryptionAlgorithmTypeNone EncryptionAlgorithmType = "None" EncryptionAlgorithmTypeAES256 EncryptionAlgorithmType = "AES256" )
func PossibleEncryptionAlgorithmTypeValues ¶ added in v0.4.0
func PossibleEncryptionAlgorithmTypeValues() []EncryptionAlgorithmType
PossibleEncryptionAlgorithmTypeValues returns the possible values for the EncryptionAlgorithmType const type.
func (EncryptionAlgorithmType) ToPtr ¶ added in v0.4.0
func (c EncryptionAlgorithmType) ToPtr() *EncryptionAlgorithmType
ToPtr returns a *EncryptionAlgorithmType pointing to the current value.
type FailedReadNotifier ¶
type FailedReadNotifier func(failureCount int, lastError error, offset int64, count int64, willRetry bool)
FailedReadNotifier is a function type that represents the notification function called when a read fails
type FilterBlobItem ¶
type FilterBlobItem struct {
// REQUIRED
ContainerName *string `xml:"ContainerName"`
// REQUIRED
Name *string `xml:"Name"`
// Blob tags
Tags *BlobTags `xml:"Tags"`
}
FilterBlobItem - Blob info from a Filter Blobs API call
type FilterBlobSegment ¶
type FilterBlobSegment struct {
// REQUIRED
Blobs []*FilterBlobItem `xml:"Blobs>Blob"`
// REQUIRED
ServiceEndpoint *string `xml:"ServiceEndpoint,attr"`
// REQUIRED
Where *string `xml:"Where"`
NextMarker *string `xml:"NextMarker"`
}
FilterBlobSegment - The result of a Filter Blobs API call
func (FilterBlobSegment) MarshalXML ¶
func (f FilterBlobSegment) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type FilterBlobSegment.
type GeoReplication ¶
type GeoReplication struct {
// REQUIRED; A GMT date/time value, to the second. All primary writes preceding this value are guaranteed to be available
// for read operations at the secondary. Primary writes after this point in time may or may
// not be available for reads.
LastSyncTime *time.Time `xml:"LastSyncTime"`
// REQUIRED; The status of the secondary location
Status *BlobGeoReplicationStatus `xml:"Status"`
}
GeoReplication - Geo-Replication information for the Secondary Storage Service
func (GeoReplication) MarshalXML ¶
func (g GeoReplication) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type GeoReplication.
func (*GeoReplication) UnmarshalXML ¶
func (g *GeoReplication) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type GeoReplication.
type HTTPGetter ¶
HTTPGetter is a function type that refers to a method that performs an HTTP GET operation.
type HTTPGetterInfo ¶
type HTTPGetterInfo struct {
// Offset specifies the start offset that should be used when
// creating the HTTP GET request's Range header
Offset int64
// Count specifies the count of bytes that should be used to calculate
// the end offset when creating the HTTP GET request's Range header
Count int64
// ETag specifies the resource's etag that should be used when creating
// the HTTP GET request's If-Match header
ETag string
}
HTTPGetterInfo is passed to an HTTPGetter function passing it parameters that should be used to make an HTTP GET request.
type HttpRange ¶
HttpRange defines a range of bytes within an HTTP resource, starting at offset and ending at offset+count. A zero-value HttpRange indicates the entire resource. An HttpRange which has an offset but na zero value count indicates from the offset to the resource's end.
func NewHttpRange ¶ added in v0.4.0
type IPEndpointStyleInfo ¶
type IPEndpointStyleInfo struct {
AccountName string // "" if not using IP endpoint style
}
IPEndpointStyleInfo is used for IP endpoint style URL when working with Azure storage emulator. Ex: "https://10.132.141.33/accountname/containername"
type IPRange ¶
type IPRange struct {
Start net.IP // Not specified if length = 0
End net.IP // Not specified if length = 0
}
IPRange represents a SAS IP range's start IP and (optionally) end IP.
type InternalError ¶
type InternalError struct {
// contains filtered or unexported fields
}
InternalError is an internal error type that all errors get wrapped in.
func (*InternalError) As ¶
func (e *InternalError) As(target interface{}) bool
As casts target interface into InternalError
func (*InternalError) Error ¶
func (e *InternalError) Error() string
Error checks if InternalError can be cast as StorageError
func (*InternalError) Is ¶
func (e *InternalError) Is(err error) bool
Is casts err into InternalError
type JSONTextConfiguration ¶
type JSONTextConfiguration struct {
// The string used to separate records.
RecordSeparator *string `xml:"RecordSeparator"`
}
JSONTextConfiguration - json text configuration
type KeyInfo ¶
type KeyInfo struct {
// REQUIRED; The date-time the key expires in ISO 8601 UTC time
Expiry *string `xml:"Expiry"`
// REQUIRED; The date-time the key is active in ISO 8601 UTC time
Start *string `xml:"Start"`
}
KeyInfo - Key information
type LeaseAccessConditions ¶
type LeaseAccessConditions struct {
// If specified, the operation only succeeds if the resource's lease is active and matches this ID.
LeaseID *string
}
LeaseAccessConditions contains a group of parameters for the containerClient.GetProperties method.
type LeaseDurationType ¶
type LeaseDurationType string
LeaseDurationType enum
const ( LeaseDurationTypeInfinite LeaseDurationType = "infinite" LeaseDurationTypeFixed LeaseDurationType = "fixed" )
func PossibleLeaseDurationTypeValues ¶
func PossibleLeaseDurationTypeValues() []LeaseDurationType
PossibleLeaseDurationTypeValues returns the possible values for the LeaseDurationType const type.
func (LeaseDurationType) ToPtr ¶
func (c LeaseDurationType) ToPtr() *LeaseDurationType
ToPtr returns a *LeaseDurationType pointing to the current value.
type LeaseStateType ¶
type LeaseStateType string
LeaseStateType enum
const ( LeaseStateTypeAvailable LeaseStateType = "available" LeaseStateTypeLeased LeaseStateType = "leased" LeaseStateTypeExpired LeaseStateType = "expired" LeaseStateTypeBreaking LeaseStateType = "breaking" LeaseStateTypeBroken LeaseStateType = "broken" )
func PossibleLeaseStateTypeValues ¶
func PossibleLeaseStateTypeValues() []LeaseStateType
PossibleLeaseStateTypeValues returns the possible values for the LeaseStateType const type.
func (LeaseStateType) ToPtr ¶
func (c LeaseStateType) ToPtr() *LeaseStateType
ToPtr returns a *LeaseStateType pointing to the current value.
type LeaseStatusType ¶
type LeaseStatusType string
LeaseStatusType enum
const ( LeaseStatusTypeLocked LeaseStatusType = "locked" LeaseStatusTypeUnlocked LeaseStatusType = "unlocked" )
func PossibleLeaseStatusTypeValues ¶
func PossibleLeaseStatusTypeValues() []LeaseStatusType
PossibleLeaseStatusTypeValues returns the possible values for the LeaseStatusType const type.
func (LeaseStatusType) ToPtr ¶
func (c LeaseStatusType) ToPtr() *LeaseStatusType
ToPtr returns a *LeaseStatusType pointing to the current value.
type ListBlobsFlatSegmentResponse ¶
type ListBlobsFlatSegmentResponse struct {
// REQUIRED
ContainerName *string `xml:"ContainerName,attr"`
// REQUIRED
Segment *BlobFlatListSegment `xml:"Blobs"`
// REQUIRED
ServiceEndpoint *string `xml:"ServiceEndpoint,attr"`
Marker *string `xml:"Marker"`
MaxResults *int32 `xml:"MaxResults"`
NextMarker *string `xml:"NextMarker"`
Prefix *string `xml:"Prefix"`
}
ListBlobsFlatSegmentResponse - An enumeration of blobs
type ListBlobsHierarchySegmentResponse ¶
type ListBlobsHierarchySegmentResponse struct {
// REQUIRED
ContainerName *string `xml:"ContainerName,attr"`
// REQUIRED
Segment *BlobHierarchyListSegment `xml:"Blobs"`
// REQUIRED
ServiceEndpoint *string `xml:"ServiceEndpoint,attr"`
Delimiter *string `xml:"Delimiter"`
Marker *string `xml:"Marker"`
MaxResults *int32 `xml:"MaxResults"`
NextMarker *string `xml:"NextMarker"`
Prefix *string `xml:"Prefix"`
}
ListBlobsHierarchySegmentResponse - An enumeration of blobs
type ListBlobsIncludeItem ¶
type ListBlobsIncludeItem string
ListBlobsIncludeItem enum
const ( ListBlobsIncludeItemCopy ListBlobsIncludeItem = "copy" ListBlobsIncludeItemDeleted ListBlobsIncludeItem = "deleted" ListBlobsIncludeItemMetadata ListBlobsIncludeItem = "metadata" ListBlobsIncludeItemSnapshots ListBlobsIncludeItem = "snapshots" ListBlobsIncludeItemUncommittedblobs ListBlobsIncludeItem = "uncommittedblobs" ListBlobsIncludeItemVersions ListBlobsIncludeItem = "versions" ListBlobsIncludeItemTags ListBlobsIncludeItem = "tags" ListBlobsIncludeItemImmutabilitypolicy ListBlobsIncludeItem = "immutabilitypolicy" ListBlobsIncludeItemLegalhold ListBlobsIncludeItem = "legalhold" ListBlobsIncludeItemDeletedwithversions ListBlobsIncludeItem = "deletedwithversions" )
func PossibleListBlobsIncludeItemValues ¶
func PossibleListBlobsIncludeItemValues() []ListBlobsIncludeItem
PossibleListBlobsIncludeItemValues returns the possible values for the ListBlobsIncludeItem const type.
func (ListBlobsIncludeItem) ToPtr ¶
func (c ListBlobsIncludeItem) ToPtr() *ListBlobsIncludeItem
ToPtr returns a *ListBlobsIncludeItem pointing to the current value.
type ListContainersDetail ¶
type ListContainersDetail struct {
// Tells the service whether to return metadata for each container.
Metadata bool
// Tells the service whether to return soft-deleted containers.
Deleted bool
}
ListContainersDetail indicates what additional information the service should return with each container.
type ListContainersIncludeType ¶
type ListContainersIncludeType string
ListContainersIncludeType enum
const ( ListContainersIncludeTypeMetadata ListContainersIncludeType = "metadata" ListContainersIncludeTypeDeleted ListContainersIncludeType = "deleted" ListContainersIncludeTypeSystem ListContainersIncludeType = "system" )
func PossibleListContainersIncludeTypeValues ¶
func PossibleListContainersIncludeTypeValues() []ListContainersIncludeType
PossibleListContainersIncludeTypeValues returns the possible values for the ListContainersIncludeType const type.
func (ListContainersIncludeType) ToPtr ¶
func (c ListContainersIncludeType) ToPtr() *ListContainersIncludeType
ToPtr returns a *ListContainersIncludeType pointing to the current value.
type ListContainersOptions ¶
type ListContainersOptions struct {
Include ListContainersDetail
// A string value that identifies the portion of the list of containers to be returned with the next listing operation. The
// operation returns the NextMarker value within the response body if the listing operation did not return all containers
// remaining to be listed with the current page. The NextMarker value can be used as the value for the marker parameter in
// a subsequent call to request the next page of list items. The marker value is opaque to the client.
Marker *string
// Specifies the maximum number of containers to return. If the request does not specify max results, or specifies a value
// greater than 5000, the server will return up to 5000 items. Note that if the listing operation crosses a partition boundary,
// then the service will return a continuation token for retrieving the remainder of the results. For this reason, it is possible
// that the service will return fewer results than specified by max results, or than the default of 5000.
MaxResults *int32
// Filters the results to return only containers whose name begins with the specified prefix.
Prefix *string
}
ListContainersOptions provides set of configurations for ListContainers operation
type ListContainersSegmentResponse ¶
type ListContainersSegmentResponse struct {
// REQUIRED
ContainerItems []*ContainerItem `xml:"Containers>Container"`
// REQUIRED
ServiceEndpoint *string `xml:"ServiceEndpoint,attr"`
Marker *string `xml:"Marker"`
MaxResults *int32 `xml:"MaxResults"`
NextMarker *string `xml:"NextMarker"`
Prefix *string `xml:"Prefix"`
}
ListContainersSegmentResponse - An enumeration of containers
func (ListContainersSegmentResponse) MarshalXML ¶
func (l ListContainersSegmentResponse) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type ListContainersSegmentResponse.
type Logging ¶
type Logging struct {
// REQUIRED; Indicates whether all delete requests should be logged.
Delete *bool `xml:"Delete"`
// REQUIRED; Indicates whether all read requests should be logged.
Read *bool `xml:"Read"`
// REQUIRED; the retention policy which determines how long the associated data should persist
RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"`
// REQUIRED; The version of Storage Analytics to configure.
Version *string `xml:"Version"`
// REQUIRED; Indicates whether all write requests should be logged.
Write *bool `xml:"Write"`
}
Logging - Azure Analytics Logging settings.
type Metrics ¶
type Metrics struct {
// REQUIRED; Indicates whether metrics are enabled for the Blob service.
Enabled *bool `xml:"Enabled"`
// Indicates whether metrics should generate summary statistics for called API operations.
IncludeAPIs *bool `xml:"IncludeAPIs"`
// the retention policy which determines how long the associated data should persist
RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"`
// The version of Storage Analytics to configure.
Version *string `xml:"Version"`
}
Metrics - a summary of request statistics grouped by API in hour or minute aggregates for blobs
type ModifiedAccessConditions ¶
type ModifiedAccessConditions struct {
// Specify an ETag value to operate only on blobs with a matching value.
IfMatch *string
// Specify this header value to operate only on a blob if it has been modified since the specified date/time.
IfModifiedSince *time.Time
// Specify an ETag value to operate only on blobs without a matching value.
IfNoneMatch *string
// Specify a SQL where clause on blob tags to operate only on blobs with a matching value.
IfTags *string
// Specify this header value to operate only on a blob if it has not been modified since the specified date/time.
IfUnmodifiedSince *time.Time
}
ModifiedAccessConditions contains a group of parameters for the containerClient.Delete method.
type ObjectReplicationPolicy ¶
type ObjectReplicationPolicy struct {
PolicyId *string
Rules *[]ObjectReplicationRules
}
ObjectReplicationPolicy are deserialized attributes
type ObjectReplicationRules ¶
ObjectReplicationRules struct
type PageBlobClearPagesOptions ¶
type PageBlobClearPagesOptions struct {
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
SequenceNumberAccessConditions *SequenceNumberAccessConditions
BlobAccessConditions *BlobAccessConditions
}
PageBlobClearPagesOptions provides set of configurations for PageBlobClient.ClearPages operation
type PageBlobClearPagesResponse ¶
type PageBlobClearPagesResponse struct {
// contains filtered or unexported fields
}
PageBlobClearPagesResponse contains the response from method PageBlobClient.ClearPages
type PageBlobClient ¶
type PageBlobClient struct {
BlobClient
// contains filtered or unexported fields
}
PageBlobClient represents a client to an Azure Storage page blob;
Example ¶
ExamplePageBlobClient shows how to manipulate a page blob with PageBlobClient. A page blob is a collection of 512-byte pages optimized for random read and write operations. The maximum size for a page blob is 8 TB.
package main
import (
"bytes"
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
blobName := "test_page_blob.vhd"
blobURL := fmt.Sprintf("https://%s.blob.core.windows.net/testcontainer/%s", accountName, blobName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
pageBlobClient, err := azblob.NewPageBlobClient(blobURL, cred, nil)
if err != nil {
log.Fatal(err)
}
_, err = pageBlobClient.Create(context.TODO(), azblob.PageBlobPageBytes*4, nil)
if err != nil {
log.Fatal(err)
}
page := make([]byte, azblob.PageBlobPageBytes)
copy(page, "Page 0")
_, err = pageBlobClient.UploadPages(context.TODO(), streaming.NopCloser(bytes.NewReader(page)), nil)
if err != nil {
log.Fatal(err)
}
copy(page, "Page 1")
_, err = pageBlobClient.UploadPages(
context.TODO(),
streaming.NopCloser(bytes.NewReader(page)),
&azblob.PageBlobUploadPagesOptions{PageRange: &azblob.HttpRange{Offset: 0, Count: 2 * azblob.PageBlobPageBytes}},
)
if err != nil {
log.Fatal(err)
}
//getPages, err := pageBlobClient.GetPageRanges(context.TODO(), azblob.HttpRange{Offset: 0, Count: }, nil)
pager := pageBlobClient.GetPageRanges(&azblob.PageBlobGetPageRangesOptions{
PageRange: azblob.NewHttpRange(0, 10*azblob.PageBlobPageBytes),
})
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, pr := range resp.PageList.PageRange {
fmt.Printf("Start=%d, End=%d\n", pr.Start, pr.End)
}
}
if pager.Err() != nil {
log.Fatal(pager.Err())
}
_, err = pageBlobClient.ClearPages(context.TODO(), azblob.HttpRange{Offset: 0, Count: 1 * azblob.PageBlobPageBytes}, nil)
if err != nil {
log.Fatal(err)
}
pager = pageBlobClient.GetPageRanges(&azblob.PageBlobGetPageRangesOptions{
PageRange: azblob.NewHttpRange(0, 10*azblob.PageBlobPageBytes),
})
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, pr := range resp.PageList.PageRange {
fmt.Printf("Start=%d, End=%d\n", pr.Start, pr.End)
}
}
if pager.Err() != nil {
log.Fatal(pager.Err())
}
get, err := pageBlobClient.Download(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
blobData := &bytes.Buffer{}
reader := get.Body(nil)
_, err = blobData.ReadFrom(reader)
if err != nil {
return
}
err = reader.Close()
if err != nil {
return
}
fmt.Println(blobData.String())
}
func NewPageBlobClient ¶
func NewPageBlobClient(blobURL string, cred azcore.TokenCredential, options *ClientOptions) (*PageBlobClient, error)
NewPageBlobClient creates a ServiceClient object using the specified URL, Azure AD credential, and options. Example of serviceURL: https://<your_storage_account>.blob.core.windows.net
func NewPageBlobClientWithNoCredential ¶ added in v0.2.0
func NewPageBlobClientWithNoCredential(blobURL string, options *ClientOptions) (*PageBlobClient, error)
NewPageBlobClientWithNoCredential creates a ServiceClient object using the specified URL and options. Example of serviceURL: https://<your_storage_account>.blob.core.windows.net?<SAS token>
func NewPageBlobClientWithSharedKey ¶ added in v0.2.0
func NewPageBlobClientWithSharedKey(blobURL string, cred *SharedKeyCredential, options *ClientOptions) (*PageBlobClient, error)
NewPageBlobClientWithSharedKey creates a ServiceClient object using the specified URL, shared key, and options. Example of serviceURL: https://<your_storage_account>.blob.core.windows.net
func (*PageBlobClient) ClearPages ¶
func (pb *PageBlobClient) ClearPages(ctx context.Context, pageRange HttpRange, options *PageBlobClearPagesOptions) (PageBlobClearPagesResponse, error)
ClearPages frees the specified pages from the page blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-page.
func (*PageBlobClient) Create ¶
func (pb *PageBlobClient) Create(ctx context.Context, size int64, o *PageBlobCreateOptions) (PageBlobCreateResponse, error)
Create creates a page blob of the specified length. Call PutPage to upload data to a page blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-blob.
func (*PageBlobClient) GetPageRanges ¶
func (pb *PageBlobClient) GetPageRanges(options *PageBlobGetPageRangesOptions) *PageBlobGetPageRangesPager
GetPageRanges returns the list of valid page ranges for a page blob or snapshot of a page blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges.
func (*PageBlobClient) GetPageRangesDiff ¶
func (pb *PageBlobClient) GetPageRangesDiff(options *PageBlobGetPageRangesDiffOptions) *PageBlobGetPageRangesDiffPager
GetPageRangesDiff gets the collection of page ranges that differ between a specified snapshot and this page blob. For more information, see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges.
func (*PageBlobClient) Resize ¶
func (pb *PageBlobClient) Resize(ctx context.Context, size int64, options *PageBlobResizeOptions) (PageBlobResizeResponse, error)
Resize resizes the page blob to the specified size (which must be a multiple of 512). For more information, see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties.
func (*PageBlobClient) StartCopyIncremental ¶
func (pb *PageBlobClient) StartCopyIncremental(ctx context.Context, copySource string, prevSnapshot string, options *PageBlobCopyIncrementalOptions) (PageBlobCopyIncrementalResponse, error)
StartCopyIncremental begins an operation to start an incremental copy from one page blob's snapshot to this page blob. The snapshot is copied such that only the differential changes between the previously copied snapshot are transferred to the destination. The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. For more information, see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob and https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots.
func (*PageBlobClient) UpdateSequenceNumber ¶
func (pb *PageBlobClient) UpdateSequenceNumber(ctx context.Context, options *PageBlobUpdateSequenceNumberOptions) (PageBlobUpdateSequenceNumberResponse, error)
UpdateSequenceNumber sets the page blob's sequence number.
func (*PageBlobClient) UploadPages ¶
func (pb *PageBlobClient) UploadPages(ctx context.Context, body io.ReadSeekCloser, options *PageBlobUploadPagesOptions) (PageBlobUploadPagesResponse, error)
UploadPages writes 1 or more pages to the page blob. The start offset and the stream size must be a multiple of 512 bytes. This method panics if the stream is not at position 0. Note that the http client closes the body stream after the request is sent to the service. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-page.
func (*PageBlobClient) UploadPagesFromURL ¶
func (pb *PageBlobClient) UploadPagesFromURL(ctx context.Context, source string, sourceOffset, destOffset, count int64, options *PageBlobUploadPagesFromURLOptions) (PageBlobUploadPagesFromURLResponse, error)
UploadPagesFromURL copies 1 or more pages from a source URL to the page blob. The sourceOffset specifies the start offset of source data to copy from. The destOffset specifies the start offset of data in page blob will be written to. The count must be a multiple of 512 bytes. For more information, see https://docs.microsoft.com/rest/api/storageservices/put-page-from-url.
func (*PageBlobClient) WithSnapshot ¶
func (pb *PageBlobClient) WithSnapshot(snapshot string) (*PageBlobClient, error)
WithSnapshot creates a new PageBlobURL object identical to the source but with the specified snapshot timestamp. Pass "" to remove the snapshot returning a URL to the base blob.
func (*PageBlobClient) WithVersionID ¶
func (pb *PageBlobClient) WithVersionID(versionID string) (*PageBlobClient, error)
WithVersionID creates a new PageBlobURL object identical to the source but with the specified snapshot timestamp. Pass "" to remove the version returning a URL to the base blob.
type PageBlobCopyIncrementalOptions ¶
type PageBlobCopyIncrementalOptions struct {
ModifiedAccessConditions *ModifiedAccessConditions
}
PageBlobCopyIncrementalOptions provides set of configurations for PageBlobClient.StartCopyIncremental operation
type PageBlobCopyIncrementalResponse ¶
type PageBlobCopyIncrementalResponse struct {
// contains filtered or unexported fields
}
PageBlobCopyIncrementalResponse contains the response from method PageBlobClient.StartCopyIncremental
type PageBlobCreateOptions ¶
type PageBlobCreateOptions struct {
// Set for page blobs only. The sequence number is a user-controlled value that you can use to track requests. The value of
// the sequence number must be between 0 and 2^63 - 1.
BlobSequenceNumber *int64
// Optional. Used to set blob tags in various blob operations.
BlobTagsMap map[string]string
// Optional. Specifies a user-defined name-value pair associated with the blob. If no name-value pairs are specified, the
// operation will copy the metadata from the source blob or file to the destination blob. If one or more name-value pairs
// are specified, the destination blob is created with the specified metadata, and metadata is not copied from the source
// blob or file. Note that beginning with version 2009-09-19, metadata names must adhere to the naming rules for C# identifiers.
// See Naming and Referencing Containers, Blobs, and Metadata for more information.
Metadata map[string]string
// Optional. Indicates the tier to be set on the page blob.
Tier *PremiumPageBlobAccessTier
HTTPHeaders *BlobHTTPHeaders
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
BlobAccessConditions *BlobAccessConditions
// Specifies the date time when the blobs immutability policy is set to expire.
ImmutabilityPolicyExpiry *time.Time
// Specifies the immutability policy mode to set on the blob.
ImmutabilityPolicyMode *BlobImmutabilityPolicyMode
// Specified if a legal hold should be set on the blob.
LegalHold *bool
}
PageBlobCreateOptions provides set of configurations for CreatePageBlob operation
type PageBlobCreateResponse ¶
type PageBlobCreateResponse struct {
// contains filtered or unexported fields
}
PageBlobCreateResponse contains the response from method PageBlobClient.Create.
type PageBlobGetPageRangesDiffOptions ¶
type PageBlobGetPageRangesDiffOptions struct {
// A string value that identifies the portion of the list of containers to be returned with the next listing operation. The
// operation returns the NextMarker value within the response body if the listing
// operation did not return all containers remaining to be listed with the current page. The NextMarker value can be used
// as the value for the marker parameter in a subsequent call to request the next
// page of list items. The marker value is opaque to the client.
Marker *string
// Specifies the maximum number of containers to return. If the request does not specify maxresults, or specifies a value
// greater than 5000, the server will return up to 5000 items. Note that if the
// listing operation crosses a partition boundary, then the service will return a continuation token for retrieving the remainder
// of the results. For this reason, it is possible that the service will
// return fewer results than specified by maxresults, or than the default of 5000.
MaxResults *int32
// Optional. This header is only supported in service versions 2019-04-19 and after and specifies the URL of a previous snapshot
// of the target blob. The response will only contain pages that were changed
// between the target blob and its previous snapshot.
PrevSnapshotURL *string
// Optional in version 2015-07-08 and newer. The prevsnapshot parameter is a DateTime value that specifies that the response
// will contain only pages that were changed between target blob and previous
// snapshot. Changed pages include both updated and cleared pages. The target blob may be a snapshot, as long as the snapshot
// specified by prevsnapshot is the older of the two. Note that incremental
// snapshots are currently supported only for blobs created on or after January 1, 2016.
PrevSnapshot *string
// Optional, you can specify whether a particular range of the blob is read
PageRange *HttpRange
// The snapshot parameter is an opaque DateTime value that, when present, specifies the blob snapshot to retrieve. For more
// information on working with blob snapshots, see Creating a Snapshot of a Blob.
// [https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/creating-a-snapshot-of-a-blob]
Snapshot *string
BlobAccessConditions *BlobAccessConditions
}
PageBlobGetPageRangesDiffOptions provides set of configurations for PageBlobClient.GetPageRangesDiff operation
type PageBlobGetPageRangesDiffPager ¶ added in v0.4.0
type PageBlobGetPageRangesDiffPager struct {
// contains filtered or unexported fields
}
PageBlobGetPageRangesDiffPager provides operations for iterating over paged responses
func (PageBlobGetPageRangesDiffPager) Err ¶ added in v0.4.0
func (p PageBlobGetPageRangesDiffPager) Err() error
Err returns the last error encountered while paging.
func (PageBlobGetPageRangesDiffPager) NextPage ¶ added in v0.4.0
NextPage returns true if the pager advanced to the next page. Returns false if there are no more pages or an error occurred.
func (PageBlobGetPageRangesDiffPager) PageResponse ¶ added in v0.4.0
func (p PageBlobGetPageRangesDiffPager) PageResponse() pageBlobClientGetPageRangesDiffResponse
PageResponse returns the current pageBlobClientGetPageRangesDiffResponse page.
type PageBlobGetPageRangesOptions ¶
type PageBlobGetPageRangesOptions struct {
Marker *string
// Specifies the maximum number of containers to return. If the request does not specify maxresults, or specifies a value
// greater than 5000, the server will return up to 5000 items. Note that if the
// listing operation crosses a partition boundary, then the service will return a continuation token for retrieving the remainder
// of the results. For this reason, it is possible that the service will
// return fewer results than specified by maxresults, or than the default of 5000.
MaxResults *int32
// Optional. This header is only supported in service versions 2019-04-19 and after and specifies the URL of a previous snapshot
// of the target blob. The response will only contain pages that were changed
// between the target blob and its previous snapshot.
PrevSnapshotURL *string
// Optional in version 2015-07-08 and newer. The prevsnapshot parameter is a DateTime value that specifies that the response
// will contain only pages that were changed between target blob and previous
// snapshot. Changed pages include both updated and cleared pages. The target blob may be a snapshot, as long as the snapshot
// specified by prevsnapshot is the older of the two. Note that incremental
// snapshots are currently supported only for blobs created on or after January 1, 2016.
PrevSnapshot *string
// Optional, you can specify whether a particular range of the blob is read
PageRange *HttpRange
// The snapshot parameter is an opaque DateTime value that, when present, specifies the blob snapshot to retrieve. For more
// information on working with blob snapshots, see Creating a Snapshot of a Blob.
// [https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/creating-a-snapshot-of-a-blob]
Snapshot *string
BlobAccessConditions *BlobAccessConditions
}
PageBlobGetPageRangesOptions provides set of configurations for GetPageRanges operation
type PageBlobGetPageRangesPager ¶ added in v0.4.0
type PageBlobGetPageRangesPager struct {
// contains filtered or unexported fields
}
PageBlobGetPageRangesPager provides operations for iterating over paged responses
func (PageBlobGetPageRangesPager) Err ¶ added in v0.4.0
func (p PageBlobGetPageRangesPager) Err() error
Err returns the last error encountered while paging.
func (PageBlobGetPageRangesPager) NextPage ¶ added in v0.4.0
NextPage returns true if the pager advanced to the next page. Returns false if there are no more pages or an error occurred.
func (PageBlobGetPageRangesPager) PageResponse ¶ added in v0.4.0
func (p PageBlobGetPageRangesPager) PageResponse() pageBlobClientGetPageRangesResponse
PageResponse returns the current pageBlobClientGetPageRangesResponse page.
type PageBlobResizeOptions ¶
type PageBlobResizeOptions struct {
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
BlobAccessConditions *BlobAccessConditions
}
PageBlobResizeOptions provides set of configurations for PageBlobClient.Resize operation
type PageBlobResizeResponse ¶
type PageBlobResizeResponse struct {
// contains filtered or unexported fields
}
PageBlobResizeResponse contains the response from method PageBlobClient.Resize
type PageBlobUpdateSequenceNumberOptions ¶
type PageBlobUpdateSequenceNumberOptions struct {
ActionType *SequenceNumberActionType
BlobSequenceNumber *int64
BlobAccessConditions *BlobAccessConditions
}
PageBlobUpdateSequenceNumberOptions provides set of configurations for PageBlobClient.UpdateSequenceNumber operation
type PageBlobUpdateSequenceNumberResponse ¶
type PageBlobUpdateSequenceNumberResponse struct {
// contains filtered or unexported fields
}
PageBlobUpdateSequenceNumberResponse contains the response from method PageBlobClient.UpdateSequenceNumber
type PageBlobUploadPagesFromURLOptions ¶
type PageBlobUploadPagesFromURLOptions struct {
// Only Bearer type is supported. Credentials should be a valid OAuth access token to copy source.
CopySourceAuthorization *string
// Specify the md5 calculated for the range of bytes that must be read from the copy source.
SourceContentMD5 []byte
// Specify the crc64 calculated for the range of bytes that must be read from the copy source.
SourceContentCRC64 []byte
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
SequenceNumberAccessConditions *SequenceNumberAccessConditions
SourceModifiedAccessConditions *SourceModifiedAccessConditions
BlobAccessConditions *BlobAccessConditions
}
PageBlobUploadPagesFromURLOptions provides set of configurations for UploadPagesFromURL operation
type PageBlobUploadPagesFromURLResponse ¶
type PageBlobUploadPagesFromURLResponse struct {
// contains filtered or unexported fields
}
PageBlobUploadPagesFromURLResponse contains the response from method PageBlobClient.UploadPagesFromURL
type PageBlobUploadPagesOptions ¶
type PageBlobUploadPagesOptions struct {
// Specify the transactional crc64 for the body, to be validated by the service.
PageRange *HttpRange
TransactionalContentCRC64 []byte
// Specify the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 []byte
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
SequenceNumberAccessConditions *SequenceNumberAccessConditions
BlobAccessConditions *BlobAccessConditions
}
PageBlobUploadPagesOptions provides set of configurations for UploadPages operation
type PageBlobUploadPagesResponse ¶
type PageBlobUploadPagesResponse struct {
// contains filtered or unexported fields
}
PageBlobUploadPagesResponse contains the response from method PageBlobClient.UploadPages.
type PageList ¶
type PageList struct {
ClearRange []*ClearRange `xml:"ClearRange"`
NextMarker *string `xml:"NextMarker"`
PageRange []*PageRange `xml:"PageRange"`
}
PageList - the list of pages
func (PageList) MarshalXML ¶
MarshalXML implements the xml.Marshaller interface for type PageList.
type PremiumPageBlobAccessTier ¶
type PremiumPageBlobAccessTier string
PremiumPageBlobAccessTier enum
const ( PremiumPageBlobAccessTierP10 PremiumPageBlobAccessTier = "P10" PremiumPageBlobAccessTierP15 PremiumPageBlobAccessTier = "P15" PremiumPageBlobAccessTierP20 PremiumPageBlobAccessTier = "P20" PremiumPageBlobAccessTierP30 PremiumPageBlobAccessTier = "P30" PremiumPageBlobAccessTierP4 PremiumPageBlobAccessTier = "P4" PremiumPageBlobAccessTierP40 PremiumPageBlobAccessTier = "P40" PremiumPageBlobAccessTierP50 PremiumPageBlobAccessTier = "P50" PremiumPageBlobAccessTierP6 PremiumPageBlobAccessTier = "P6" PremiumPageBlobAccessTierP60 PremiumPageBlobAccessTier = "P60" PremiumPageBlobAccessTierP70 PremiumPageBlobAccessTier = "P70" PremiumPageBlobAccessTierP80 PremiumPageBlobAccessTier = "P80" )
func PossiblePremiumPageBlobAccessTierValues ¶
func PossiblePremiumPageBlobAccessTierValues() []PremiumPageBlobAccessTier
PossiblePremiumPageBlobAccessTierValues returns the possible values for the PremiumPageBlobAccessTier const type.
func (PremiumPageBlobAccessTier) ToPtr ¶
func (c PremiumPageBlobAccessTier) ToPtr() *PremiumPageBlobAccessTier
ToPtr returns a *PremiumPageBlobAccessTier pointing to the current value.
type PublicAccessType ¶
type PublicAccessType string
PublicAccessType enum
const ( PublicAccessTypeBlob PublicAccessType = "blob" PublicAccessTypeContainer PublicAccessType = "container" )
func PossiblePublicAccessTypeValues ¶
func PossiblePublicAccessTypeValues() []PublicAccessType
PossiblePublicAccessTypeValues returns the possible values for the PublicAccessType const type.
func (PublicAccessType) ToPtr ¶
func (c PublicAccessType) ToPtr() *PublicAccessType
ToPtr returns a *PublicAccessType pointing to the current value.
type QueryFormat ¶
type QueryFormat struct {
// REQUIRED; The quick query format type.
Type *QueryFormatType `xml:"Type"`
// Groups the settings used for formatting the response if the response should be Arrow formatted.
ArrowConfiguration *ArrowConfiguration `xml:"ArrowConfiguration"`
// Groups the settings used for interpreting the blob data if the blob is delimited text formatted.
DelimitedTextConfiguration *DelimitedTextConfiguration `xml:"DelimitedTextConfiguration"`
// json text configuration
JSONTextConfiguration *JSONTextConfiguration `xml:"JsonTextConfiguration"`
// Anything
ParquetTextConfiguration interface{} `xml:"ParquetTextConfiguration"`
}
QueryFormat struct
type QueryFormatType ¶
type QueryFormatType string
QueryFormatType - The quick query format type.
const ( QueryFormatTypeDelimited QueryFormatType = "delimited" QueryFormatTypeJSON QueryFormatType = "json" QueryFormatTypeArrow QueryFormatType = "arrow" QueryFormatTypeParquet QueryFormatType = "parquet" )
func PossibleQueryFormatTypeValues ¶
func PossibleQueryFormatTypeValues() []QueryFormatType
PossibleQueryFormatTypeValues returns the possible values for the QueryFormatType const type.
func (QueryFormatType) ToPtr ¶
func (c QueryFormatType) ToPtr() *QueryFormatType
ToPtr returns a *QueryFormatType pointing to the current value.
type QueryRequest ¶
type QueryRequest struct {
// REQUIRED; The query expression in SQL. The maximum size of the query expression is 256KiB.
Expression *string `xml:"Expression"`
// REQUIRED; Required. The type of the provided query expression.
QueryType *string `xml:"QueryType"`
InputSerialization *QuerySerialization `xml:"InputSerialization"`
OutputSerialization *QuerySerialization `xml:"OutputSerialization"`
}
QueryRequest - Groups the set of query request settings.
func (QueryRequest) MarshalXML ¶
func (q QueryRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type QueryRequest.
type QuerySerialization ¶
type QuerySerialization struct {
// REQUIRED
Format *QueryFormat `xml:"Format"`
}
QuerySerialization struct
type RehydratePriority ¶
type RehydratePriority string
RehydratePriority - If an object is in rehydrate pending state then this header is returned with priority of rehydrate. Valid values are High and Standard.
const ( RehydratePriorityHigh RehydratePriority = "High" RehydratePriorityStandard RehydratePriority = "Standard" )
func PossibleRehydratePriorityValues ¶
func PossibleRehydratePriorityValues() []RehydratePriority
PossibleRehydratePriorityValues returns the possible values for the RehydratePriority const type.
func (RehydratePriority) ToPtr ¶
func (c RehydratePriority) ToPtr() *RehydratePriority
ToPtr returns a *RehydratePriority pointing to the current value.
type ReleaseLeaseBlobOptions ¶
type ReleaseLeaseBlobOptions struct {
ModifiedAccessConditions *ModifiedAccessConditions
}
ReleaseLeaseBlobOptions provides set of configurations for ReleaseLeaseBlob operation
type ResponseError ¶
type ResponseError interface {
Error() string
Unwrap() error
RawResponse() *http.Response
NonRetriable()
}
ResponseError is a wrapper of error passed from service
type RetentionPolicy ¶
type RetentionPolicy struct {
// REQUIRED; Indicates whether a retention policy is enabled for the storage service
Enabled *bool `xml:"Enabled"`
// Indicates whether permanent delete is allowed on this storage account.
AllowPermanentDelete *bool `xml:"AllowPermanentDelete"`
// Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this
// value will be deleted
Days *int32 `xml:"Days"`
}
RetentionPolicy - the retention policy which determines how long the associated data should persist
type RetryReaderOptions ¶
type RetryReaderOptions struct {
// MaxRetryRequests specifies the maximum number of HTTP GET requests that will be made
// while reading from a RetryReader. A value of zero means that no additional HTTP
// GET requests will be made.
MaxRetryRequests int
// NotifyFailedRead is called, if non-nil, after any failure to read. Expected usage is diagnostic logging.
NotifyFailedRead FailedReadNotifier
// TreatEarlyCloseAsError can be set to true to prevent retries after "read on closed response body". By default,
// retryReader has the following special behaviour: closing the response body before it is all read is treated as a
// retryable error. This is to allow callers to force a retry by closing the body from another goroutine (e.g. if the =
// read is too slow, caller may want to force a retry in the hope that the retry will be quicker). If
// TreatEarlyCloseAsError is true, then retryReader's special behaviour is suppressed, and "read on closed body" is instead
// treated as a fatal (non-retryable) error.
// Note that setting TreatEarlyCloseAsError only guarantees that Closing will produce a fatal error if the Close happens
// from the same "thread" (goroutine) as Read. Concurrent Close calls from other goroutines may instead produce network errors
// which will be retried.
TreatEarlyCloseAsError bool
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
// contains filtered or unexported fields
}
RetryReaderOptions contains properties which can help to decide when to do retry.
type SASProtocol ¶
type SASProtocol string
SASProtocol indicates the http/https.
const ( // SASProtocolHTTPS can be specified for a SAS protocol SASProtocolHTTPS SASProtocol = "https" )
type SASQueryParameters ¶
type SASQueryParameters struct {
// contains filtered or unexported fields
}
SASQueryParameters object represents the components that make up an Azure Storage SAS' query parameters. You parse a map of query parameters into its fields by calling NewSASQueryParameters(). You add the components to a query parameter map by calling AddToValues(). NOTE: Changing any field requires computing a new SAS signature using a XxxSASSignatureValues type. This type defines the components used by all Azure Storage resources (Containers, Blobs, Files, & Queues).
func (*SASQueryParameters) AgentObjectId ¶ added in v0.3.0
func (p *SASQueryParameters) AgentObjectId() string
AgentObjectId returns agentObjectId
func (*SASQueryParameters) CacheControl ¶
func (p *SASQueryParameters) CacheControl() string
CacheControl returns cacheControl
func (*SASQueryParameters) ContentDisposition ¶
func (p *SASQueryParameters) ContentDisposition() string
ContentDisposition returns contentDisposition
func (*SASQueryParameters) ContentEncoding ¶
func (p *SASQueryParameters) ContentEncoding() string
ContentEncoding returns contentEncoding
func (*SASQueryParameters) ContentLanguage ¶
func (p *SASQueryParameters) ContentLanguage() string
ContentLanguage returns contentLanguage
func (*SASQueryParameters) ContentType ¶
func (p *SASQueryParameters) ContentType() string
ContentType returns sontentType
func (*SASQueryParameters) Encode ¶
func (p *SASQueryParameters) Encode() string
Encode encodes the SAS query parameters into URL encoded form sorted by key.
func (*SASQueryParameters) ExpiryTime ¶
func (p *SASQueryParameters) ExpiryTime() time.Time
ExpiryTime returns expiryTime
func (*SASQueryParameters) IPRange ¶
func (p *SASQueryParameters) IPRange() IPRange
IPRange returns ipRange
func (*SASQueryParameters) Identifier ¶
func (p *SASQueryParameters) Identifier() string
Identifier returns identifier
func (*SASQueryParameters) Permissions ¶
func (p *SASQueryParameters) Permissions() string
Permissions returns permissions
func (*SASQueryParameters) PreauthorizedAgentObjectId ¶ added in v0.3.0
func (p *SASQueryParameters) PreauthorizedAgentObjectId() string
PreauthorizedAgentObjectId returns preauthorizedAgentObjectId
func (*SASQueryParameters) Protocol ¶
func (p *SASQueryParameters) Protocol() SASProtocol
Protocol returns protocol
func (*SASQueryParameters) Resource ¶
func (p *SASQueryParameters) Resource() string
Resource returns resource
func (*SASQueryParameters) ResourceTypes ¶
func (p *SASQueryParameters) ResourceTypes() string
ResourceTypes returns resourceTypes
func (*SASQueryParameters) Services ¶
func (p *SASQueryParameters) Services() string
Services returns services
func (*SASQueryParameters) Signature ¶
func (p *SASQueryParameters) Signature() string
Signature returns signature
func (*SASQueryParameters) SignedCorrelationId ¶ added in v0.3.0
func (p *SASQueryParameters) SignedCorrelationId() string
SignedCorrelationId returns signedCorrelationId
func (*SASQueryParameters) SignedDirectoryDepth ¶ added in v0.3.0
func (p *SASQueryParameters) SignedDirectoryDepth() string
SignedDirectoryDepth returns signedDirectoryDepth
func (*SASQueryParameters) SignedExpiry ¶
func (p *SASQueryParameters) SignedExpiry() time.Time
SignedExpiry returns signedExpiry
func (*SASQueryParameters) SignedService ¶
func (p *SASQueryParameters) SignedService() string
SignedService returns signedService
func (*SASQueryParameters) SignedStart ¶
func (p *SASQueryParameters) SignedStart() time.Time
SignedStart returns signedStart
func (*SASQueryParameters) SignedTid ¶
func (p *SASQueryParameters) SignedTid() string
SignedTid returns aignedTid
func (*SASQueryParameters) SignedVersion ¶
func (p *SASQueryParameters) SignedVersion() string
SignedVersion returns signedVersion
func (*SASQueryParameters) SnapshotTime ¶
func (p *SASQueryParameters) SnapshotTime() time.Time
SnapshotTime returns snapshotTime
func (*SASQueryParameters) StartTime ¶
func (p *SASQueryParameters) StartTime() time.Time
StartTime returns startTime
func (*SASQueryParameters) Version ¶
func (p *SASQueryParameters) Version() string
Version returns version
type SKUName ¶
type SKUName string
SKUName enum
func PossibleSKUNameValues ¶
func PossibleSKUNameValues() []SKUName
PossibleSKUNameValues returns the possible values for the SKUName const type.
type SequenceNumberAccessConditions ¶
type SequenceNumberAccessConditions struct {
// Specify this header value to operate only on a blob if it has the specified sequence number.
IfSequenceNumberEqualTo *int64
// Specify this header value to operate only on a blob if it has a sequence number less than the specified.
IfSequenceNumberLessThan *int64
// Specify this header value to operate only on a blob if it has a sequence number less than or equal to the specified.
IfSequenceNumberLessThanOrEqualTo *int64
}
SequenceNumberAccessConditions contains a group of parameters for the pageBlobClient.UploadPages method.
type SequenceNumberActionType ¶
type SequenceNumberActionType string
SequenceNumberActionType enum
const ( SequenceNumberActionTypeMax SequenceNumberActionType = "max" SequenceNumberActionTypeUpdate SequenceNumberActionType = "update" SequenceNumberActionTypeIncrement SequenceNumberActionType = "increment" )
func PossibleSequenceNumberActionTypeValues ¶
func PossibleSequenceNumberActionTypeValues() []SequenceNumberActionType
PossibleSequenceNumberActionTypeValues returns the possible values for the SequenceNumberActionType const type.
func (SequenceNumberActionType) ToPtr ¶
func (c SequenceNumberActionType) ToPtr() *SequenceNumberActionType
ToPtr returns a *SequenceNumberActionType pointing to the current value.
type ServiceClient ¶
type ServiceClient struct {
// contains filtered or unexported fields
}
ServiceClient represents a URL to the Azure Blob Storage service allowing you to manipulate blob containers.
func NewServiceClient ¶
func NewServiceClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*ServiceClient, error)
NewServiceClient creates a ServiceClient object using the specified URL, Azure AD credential, and options. Example of serviceURL: https://<your_storage_account>.blob.core.windows.net
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClient(serviceURL, cred, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(serviceClient)
}
func NewServiceClientFromConnectionString ¶
func NewServiceClientFromConnectionString(connectionString string, options *ClientOptions) (*ServiceClient, error)
NewServiceClientFromConnectionString creates a service client from the given connection string. nolint
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
// Your connection string can be obtained from the Azure Portal.
connectionString, ok := os.LookupEnv("BLOB_STORAGE_CONNECTION_STRING")
if !ok {
log.Fatal("the environment variable 'AZURE_STORAGE_CONNECTION_STRING' could not be found")
}
serviceClient, err := azblob.NewServiceClientFromConnectionString(connectionString, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(serviceClient)
}
func NewServiceClientWithNoCredential ¶ added in v0.2.0
func NewServiceClientWithNoCredential(serviceURL string, options *ClientOptions) (*ServiceClient, error)
NewServiceClientWithNoCredential creates a ServiceClient object using the specified URL and options. Example of serviceURL: https://<your_storage_account>.blob.core.windows.net?<SAS token>
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
sharedAccessSignature, ok := os.LookupEnv("BLOB_STORAGE_SHARED_ACCESS_SIGNATURE")
if !ok {
panic("BLOB_STORAGE_SHARED_ACCESS_SIGNATURE could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sharedAccessSignature)
serviceClient, err := azblob.NewServiceClientWithNoCredential(serviceURL, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(serviceClient)
}
func NewServiceClientWithSharedKey ¶ added in v0.2.0
func NewServiceClientWithSharedKey(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*ServiceClient, error)
NewServiceClientWithSharedKey creates a ServiceClient object using the specified URL, shared key, and options. Example of serviceURL: https://<your_storage_account>.blob.core.windows.net
func (*ServiceClient) CanGetAccountSASToken ¶
func (s *ServiceClient) CanGetAccountSASToken() bool
CanGetAccountSASToken checks if shared key in ServiceClient is nil
func (*ServiceClient) CreateContainer ¶
func (s *ServiceClient) CreateContainer(ctx context.Context, containerName string, options *ContainerCreateOptions) (ContainerCreateResponse, error)
CreateContainer is a lifecycle method to creates a new container under the specified account. If the container with the same name already exists, a ResourceExistsError will be raised. This method returns a client with which to interact with the newly created container.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClient(serviceURL, cred, nil)
if err != nil {
log.Fatal(err)
}
_, err = serviceClient.CreateContainer(context.TODO(), "testcontainer", nil)
if err != nil {
log.Fatal(err)
}
// ======== 2. Delete a container ========
defer func(serviceClient1 *azblob.ServiceClient, ctx context.Context, containerName string, options *azblob.ContainerDeleteOptions) {
_, err = serviceClient1.DeleteContainer(ctx, containerName, options)
if err != nil {
log.Fatal(err)
}
}(serviceClient, context.TODO(), "testcontainer", nil)
}
func (*ServiceClient) DeleteContainer ¶
func (s *ServiceClient) DeleteContainer(ctx context.Context, containerName string, options *ContainerDeleteOptions) (ContainerDeleteResponse, error)
DeleteContainer is a lifecycle method that marks the specified container for deletion. The container and any blobs contained within it are later deleted during garbage collection. If the container is not found, a ResourceNotFoundError will be raised.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClient(serviceURL, cred, nil)
if err != nil {
log.Fatal(err)
}
_, err = serviceClient.DeleteContainer(context.TODO(), "testcontainer", nil)
if err != nil {
log.Fatal(err)
}
}
func (*ServiceClient) FindBlobsByTags ¶
func (s *ServiceClient) FindBlobsByTags(ctx context.Context, o *ServiceFilterBlobsOptions) (ServiceFilterBlobsResponse, error)
FindBlobsByTags operation finds all blobs in the storage account whose tags match a given search expression. Filter blobs searches across all containers within a storage account but can be scoped within the expression to a single container. https://docs.microsoft.com/en-us/rest/api/storageservices/find-blobs-by-tags eg. "dog='germanshepherd' and penguin='emperorpenguin'" To specify a container, eg. "@container=’containerName’ and Name = ‘C’"
func (*ServiceClient) GetAccountInfo ¶
func (s *ServiceClient) GetAccountInfo(ctx context.Context, o *ServiceGetAccountInfoOptions) (ServiceGetAccountInfoResponse, error)
GetAccountInfo provides account level information
func (*ServiceClient) GetProperties ¶
func (s *ServiceClient) GetProperties(ctx context.Context, o *ServiceGetPropertiesOptions) (ServiceGetPropertiesResponse, error)
GetProperties - gets the properties of a storage account's Blob service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClient(serviceURL, cred, nil)
if err != nil {
log.Fatal(err)
}
serviceGetPropertiesResponse, err := serviceClient.GetProperties(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(serviceGetPropertiesResponse)
}
func (*ServiceClient) GetSASURL ¶ added in v0.4.0
func (s *ServiceClient) GetSASURL(resources AccountSASResourceTypes, permissions AccountSASPermissions, start time.Time, expiry time.Time) (string, error)
GetSASURL is a convenience method for generating a SAS token for the currently pointed at account. It can only be used if the credential supplied during creation was a SharedKeyCredential. This validity can be checked with CanGetAccountSASToken().
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
cred, err := azblob.NewSharedKeyCredential("myAccountName", "myAccountKey")
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClientWithSharedKey("https://<myAccountName>.blob.core.windows.net", cred, nil)
if err != nil {
log.Fatal(err)
}
resources := azblob.AccountSASResourceTypes{Service: true}
permission := azblob.AccountSASPermissions{Read: true}
start := time.Now()
expiry := start.AddDate(1, 0, 0)
sasURL, err := serviceClient.GetSASURL(resources, permission, start, expiry)
if err != nil {
log.Fatal(err)
}
serviceURL := fmt.Sprintf("https://<myAccountName>.blob.core.windows.net/?%s", sasURL)
serviceClientWithSAS, err := azblob.NewServiceClientWithNoCredential(serviceURL, nil)
if err != nil {
log.Fatal(err)
}
_ = serviceClientWithSAS
}
func (*ServiceClient) GetStatistics ¶
func (s *ServiceClient) GetStatistics(ctx context.Context, o *ServiceGetStatisticsOptions) (ServiceGetStatisticsResponse, error)
GetStatistics Retrieves statistics related to replication for the Blob service. It is only available when read-access geo-redundant replication is enabled for the storage account. With geo-redundant replication, Azure Storage maintains your data durable in two locations. In both locations, Azure Storage constantly maintains multiple healthy replicas of your data. The location where you read, create, update, or delete data is the primary storage account location. The primary location exists in the region you choose at the time you create an account via the Azure Management Azure classic portal, for example, North Central US. The location to which your data is replicated is the secondary location. The secondary location is automatically determined based on the location of the primary; it is in a second data center that resides in the same region as the primary location. Read-only access is available from the secondary location, if read-access geo-redundant replication is enabled for your storage account.
func (*ServiceClient) ListContainers ¶
func (s *ServiceClient) ListContainers(o *ListContainersOptions) *ServiceListContainersSegmentPager
ListContainers operation returns a pager of the containers under the specified account. Use an empty Marker to start enumeration from the beginning. Container names are returned in lexicographic order. For more information, see https://docs.microsoft.com/rest/api/storageservices/list-containers2.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClient(serviceURL, cred, nil)
if err != nil {
log.Fatal(err)
}
listContainersOptions := azblob.ListContainersOptions{
Include: azblob.ListContainersDetail{
Metadata: true, // Include Metadata
Deleted: true, // Include deleted containers in the result as well
},
}
pager := serviceClient.ListContainers(&listContainersOptions)
for pager.NextPage(context.TODO()) {
resp := pager.PageResponse()
for _, container := range resp.ContainerItems {
fmt.Println(*container.Name)
}
}
if pager.Err() != nil {
log.Fatal(pager.Err())
}
}
func (*ServiceClient) NewContainerClient ¶
func (s *ServiceClient) NewContainerClient(containerName string) (*ContainerClient, error)
NewContainerClient creates a new ContainerClient object by concatenating containerName to the end of ServiceClient's URL. The new ContainerClient uses the same request policy pipeline as the ServiceClient. To change the pipeline, create the ContainerClient and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewContainerClient instead of calling this object's NewContainerClient method.
func (*ServiceClient) SetProperties ¶
func (s *ServiceClient) SetProperties(ctx context.Context, o *ServiceSetPropertiesOptions) (ServiceSetPropertiesResponse, error)
SetProperties Sets the properties of a storage account's Blob service, including Azure Storage Analytics. If an element (e.g. analytics_logging) is left as None, the existing settings on the service for that functionality are preserved.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
accountName, ok := os.LookupEnv("BLOB_STORAGE_ACCOUNT_NAME")
if !ok {
panic("BLOB_STORAGE_ACCOUNT_NAME could not be found")
}
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatal(err)
}
serviceClient, err := azblob.NewServiceClient(serviceURL, cred, nil)
if err != nil {
log.Fatal(err)
}
enabled := true // enabling retention period
days := int32(5) // setting retention period to 5 days
serviceSetPropertiesResponse, err := serviceClient.SetProperties(context.TODO(), &azblob.ServiceSetPropertiesOptions{
DeleteRetentionPolicy: &azblob.RetentionPolicy{Enabled: &enabled, Days: &days},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(serviceSetPropertiesResponse)
}
func (ServiceClient) URL ¶
func (s ServiceClient) URL() string
URL returns the URL endpoint used by the ServiceClient object.
type ServiceFilterBlobsOptions ¶
type ServiceFilterBlobsOptions struct {
// A string value that identifies the portion of the list of containers to be returned with the next listing operation. The operation returns the NextMarker
// value within the response body if the listing operation did not return all containers remaining to be listed with the current page. The NextMarker value
// can be used as the value for the marker parameter in a subsequent call to request the next page of list items. The marker value is opaque to the client.
Marker *string
// Specifies the maximum number of containers to return. If the request does not specify maxresults, or specifies a value greater than 5000, the server
// will return up to 5000 items. Note that if the listing operation crosses a partition boundary, then the service will return a continuation token for
// retrieving the remainder of the results. For this reason, it is possible that the service will return fewer results than specified by maxresults, or
// than the default of 5000.
MaxResults *int32
// Filters the results to return only to return only blobs whose tags match the specified expression.
Where *string
}
ServiceFilterBlobsOptions provides set of configurations for ServiceClient.FindBlobsByTags
type ServiceFilterBlobsResponse ¶
type ServiceFilterBlobsResponse struct {
// contains filtered or unexported fields
}
ServiceFilterBlobsResponse contains the response from ServiceClient.FindBlobsByTags
type ServiceGetAccountInfoOptions ¶
type ServiceGetAccountInfoOptions struct {
}
ServiceGetAccountInfoOptions provides set of options for ServiceClient.GetAccountInfo
type ServiceGetAccountInfoResponse ¶
type ServiceGetAccountInfoResponse struct {
// contains filtered or unexported fields
}
ServiceGetAccountInfoResponse contains the response from ServiceClient.GetAccountInfo
type ServiceGetPropertiesOptions ¶
type ServiceGetPropertiesOptions struct {
}
ServiceGetPropertiesOptions provides set of options for ServiceClient.GetProperties
type ServiceGetPropertiesResponse ¶
type ServiceGetPropertiesResponse struct {
// contains filtered or unexported fields
}
ServiceGetPropertiesResponse contains the response from ServiceClient.GetProperties
type ServiceGetStatisticsOptions ¶
type ServiceGetStatisticsOptions struct {
}
ServiceGetStatisticsOptions provides set of options for ServiceClient.GetStatistics
type ServiceGetStatisticsResponse ¶
type ServiceGetStatisticsResponse struct {
// contains filtered or unexported fields
}
ServiceGetStatisticsResponse contains the response from ServiceClient.GetStatistics.
type ServiceListContainersSegmentPager ¶
type ServiceListContainersSegmentPager struct {
// contains filtered or unexported fields
}
ServiceListContainersSegmentPager provides operations for iterating over paged responses.
func (*ServiceListContainersSegmentPager) Err ¶
func (p *ServiceListContainersSegmentPager) Err() error
Err returns the last error encountered while paging.
func (*ServiceListContainersSegmentPager) NextPage ¶
NextPage returns true if the pager advanced to the next page. Returns false if there are no more pages or an error occurred.
func (*ServiceListContainersSegmentPager) PageResponse ¶
func (p *ServiceListContainersSegmentPager) PageResponse() serviceClientListContainersSegmentResponse
PageResponse returns the current serviceClientListContainersSegmentResponse page.
type ServiceSetPropertiesOptions ¶
type ServiceSetPropertiesOptions struct {
// The set of CORS rules.
Cors []*CorsRule
// The default version to use for requests to the Blob service if an incoming request's version is not specified. Possible
// values include version 2008-10-27 and all more recent versions
DefaultServiceVersion *string
// the retention policy which determines how long the associated data should persist
DeleteRetentionPolicy *RetentionPolicy
// a summary of request statistics grouped by API in hour or minute aggregates for blobs
HourMetrics *Metrics
// Azure Analytics Logging settings.
Logging *Logging
// a summary of request statistics grouped by API in hour or minute aggregates for blobs
MinuteMetrics *Metrics
// The properties that enable an account to host a static website
StaticWebsite *StaticWebsite
}
ServiceSetPropertiesOptions provides set of options for ServiceClient.SetProperties
type ServiceSetPropertiesResponse ¶
type ServiceSetPropertiesResponse struct {
// contains filtered or unexported fields
}
ServiceSetPropertiesResponse contains the response from ServiceClient.SetProperties
type SharedKeyCredential ¶
type SharedKeyCredential struct {
// contains filtered or unexported fields
}
SharedKeyCredential contains an account's name and its primary or secondary key. It is immutable making it shareable and goroutine-safe.
func NewSharedKeyCredential ¶
func NewSharedKeyCredential(accountName string, accountKey string) (*SharedKeyCredential, error)
NewSharedKeyCredential creates an immutable SharedKeyCredential containing the storage account's name and either its primary or secondary key.
func (*SharedKeyCredential) AccountName ¶
func (c *SharedKeyCredential) AccountName() string
AccountName returns the Storage account's name.
func (*SharedKeyCredential) ComputeHMACSHA256 ¶
func (c *SharedKeyCredential) ComputeHMACSHA256(message string) (string, error)
ComputeHMACSHA256 generates a hash signature for an HTTP request or for a SAS.
func (*SharedKeyCredential) SetAccountKey ¶
func (c *SharedKeyCredential) SetAccountKey(accountKey string) error
SetAccountKey replaces the existing account key with the specified account key.
type SignedIdentifier ¶
type SignedIdentifier struct {
// REQUIRED; An Access policy
AccessPolicy *AccessPolicy `xml:"AccessPolicy"`
// REQUIRED; a unique id
ID *string `xml:"Id"`
}
SignedIdentifier - signed identifier
type SourceModifiedAccessConditions ¶
type SourceModifiedAccessConditions struct {
// Specify an ETag value to operate only on blobs with a matching value.
SourceIfMatch *string
// Specify this header value to operate only on a blob if it has been modified since the specified date/time.
SourceIfModifiedSince *time.Time
// Specify an ETag value to operate only on blobs without a matching value.
SourceIfNoneMatch *string
// Specify a SQL where clause on blob tags to operate only on blobs with a matching value.
SourceIfTags *string
// Specify this header value to operate only on a blob if it has not been modified since the specified date/time.
SourceIfUnmodifiedSince *time.Time
}
SourceModifiedAccessConditions contains a group of parameters for the blobClient.StartCopyFromURL method.
type StaticWebsite ¶
type StaticWebsite struct {
// REQUIRED; Indicates whether this account is hosting a static website
Enabled *bool `xml:"Enabled"`
// Absolute path of the default index page
DefaultIndexDocumentPath *string `xml:"DefaultIndexDocumentPath"`
// The absolute path of the custom 404 page
ErrorDocument404Path *string `xml:"ErrorDocument404Path"`
// The default name of the index page under each directory
IndexDocument *string `xml:"IndexDocument"`
}
StaticWebsite - The properties that enable an account to host a static website
type StorageError ¶
type StorageError struct {
ErrorCode StorageErrorCode
// contains filtered or unexported fields
}
StorageError is the internal struct that replaces the generated StorageError. TL;DR: This implements xml.Unmarshaler, and when the original StorageError is substituted, this unmarshaler kicks in. This handles the description and details. defunkifyStorageError handles the response, cause, and service code.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
func main() {
/* This example demonstrates how to handle errors returned from the various Client methods. All these methods return an
object implementing the azcore.Response interface and an object implementing Go's error interface.
The error result is nil if the request was successful; your code can safely use the Response interface object.
If the error is non-nil, the error could be due to:
1. An invalid argument passed to the method. You should not write code to handle these errors;
instead, fix these errors as they appear during development/testing.
2. A network request didn't reach an Azure Storage Service. This usually happens due to a bad URL or
faulty networking infrastructure (like a router issue). In this case, an object implementing the
net.Error interface will be returned. The net.Error interface offers Timeout and Temporary methods
which return true if the network error is determined to be a timeout or temporary condition. If
your pipeline uses the retry policy factory, then this policy looks for Timeout/Temporary and
automatically retries based on the retry options you've configured. Because of the retry policy,
your code will usually not call the Timeout/Temporary methods explicitly other than possibly logging
the network failure.
3. A network request did reach the Azure Storage Service but the service failed to perform the
requested operation. In this case, an object implementing the StorageError interface is returned.
The StorageError interface also implements the net.Error interface and, if you use the retry policy,
you would most likely ignore the Timeout/Temporary methods. However, the StorageError interface exposes
richer information such as a service error code, an error description, details data, and the
service-returned http.Response. And, from the http.Response, you can get the initiating http.Request.
*/
container, err := azblob.NewContainerClientWithNoCredential("https://myaccount.blob.core.windows.net/mycontainer", nil)
if err != nil {
log.Fatal(err)
}
_, err = container.Create(context.TODO(), nil)
if err != nil {
var storageError *azblob.StorageError
if errors.As(err, &storageError) {
fmt.Println(storageError.ErrorCode)
} else {
log.Fatal("Failed to parse err as StorageError")
}
}
}
func (StorageError) Error ¶
func (e StorageError) Error() string
Error implements the error interface's Error method to return a string representation of the error.
func (StorageError) Is ¶
func (e StorageError) Is(err error) bool
Is checks if err can be cast as StorageError
func (StorageError) Response ¶
func (e StorageError) Response() *http.Response
Response returns StorageError.response
func (*StorageError) StatusCode ¶
func (e *StorageError) StatusCode() int
StatusCode returns service-error information. The caller may examine these values but should not modify any of them.
func (*StorageError) Temporary ¶
func (e *StorageError) Temporary() bool
Temporary returns true if the error occurred due to a temporary condition (including an HTTP status of 500 or 503).
func (*StorageError) UnmarshalXML ¶
func (e *StorageError) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error)
UnmarshalXML performs custom unmarshalling of XML-formatted Azure storage request errors. nolint
type StorageErrorCode ¶
type StorageErrorCode string
StorageErrorCode - Error codes returned by the service
const ( StorageErrorCodeAccountAlreadyExists StorageErrorCode = "AccountAlreadyExists" StorageErrorCodeAccountBeingCreated StorageErrorCode = "AccountBeingCreated" StorageErrorCodeAccountIsDisabled StorageErrorCode = "AccountIsDisabled" StorageErrorCodeAppendPositionConditionNotMet StorageErrorCode = "AppendPositionConditionNotMet" StorageErrorCodeAuthenticationFailed StorageErrorCode = "AuthenticationFailed" StorageErrorCodeAuthorizationFailure StorageErrorCode = "AuthorizationFailure" StorageErrorCodeAuthorizationPermissionMismatch StorageErrorCode = "AuthorizationPermissionMismatch" StorageErrorCodeAuthorizationProtocolMismatch StorageErrorCode = "AuthorizationProtocolMismatch" StorageErrorCodeAuthorizationResourceTypeMismatch StorageErrorCode = "AuthorizationResourceTypeMismatch" StorageErrorCodeAuthorizationServiceMismatch StorageErrorCode = "AuthorizationServiceMismatch" StorageErrorCodeAuthorizationSourceIPMismatch StorageErrorCode = "AuthorizationSourceIPMismatch" StorageErrorCodeBlobAlreadyExists StorageErrorCode = "BlobAlreadyExists" StorageErrorCodeBlobArchived StorageErrorCode = "BlobArchived" StorageErrorCodeBlobBeingRehydrated StorageErrorCode = "BlobBeingRehydrated" StorageErrorCodeBlobImmutableDueToPolicy StorageErrorCode = "BlobImmutableDueToPolicy" StorageErrorCodeBlobNotArchived StorageErrorCode = "BlobNotArchived" StorageErrorCodeBlobNotFound StorageErrorCode = "BlobNotFound" StorageErrorCodeBlobOverwritten StorageErrorCode = "BlobOverwritten" StorageErrorCodeBlobTierInadequateForContentLength StorageErrorCode = "BlobTierInadequateForContentLength" StorageErrorCodeBlobUsesCustomerSpecifiedEncryption StorageErrorCode = "BlobUsesCustomerSpecifiedEncryption" StorageErrorCodeBlockCountExceedsLimit StorageErrorCode = "BlockCountExceedsLimit" StorageErrorCodeBlockListTooLong StorageErrorCode = "BlockListTooLong" StorageErrorCodeCannotChangeToLowerTier StorageErrorCode = "CannotChangeToLowerTier" StorageErrorCodeCannotVerifyCopySource StorageErrorCode = "CannotVerifyCopySource" StorageErrorCodeConditionHeadersNotSupported StorageErrorCode = "ConditionHeadersNotSupported" StorageErrorCodeConditionNotMet StorageErrorCode = "ConditionNotMet" StorageErrorCodeContainerAlreadyExists StorageErrorCode = "ContainerAlreadyExists" StorageErrorCodeContainerBeingDeleted StorageErrorCode = "ContainerBeingDeleted" StorageErrorCodeContainerDisabled StorageErrorCode = "ContainerDisabled" StorageErrorCodeContainerNotFound StorageErrorCode = "ContainerNotFound" StorageErrorCodeContentLengthLargerThanTierLimit StorageErrorCode = "ContentLengthLargerThanTierLimit" StorageErrorCodeCopyAcrossAccountsNotSupported StorageErrorCode = "CopyAcrossAccountsNotSupported" StorageErrorCodeCopyIDMismatch StorageErrorCode = "CopyIdMismatch" StorageErrorCodeEmptyMetadataKey StorageErrorCode = "EmptyMetadataKey" StorageErrorCodeFeatureVersionMismatch StorageErrorCode = "FeatureVersionMismatch" StorageErrorCodeIncrementalCopyBlobMismatch StorageErrorCode = "IncrementalCopyBlobMismatch" StorageErrorCodeIncrementalCopyOfEralierVersionSnapshotNotAllowed StorageErrorCode = "IncrementalCopyOfEralierVersionSnapshotNotAllowed" StorageErrorCodeIncrementalCopySourceMustBeSnapshot StorageErrorCode = "IncrementalCopySourceMustBeSnapshot" StorageErrorCodeInfiniteLeaseDurationRequired StorageErrorCode = "InfiniteLeaseDurationRequired" StorageErrorCodeInsufficientAccountPermissions StorageErrorCode = "InsufficientAccountPermissions" StorageErrorCodeInternalError StorageErrorCode = "InternalError" StorageErrorCodeInvalidAuthenticationInfo StorageErrorCode = "InvalidAuthenticationInfo" StorageErrorCodeInvalidBlobOrBlock StorageErrorCode = "InvalidBlobOrBlock" StorageErrorCodeInvalidBlobTier StorageErrorCode = "InvalidBlobTier" StorageErrorCodeInvalidBlobType StorageErrorCode = "InvalidBlobType" StorageErrorCodeInvalidBlockID StorageErrorCode = "InvalidBlockId" StorageErrorCodeInvalidBlockList StorageErrorCode = "InvalidBlockList" StorageErrorCodeInvalidHTTPVerb StorageErrorCode = "InvalidHttpVerb" StorageErrorCodeInvalidHeaderValue StorageErrorCode = "InvalidHeaderValue" StorageErrorCodeInvalidInput StorageErrorCode = "InvalidInput" StorageErrorCodeInvalidMD5 StorageErrorCode = "InvalidMd5" StorageErrorCodeInvalidMetadata StorageErrorCode = "InvalidMetadata" StorageErrorCodeInvalidOperation StorageErrorCode = "InvalidOperation" StorageErrorCodeInvalidPageRange StorageErrorCode = "InvalidPageRange" StorageErrorCodeInvalidQueryParameterValue StorageErrorCode = "InvalidQueryParameterValue" StorageErrorCodeInvalidRange StorageErrorCode = "InvalidRange" StorageErrorCodeInvalidResourceName StorageErrorCode = "InvalidResourceName" StorageErrorCodeInvalidSourceBlobType StorageErrorCode = "InvalidSourceBlobType" StorageErrorCodeInvalidSourceBlobURL StorageErrorCode = "InvalidSourceBlobUrl" StorageErrorCodeInvalidURI StorageErrorCode = "InvalidUri" StorageErrorCodeInvalidVersionForPageBlobOperation StorageErrorCode = "InvalidVersionForPageBlobOperation" StorageErrorCodeInvalidXMLDocument StorageErrorCode = "InvalidXmlDocument" StorageErrorCodeInvalidXMLNodeValue StorageErrorCode = "InvalidXmlNodeValue" StorageErrorCodeLeaseAlreadyBroken StorageErrorCode = "LeaseAlreadyBroken" StorageErrorCodeLeaseAlreadyPresent StorageErrorCode = "LeaseAlreadyPresent" StorageErrorCodeLeaseIDMismatchWithBlobOperation StorageErrorCode = "LeaseIdMismatchWithBlobOperation" StorageErrorCodeLeaseIDMismatchWithContainerOperation StorageErrorCode = "LeaseIdMismatchWithContainerOperation" StorageErrorCodeLeaseIDMismatchWithLeaseOperation StorageErrorCode = "LeaseIdMismatchWithLeaseOperation" StorageErrorCodeLeaseIDMissing StorageErrorCode = "LeaseIdMissing" StorageErrorCodeLeaseIsBreakingAndCannotBeAcquired StorageErrorCode = "LeaseIsBreakingAndCannotBeAcquired" StorageErrorCodeLeaseIsBreakingAndCannotBeChanged StorageErrorCode = "LeaseIsBreakingAndCannotBeChanged" StorageErrorCodeLeaseIsBrokenAndCannotBeRenewed StorageErrorCode = "LeaseIsBrokenAndCannotBeRenewed" StorageErrorCodeLeaseLost StorageErrorCode = "LeaseLost" StorageErrorCodeLeaseNotPresentWithBlobOperation StorageErrorCode = "LeaseNotPresentWithBlobOperation" StorageErrorCodeLeaseNotPresentWithContainerOperation StorageErrorCode = "LeaseNotPresentWithContainerOperation" StorageErrorCodeLeaseNotPresentWithLeaseOperation StorageErrorCode = "LeaseNotPresentWithLeaseOperation" StorageErrorCodeMD5Mismatch StorageErrorCode = "Md5Mismatch" StorageErrorCodeMaxBlobSizeConditionNotMet StorageErrorCode = "MaxBlobSizeConditionNotMet" StorageErrorCodeMetadataTooLarge StorageErrorCode = "MetadataTooLarge" StorageErrorCodeMissingContentLengthHeader StorageErrorCode = "MissingContentLengthHeader" StorageErrorCodeMissingRequiredHeader StorageErrorCode = "MissingRequiredHeader" StorageErrorCodeMissingRequiredQueryParameter StorageErrorCode = "MissingRequiredQueryParameter" StorageErrorCodeMissingRequiredXMLNode StorageErrorCode = "MissingRequiredXmlNode" StorageErrorCodeMultipleConditionHeadersNotSupported StorageErrorCode = "MultipleConditionHeadersNotSupported" StorageErrorCodeNoAuthenticationInformation StorageErrorCode = "NoAuthenticationInformation" StorageErrorCodeNoPendingCopyOperation StorageErrorCode = "NoPendingCopyOperation" StorageErrorCodeOperationNotAllowedOnIncrementalCopyBlob StorageErrorCode = "OperationNotAllowedOnIncrementalCopyBlob" StorageErrorCodeOperationTimedOut StorageErrorCode = "OperationTimedOut" StorageErrorCodeOutOfRangeInput StorageErrorCode = "OutOfRangeInput" StorageErrorCodeOutOfRangeQueryParameterValue StorageErrorCode = "OutOfRangeQueryParameterValue" StorageErrorCodePendingCopyOperation StorageErrorCode = "PendingCopyOperation" StorageErrorCodePreviousSnapshotCannotBeNewer StorageErrorCode = "PreviousSnapshotCannotBeNewer" StorageErrorCodePreviousSnapshotNotFound StorageErrorCode = "PreviousSnapshotNotFound" StorageErrorCodePreviousSnapshotOperationNotSupported StorageErrorCode = "PreviousSnapshotOperationNotSupported" StorageErrorCodeRequestBodyTooLarge StorageErrorCode = "RequestBodyTooLarge" StorageErrorCodeRequestURLFailedToParse StorageErrorCode = "RequestUrlFailedToParse" StorageErrorCodeResourceAlreadyExists StorageErrorCode = "ResourceAlreadyExists" StorageErrorCodeResourceNotFound StorageErrorCode = "ResourceNotFound" StorageErrorCodeResourceTypeMismatch StorageErrorCode = "ResourceTypeMismatch" StorageErrorCodeSequenceNumberConditionNotMet StorageErrorCode = "SequenceNumberConditionNotMet" StorageErrorCodeSequenceNumberIncrementTooLarge StorageErrorCode = "SequenceNumberIncrementTooLarge" StorageErrorCodeServerBusy StorageErrorCode = "ServerBusy" StorageErrorCodeSnapshotCountExceeded StorageErrorCode = "SnapshotCountExceeded" StorageErrorCodeSnapshotOperationRateExceeded StorageErrorCode = "SnapshotOperationRateExceeded" StorageErrorCodeSnapshotsPresent StorageErrorCode = "SnapshotsPresent" StorageErrorCodeSourceConditionNotMet StorageErrorCode = "SourceConditionNotMet" StorageErrorCodeSystemInUse StorageErrorCode = "SystemInUse" StorageErrorCodeTargetConditionNotMet StorageErrorCode = "TargetConditionNotMet" StorageErrorCodeUnsupportedHTTPVerb StorageErrorCode = "UnsupportedHttpVerb" StorageErrorCodeUnsupportedHeader StorageErrorCode = "UnsupportedHeader" StorageErrorCodeUnsupportedQueryParameter StorageErrorCode = "UnsupportedQueryParameter" StorageErrorCodeUnsupportedXMLNode StorageErrorCode = "UnsupportedXmlNode" )
func PossibleStorageErrorCodeValues ¶
func PossibleStorageErrorCodeValues() []StorageErrorCode
PossibleStorageErrorCodeValues returns the possible values for the StorageErrorCode const type.
func (StorageErrorCode) ToPtr ¶
func (c StorageErrorCode) ToPtr() *StorageErrorCode
ToPtr returns a *StorageErrorCode pointing to the current value.
type StorageServiceProperties ¶
type StorageServiceProperties struct {
// The set of CORS rules.
Cors []*CorsRule `xml:"Cors>CorsRule"`
// The default version to use for requests to the Blob service if an incoming request's version is not specified. Possible
// values include version 2008-10-27 and all more recent versions
DefaultServiceVersion *string `xml:"DefaultServiceVersion"`
// the retention policy which determines how long the associated data should persist
DeleteRetentionPolicy *RetentionPolicy `xml:"DeleteRetentionPolicy"`
// a summary of request statistics grouped by API in hour or minute aggregates for blobs
HourMetrics *Metrics `xml:"HourMetrics"`
// Azure Analytics Logging settings.
Logging *Logging `xml:"Logging"`
// a summary of request statistics grouped by API in hour or minute aggregates for blobs
MinuteMetrics *Metrics `xml:"MinuteMetrics"`
// The properties that enable an account to host a static website
StaticWebsite *StaticWebsite `xml:"StaticWebsite"`
}
StorageServiceProperties - Storage Service Properties.
func (StorageServiceProperties) MarshalXML ¶
func (s StorageServiceProperties) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type StorageServiceProperties.
type StorageServiceStats ¶
type StorageServiceStats struct {
// Geo-Replication information for the Secondary Storage Service
GeoReplication *GeoReplication `xml:"GeoReplication"`
}
StorageServiceStats - Stats for the storage service.
type TransferManager ¶
type TransferManager interface {
// Get provides a buffer that will be used to read data into and write out to the stream.
// It is guaranteed by this package to not read or write beyond the size of the slice.
Get() []byte
// Put may or may not put the buffer into underlying storage, depending on settings.
// The buffer must not be touched after this has been called.
Put(b []byte) // nolint
// Run will use a goroutine pool entry to run a function. This blocks until a pool
// goroutine becomes available.
Run(func())
// Close shuts down all internal goroutines. This must be called when the TransferManager
// will no longer be used. Not closing it will cause a goroutine leak.
Close()
}
TransferManager provides a buffer and thread pool manager for certain transfer options. It is undefined behavior if code outside this package call any of these methods.
func NewStaticBuffer ¶
func NewStaticBuffer(size, max int) (TransferManager, error)
NewStaticBuffer creates a TransferManager that will use a channel as a circular buffer that can hold "max" buffers of "size". The goroutine pool is also sized at max. This can be shared between calls if you wish to control maximum memory and concurrency with multiple concurrent calls.
func NewSyncPool ¶
func NewSyncPool(size, concurrency int) (TransferManager, error)
NewSyncPool creates a TransferManager that will use a sync.Pool that can hold a non-capped number of buffers constrained by concurrency. This can be shared between calls if you wish to share memory and concurrency.
type UploadOption ¶ added in v0.4.0
type UploadOption struct {
// BlockSize specifies the block size to use; the default (and maximum size) is BlockBlobMaxStageBlockBytes.
BlockSize int64
// Progress is a function that is invoked periodically as bytes are sent to the BlockBlobClient.
// Note that the progress reporting is not always increasing; it can go down when retrying a request.
Progress func(bytesTransferred int64)
// HTTPHeaders indicates the HTTP headers to be associated with the blob.
HTTPHeaders *BlobHTTPHeaders
// Metadata indicates the metadata to be associated with the blob when PutBlockList is called.
Metadata map[string]string
// BlobAccessConditions indicates the access conditions for the block blob.
BlobAccessConditions *BlobAccessConditions
// AccessTier indicates the tier of blob
AccessTier *AccessTier
// TagsMap
TagsMap map[string]string
// ClientProvidedKeyOptions indicates the client provided key by name and/or by value to encrypt/decrypt data.
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
// Parallelism indicates the maximum number of blocks to upload in parallel (0=default)
Parallelism uint16
// Optional header, Specifies the transactional crc64 for the body, to be validated by the service.
TransactionalContentCRC64 *[]byte
// Specify the transactional md5 for the body, to be validated by the service.
TransactionalContentMD5 *[]byte
}
UploadOption identifies options used by the UploadBuffer and UploadFile functions.
type UploadStreamOptions ¶ added in v0.4.0
type UploadStreamOptions struct {
// TransferManager provides a TransferManager that controls buffer allocation/reuse and
// concurrency. This overrides BufferSize and MaxBuffers if set.
TransferManager TransferManager
// BufferSize sizes the buffer used to read data from source. If < 1 MiB, defaults to 1 MiB.
BufferSize int
// MaxBuffers defines the number of simultaneous uploads will be performed to upload the file.
MaxBuffers int
HTTPHeaders *BlobHTTPHeaders
Metadata map[string]string
BlobAccessConditions *BlobAccessConditions
AccessTier *AccessTier
BlobTagsMap map[string]string
CpkInfo *CpkInfo
CpkScopeInfo *CpkScopeInfo
// contains filtered or unexported fields
}
UploadStreamOptions provides set of configurations for UploadStream operation
type UserDelegationKey ¶
type UserDelegationKey struct {
// REQUIRED; The date-time the key expires
SignedExpiry *time.Time `xml:"SignedExpiry"`
// REQUIRED; The Azure Active Directory object ID in GUID format.
SignedOid *string `xml:"SignedOid"`
// REQUIRED; Abbreviation of the Azure Storage service that accepts the key
SignedService *string `xml:"SignedService"`
// REQUIRED; The date-time the key is active
SignedStart *time.Time `xml:"SignedStart"`
// REQUIRED; The Azure Active Directory tenant ID in GUID format
SignedTid *string `xml:"SignedTid"`
// REQUIRED; The service version that created the key
SignedVersion *string `xml:"SignedVersion"`
// REQUIRED; The key as a base64 string
Value *string `xml:"Value"`
}
UserDelegationKey - A user delegation key
func (UserDelegationKey) MarshalXML ¶
func (u UserDelegationKey) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements the xml.Marshaller interface for type UserDelegationKey.
func (*UserDelegationKey) UnmarshalXML ¶
func (u *UserDelegationKey) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements the xml.Unmarshaller interface for type UserDelegationKey.
Source Files
¶
- bytes_writer.go
- chunkwriting.go
- connection.go
- constants.go
- doc.go
- highlevel.go
- section_writer.go
- transfer_manager.go
- zc_access_policy.go
- zc_append_blob_client.go
- zc_blob_client.go
- zc_blob_lease_client.go
- zc_block_blob_client.go
- zc_connection_string.go
- zc_container_client.go
- zc_container_lease_client.go
- zc_page_blob_client.go
- zc_parsing_urls.go
- zc_response_error.go
- zc_response_helpers.go
- zc_retry_reader.go
- zc_sas_account.go
- zc_sas_query_params.go
- zc_sas_service.go
- zc_service_client.go
- zc_shared_policy_shared_key_credential.go
- zc_storage_error.go
- zc_validators.go
- zm_access_conditions.go
- zm_append_blob_client_util.go
- zm_blob_client_util.go
- zm_blob_lease_client_util.go
- zm_block_blob_client_util.go
- zm_client_util.go
- zm_container_client_util.go
- zm_container_lease_client_util.go
- zm_highlevel_util.go
- zm_page_blob_client_util.go
- zm_serialize_and_desearilize_util.go
- zm_service_client_util.go
- zz_generated_appendblob_client.go
- zz_generated_blob_client.go
- zz_generated_blockblob_client.go
- zz_generated_constants.go
- zz_generated_container_client.go
- zz_generated_models.go
- zz_generated_pageblob_client.go
- zz_generated_pagers.go
- zz_generated_response_types.go
- zz_generated_service_client.go
- zz_generated_time_rfc1123.go
- zz_generated_time_rfc3339.go
- zz_generated_xml_helper.go