service

package
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 18, 2024 License: MIT Imports: 21 Imported by: 65

Documentation

Overview

Example (Service_BatchDelete)

ExampleServiceBatchDelete shows blob batch operations for delete and set tier.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	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_ACCOUNT_KEY")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}

	// create shared key credential
	cred, err := azblob.NewSharedKeyCredential(accountName, accountKey)
	handleError(err)

	// create service batch client
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
	svcBatchClient, err := service.NewClientWithSharedKeyCredential(serviceURL, cred, nil)
	handleError(err)

	// create new batch builder
	bb, err := svcBatchClient.NewBatchBuilder()
	handleError(err)

	// add operations to the batch builder
	err = bb.Delete("cnt1", "testBlob0", nil)
	handleError(err)

	err = bb.Delete("cnt1", "testBlob1", &service.BatchDeleteOptions{
		VersionID: to.Ptr("2023-01-03T11:57:25.4067017Z"), // version id for deletion
	})
	handleError(err)

	err = bb.Delete("cnt2", "testBlob2", &service.BatchDeleteOptions{
		Snapshot: to.Ptr("2023-01-03T11:57:25.6515618Z"), // snapshot for deletion
	})
	handleError(err)

	err = bb.Delete("cnt2", "testBlob3", &service.BatchDeleteOptions{
		DeleteOptions: blob.DeleteOptions{
			DeleteSnapshots: to.Ptr(blob.DeleteSnapshotsOptionTypeOnly),
			BlobDeleteType:  to.Ptr(blob.DeleteTypeNone),
		},
	})
	handleError(err)

	resp, err := svcBatchClient.SubmitBatch(context.TODO(), bb, nil)
	handleError(err)

	// get response for individual sub-requests
	for _, resp := range resp.Responses {
		if resp.ContainerName != nil && resp.BlobName != nil {
			fmt.Println("Container: " + *resp.ContainerName)
			fmt.Println("Blob: " + *resp.BlobName)
		}
		if resp.Error == nil {
			fmt.Println("Successful sub-request")
		} else {
			fmt.Println("Error: " + resp.Error.Error())
		}
	}
}
Output:

Example (Service_BatchSetTier)

ExampleServiceBatchSetTier shows blob batch operations for delete and set tier.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	tenantID, ok := os.LookupEnv("AZURE_STORAGE_TENANT_ID")
	if !ok {
		panic("AZURE_STORAGE_TENANT_ID could not be found")
	}
	clientID, ok := os.LookupEnv("AZURE_STORAGE_CLIENT_ID")
	if !ok {
		panic("AZURE_STORAGE_CLIENT_ID could not be found")
	}
	clientSecret, ok := os.LookupEnv("AZURE_STORAGE_CLIENT_SECRET")
	if !ok {
		panic("AZURE_STORAGE_CLIENT_SECRET could not be found")
	}

	// create client secret credential
	cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, clientSecret, nil)
	handleError(err)

	// create service batch client
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
	svcBatchClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	// create new batch builder
	bb, err := svcBatchClient.NewBatchBuilder()
	handleError(err)

	// add operations to the batch builder
	err = bb.SetTier("cnt1", "testBlob4", blob.AccessTierHot, nil)
	handleError(err)

	err = bb.SetTier("cnt1", "testBlob5", blob.AccessTierCool, &service.BatchSetTierOptions{
		VersionID: to.Ptr("2023-01-03T11:57:25.4067017Z"),
	})
	handleError(err)

	err = bb.SetTier("cnt2", "testBlob5", blob.AccessTierCool, &service.BatchSetTierOptions{
		Snapshot: to.Ptr("2023-01-03T11:57:25.6515618Z"),
	})
	handleError(err)

	err = bb.SetTier("cnt2", "testBlob4", blob.AccessTierCool, &service.BatchSetTierOptions{
		SetTierOptions: blob.SetTierOptions{
			RehydratePriority: to.Ptr(blob.RehydratePriorityStandard),
		},
	})
	handleError(err)

	resp, err := svcBatchClient.SubmitBatch(context.TODO(), bb, nil)
	handleError(err)

	// get response for individual sub-requests
	for _, resp := range resp.Responses {
		if resp.ContainerName != nil && resp.BlobName != nil {
			fmt.Println("Container: " + *resp.ContainerName)
			fmt.Println("Blob: " + *resp.BlobName)
		}
		if resp.Error == nil {
			fmt.Println("Successful sub-request")
		} else {
			fmt.Println("Error: " + resp.Error.Error())
		}
	}
}
Output:

Example (Service_Client_CreateContainer)
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/container"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)

	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	_, err = serviceClient.CreateContainer(context.TODO(), "testcontainer", nil)
	handleError(err)

	// ======== 2. Delete a container ========
	defer func(serviceClient1 *service.Client, ctx context.Context, containerName string, options *container.DeleteOptions) {
		_, err = serviceClient1.DeleteContainer(ctx, containerName, options)
		if err != nil {
			log.Fatal(err)
		}
	}(serviceClient, context.TODO(), "testcontainer", nil)
}
Output:

Example (Service_Client_DeleteContainer)
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/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)
	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	_, err = serviceClient.DeleteContainer(context.TODO(), "testcontainer", nil)
	handleError(err)
}
Output:

Example (Service_Client_GetProperties)
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/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)

	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	serviceGetPropertiesResponse, err := serviceClient.GetProperties(context.TODO(), nil)
	handleError(err)

	fmt.Println(serviceGetPropertiesResponse)
}
Output:

Example (Service_Client_GetSASURL)
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	cred, err := azblob.NewSharedKeyCredential("myAccountName", "myAccountKey")
	handleError(err)
	serviceClient, err := service.NewClientWithSharedKeyCredential("https://<myAccountName>.blob.core.windows.net", cred, nil)
	handleError(err)

	resources := sas.AccountResourceTypes{Service: true}
	permission := sas.AccountPermissions{Read: true}
	start := time.Now()
	expiry := start.AddDate(1, 0, 0)
	options := service.GetSASURLOptions{StartTime: &start}
	sasURL, err := serviceClient.GetSASURL(resources, permission, expiry, &options)
	handleError(err)

	serviceURL := fmt.Sprintf("https://<myAccountName>.blob.core.windows.net/?%s", sasURL)
	serviceClientWithSAS, err := service.NewClientWithNoCredential(serviceURL, nil)
	handleError(err)
	_ = serviceClientWithSAS
}
Output:

Example (Service_Client_ListContainers)
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/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)
	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	listContainersOptions := service.ListContainersOptions{
		Include: service.ListContainersInclude{
			Metadata: true, // Include Metadata
			Deleted:  true, // Include deleted containers in the result as well
		},
	}
	pager := serviceClient.NewListContainersPager(&listContainersOptions)

	for pager.More() {
		resp, err := pager.NextPage(context.TODO())
		if err != nil {
			log.Fatal(err)
		}
		for _, container := range resp.ContainerItems {
			fmt.Println(*container.Name)
		}
	}
}
Output:

Example (Service_Client_NewClient)
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/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)
	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)
	fmt.Println(serviceClient.URL())
}
Output:

Example (Service_Client_NewClientFromConnectionString)
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	// Your connection string can be obtained from the Azure Portal.
	connectionString, ok := os.LookupEnv("AZURE_STORAGE_CONNECTION_STRING")
	if !ok {
		log.Fatal("the environment variable 'AZURE_STORAGE_CONNECTION_STRING' could not be found")
	}

	serviceClient, err := service.NewClientFromConnectionString(connectionString, nil)
	handleError(err)
	fmt.Println(serviceClient.URL())
}
Output:

Example (Service_Client_NewClientWithNoCredential)
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	sharedAccessSignature, ok := os.LookupEnv("AZURE_STORAGE_SHARED_ACCESS_SIGNATURE")
	if !ok {
		panic("AZURE_STORAGE_SHARED_ACCESS_SIGNATURE could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sharedAccessSignature)

	serviceClient, err := service.NewClientWithNoCredential(serviceURL, nil)
	handleError(err)
	fmt.Println(serviceClient.URL())
}
Output:

Example (Service_Client_NewClientWithSharedKeyCredential)
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	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_ACCOUNT_KEY")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := service.NewSharedKeyCredential(accountName, accountKey)
	handleError(err)
	serviceClient, err := service.NewClientWithSharedKeyCredential(serviceURL, cred, nil)
	handleError(err)
	fmt.Println(serviceClient.URL())
}
Output:

Example (Service_Client_NewClientWithUserDelegationCredential)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	const containerName = "testContainer"

	// Create Managed Identity (OAuth) Credentials using Client ID
	clientOptions := azcore.ClientOptions{} // Fill clientOptions as needed
	optsClientID := azidentity.ManagedIdentityCredentialOptions{ClientOptions: clientOptions, ID: azidentity.ClientID("7cf7db0d-...")}
	cred, err := azidentity.NewManagedIdentityCredential(&optsClientID)
	handleError(err)
	clientOptionsService := service.ClientOptions{} // Same as azcore.ClientOptions using service instead

	svcClient, err := service.NewClient(fmt.Sprintf("https://%s.blob.core.windows.net/", accountName), cred, &clientOptionsService)
	handleError(err)

	// Set current and past time and create key
	currentTime := time.Now().UTC().Add(-10 * time.Second)
	pastTime := currentTime.Add(48 * time.Hour)
	info := service.KeyInfo{
		Start:  to.Ptr(currentTime.UTC().Format(sas.TimeFormat)),
		Expiry: to.Ptr(pastTime.UTC().Format(sas.TimeFormat)),
	}

	udc, err := svcClient.GetUserDelegationCredential(context.Background(), info, nil)
	handleError(err)

	fmt.Println("User Delegation Key has been created for ", accountName)

	// Create Blob Signature Values with desired permissions and sign with user delegation credential
	sasQueryParams, err := sas.BlobSignatureValues{
		Protocol:      sas.ProtocolHTTPS,
		StartTime:     time.Now().UTC().Add(time.Second * -10),
		ExpiryTime:    time.Now().UTC().Add(15 * time.Minute),
		Permissions:   to.Ptr(sas.ContainerPermissions{Read: true, List: true}).String(),
		ContainerName: containerName,
	}.SignWithUserDelegation(udc)
	handleError(err)

	sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sasQueryParams.Encode())

	// This URL can be used to authenticate requests now
	serviceClient, err := service.NewClientWithNoCredential(sasURL, nil)
	handleError(err)

	// You can also break a blob URL up into it's constituent parts
	blobURLParts, _ := blob.ParseURL(serviceClient.URL())
	fmt.Printf("SAS expiry time = %s\n", blobURLParts.SAS.ExpiryTime())

	// Create Managed Identity (OAuth) Credentials using Resource ID
	optsResourceID := azidentity.ManagedIdentityCredentialOptions{ClientOptions: clientOptions, ID: azidentity.ResourceID("/subscriptions/...")}
	cred, err = azidentity.NewManagedIdentityCredential(&optsResourceID)
	handleError(err)

	svcClient, err = service.NewClient(fmt.Sprintf("https://%s.blob.core.windows.net/", accountName), cred, &clientOptionsService)
	handleError(err)

	udc, err = svcClient.GetUserDelegationCredential(context.Background(), info, nil)
	handleError(err)
	fmt.Println("User Delegation Key has been created for ", accountName)

	// Create Blob Signature Values with desired permissions and sign with user delegation credential
	sasQueryParams, err = sas.BlobSignatureValues{
		Protocol:      sas.ProtocolHTTPS,
		StartTime:     time.Now().UTC().Add(time.Second * -10),
		ExpiryTime:    time.Now().UTC().Add(15 * time.Minute),
		Permissions:   to.Ptr(sas.ContainerPermissions{Read: true, List: true}).String(),
		ContainerName: containerName,
	}.SignWithUserDelegation(udc)
	handleError(err)

	sasURL = fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sasQueryParams.Encode())

	// This URL can be used to authenticate requests now
	serviceClient, err = service.NewClientWithNoCredential(sasURL, nil)
	handleError(err)

	// You can also break a blob URL up into it's constituent parts
	blobURLParts, _ = blob.ParseURL(serviceClient.URL())
	fmt.Printf("SAS expiry time = %s\n", blobURLParts.SAS.ExpiryTime())
}
Output:

Example (Service_Client_RestoreContainer)
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/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)
	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	listOptions := service.ListContainersOptions{
		Include: service.ListContainersInclude{
			Metadata: true, // Include Metadata
			Deleted:  true, // Include deleted containers in the result as well
		},
	}
	pager := serviceClient.NewListContainersPager(&listOptions)

	for pager.More() {
		resp, err := pager.NextPage(context.TODO())
		if err != nil {
			log.Fatal(err)
		}
		for _, cont := range resp.ContainerItems {
			if *cont.Deleted {
				_, err = serviceClient.RestoreContainer(context.TODO(), *cont.Name, *cont.Version, nil)
				handleError(err)
			}
		}
	}
}
Output:

Example (Service_Client_SetProperties)
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/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("AZURE_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	handleError(err)
	serviceClient, err := service.NewClient(serviceURL, cred, nil)
	handleError(err)

	enabled := true  // enabling retention period
	days := int32(5) // setting retention period to 5 days
	serviceSetPropertiesResponse, err := serviceClient.SetProperties(context.TODO(), &service.SetPropertiesOptions{
		DeleteRetentionPolicy: &service.RetentionPolicy{Enabled: &enabled, Days: &days},
	})

	handleError(err)
	fmt.Println(serviceSetPropertiesResponse)
}
Output:

Example (Service_SASSignatureValues_Sign)

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/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
)

func handleError(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func main() {
	accountName, accountKey := os.Getenv("AZURE_STORAGE_ACCOUNT_NAME"), os.Getenv("AZURE_STORAGE_ACCOUNT_KEY")

	credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
	handleError(err)

	sasQueryParams, err := sas.AccountSignatureValues{
		Protocol:      sas.ProtocolHTTPS,
		ExpiryTime:    time.Now().UTC().Add(48 * time.Hour),
		Permissions:   to.Ptr(sas.AccountPermissions{Read: true, List: true}).String(),
		ResourceTypes: to.Ptr(sas.AccountResourceTypes{Container: true, Object: true}).String(),
	}.SignWithSharedKey(credential)
	handleError(err)

	sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", accountName, sasQueryParams.Encode())

	// This URL can be used to authenticate requests now
	serviceClient, err := service.NewClientWithNoCredential(sasURL, nil)
	handleError(err)

	// You can also break a blob URL up into it's constituent parts
	blobURLParts, _ := blob.ParseURL(serviceClient.URL())
	fmt.Printf("SAS expiry time = %s\n", blobURLParts.SAS.ExpiryTime())
}
Output:

Index

Examples

Constants

View Source
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"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessConditions

type AccessConditions = exported.ContainerAccessConditions

AccessConditions identifies container-specific access conditions which you optionally set.

type AccountKind

type AccountKind = generated.AccountKind

AccountKind defines values for AccountKind

const (
	AccountKindStorage          AccountKind = generated.AccountKindStorage
	AccountKindBlobStorage      AccountKind = generated.AccountKindBlobStorage
	AccountKindStorageV2        AccountKind = generated.AccountKindStorageV2
	AccountKindFileStorage      AccountKind = generated.AccountKindFileStorage
	AccountKindBlockBlobStorage AccountKind = generated.AccountKindBlockBlobStorage
)

func PossibleAccountKindValues

func PossibleAccountKindValues() []AccountKind

PossibleAccountKindValues returns the possible values for the AccountKind const type.

type BatchBuilder added in v1.1.0

type BatchBuilder struct {
	// contains filtered or unexported fields
}

BatchBuilder is used for creating the batch operations list. It contains the list of either delete or set tier sub-requests. NOTE: All sub-requests in the batch must be of the same type, either delete or set tier.

func (*BatchBuilder) Delete added in v1.1.0

func (bb *BatchBuilder) Delete(containerName string, blobName string, options *BatchDeleteOptions) error

Delete operation is used to add delete sub-request to the batch builder.

func (*BatchBuilder) SetTier added in v1.1.0

func (bb *BatchBuilder) SetTier(containerName string, blobName string, accessTier blob.AccessTier, options *BatchSetTierOptions) error

SetTier operation is used to add set tier sub-request to the batch builder.

type BatchDeleteOptions added in v1.1.0

type BatchDeleteOptions struct {
	blob.DeleteOptions
	VersionID *string
	Snapshot  *string
}

BatchDeleteOptions contains the optional parameters for the BatchBuilder.Delete method.

type BatchResponseItem added in v1.1.0

type BatchResponseItem = exported.BatchResponseItem

BatchResponseItem contains the response for the individual sub-requests.

type BatchSetTierOptions added in v1.1.0

type BatchSetTierOptions struct {
	blob.SetTierOptions
	VersionID *string
	Snapshot  *string
}

BatchSetTierOptions contains the optional parameters for the BatchBuilder.SetTier method.

type BlobGeoReplicationStatus

type BlobGeoReplicationStatus = generated.BlobGeoReplicationStatus

BlobGeoReplicationStatus - The status of the secondary location

func PossibleBlobGeoReplicationStatusValues

func PossibleBlobGeoReplicationStatusValues() []BlobGeoReplicationStatus

PossibleBlobGeoReplicationStatusValues returns the possible values for the BlobGeoReplicationStatus const type.

type BlobTag added in v0.6.0

type BlobTag = generated.BlobTag

BlobTag - a key/value pair on a blob

type BlobTags added in v1.0.0

type BlobTags = generated.BlobTags

BlobTags - Blob tags

type CORSRule added in v1.0.0

type CORSRule = generated.CORSRule

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 added in v1.0.0

type CPKInfo = generated.CPKInfo

CPKInfo contains a group of parameters for the BlobClient.Download method.

type CPKScopeInfo added in v1.0.0

type CPKScopeInfo = generated.CPKScopeInfo

CPKScopeInfo contains a group of parameters for the BlobClient.SetMetadata method.

type Client

Client represents a URL to the Azure Blob Storage service allowing you to manipulate blob containers.

func NewClient

func NewClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error)

NewClient creates an instance of Client with the specified values.

  • serviceURL - the URL of the storage account e.g. https://<account>.blob.core.windows.net/
  • cred - an Azure AD credential, typically obtained via the azidentity module
  • options - client options; pass nil to accept the default values

func NewClientFromConnectionString

func NewClientFromConnectionString(connectionString string, options *ClientOptions) (*Client, error)

NewClientFromConnectionString creates an instance of Client with the specified values.

  • connectionString - a connection string for the desired storage account
  • options - client options; pass nil to accept the default values

func NewClientWithNoCredential

func NewClientWithNoCredential(serviceURL string, options *ClientOptions) (*Client, error)

NewClientWithNoCredential creates an instance of Client with the specified values. This is used to anonymously access a storage account or with a shared access signature (SAS) token.

  • serviceURL - the URL of the storage account e.g. https://<account>.blob.core.windows.net/?<sas token>
  • options - client options; pass nil to accept the default values

func NewClientWithSharedKeyCredential

func NewClientWithSharedKeyCredential(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*Client, error)

NewClientWithSharedKeyCredential creates an instance of Client with the specified values.

  • serviceURL - the URL of the storage account e.g. https://<account>.blob.core.windows.net/
  • cred - a SharedKeyCredential created with the matching storage account and access key
  • options - client options; pass nil to accept the default values

func (*Client) CreateContainer

func (s *Client) CreateContainer(ctx context.Context, containerName string, options *CreateContainerOptions) (CreateContainerResponse, 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.

func (*Client) DeleteContainer

func (s *Client) DeleteContainer(ctx context.Context, containerName string, options *DeleteContainerOptions) (DeleteContainerResponse, 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.

func (*Client) FilterBlobs

func (s *Client) FilterBlobs(ctx context.Context, where string, o *FilterBlobsOptions) (FilterBlobsResponse, error)

FilterBlobs 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 (*Client) GetAccountInfo

GetAccountInfo provides account level information For more information, see https://learn.microsoft.com/en-us/rest/api/storageservices/get-account-information?tabs=shared-access-signatures.

func (*Client) GetProperties

GetProperties - gets the properties of a storage account's Blob service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.

func (*Client) GetSASURL

func (s *Client) GetSASURL(resources sas.AccountResourceTypes, permissions sas.AccountPermissions, expiry time.Time, o *GetSASURLOptions) (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.

func (*Client) GetStatistics

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 (*Client) GetUserDelegationCredential

func (s *Client) GetUserDelegationCredential(ctx context.Context, info KeyInfo, o *GetUserDelegationCredentialOptions) (*UserDelegationCredential, error)

GetUserDelegationCredential obtains a UserDelegationKey object using the base ServiceURL object. OAuth is required for this call, as well as any role that can delegate access to the storage account.

func (*Client) NewBatchBuilder added in v1.1.0

func (s *Client) NewBatchBuilder() (*BatchBuilder, error)

NewBatchBuilder creates an instance of BatchBuilder using the same auth policy as the client. BatchBuilder is used to build the batch consisting of either delete or set tier sub-requests. All sub-requests in the batch must be of the same type, either delete or set tier. NOTE: Service level Blob Batch operation is supported only when the Client was created using SharedKeyCredential and Account SAS.

func (*Client) NewContainerClient

func (s *Client) NewContainerClient(containerName string) *container.Client

NewContainerClient creates a new container.Client object by concatenating containerName to the end of this Client's URL. The new container.Client uses the same request policy pipeline as the Client.

func (*Client) NewListContainersPager

func (s *Client) NewListContainersPager(o *ListContainersOptions) *runtime.Pager[ListContainersResponse]

NewListContainersPager 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.

func (*Client) RestoreContainer

func (s *Client) RestoreContainer(ctx context.Context, deletedContainerName string, deletedContainerVersion string, options *RestoreContainerOptions) (RestoreContainerResponse, error)

RestoreContainer restores soft-deleted container Operation will only be successful if used within the specified number of days set in the delete retention policy

func (*Client) SetProperties

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.

func (*Client) SubmitBatch added in v1.1.0

func (s *Client) SubmitBatch(ctx context.Context, bb *BatchBuilder, options *SubmitBatchOptions) (SubmitBatchResponse, error)

SubmitBatch operation allows multiple API calls to be embedded into a single HTTP request. It builds the request body using the BatchBuilder object passed. BatchBuilder contains the list of operations to be submitted. It supports up to 256 sub-requests in a single batch. For more information, see https://docs.microsoft.com/rest/api/storageservices/blob-batch.

func (*Client) URL

func (s *Client) URL() string

URL returns the URL endpoint used by the Client object.

type ClientOptions

type ClientOptions base.ClientOptions

ClientOptions contains the optional parameters when creating a Client.

type ContainerItem added in v0.6.0

type ContainerItem = generated.ContainerItem

ContainerItem - An Azure Storage container returned from method Client.ListContainersSegment.

type ContainerProperties added in v0.6.0

type ContainerProperties = generated.ContainerProperties

ContainerProperties - Properties of a container

type CreateContainerOptions

type CreateContainerOptions = container.CreateOptions

CreateContainerOptions contains the optional parameters for the container.Client.Create method.

type CreateContainerResponse

type CreateContainerResponse = generated.ContainerClientCreateResponse

CreateContainerResponse contains the response from method container.Client.Create.

type DeleteContainerOptions

type DeleteContainerOptions = container.DeleteOptions

DeleteContainerOptions contains the optional parameters for the container.Client.Delete method.

type DeleteContainerResponse

type DeleteContainerResponse = generated.ContainerClientDeleteResponse

DeleteContainerResponse contains the response from method container.Client.Delete

type FilterBlobItem added in v0.6.0

type FilterBlobItem = generated.FilterBlobItem

FilterBlobItem - Blob info returned from method Client.FilterBlobs.

type FilterBlobSegment added in v1.0.0

type FilterBlobSegment = generated.FilterBlobSegment

FilterBlobSegment - The result of a Filter Blobs API call.

type FilterBlobsOptions

type FilterBlobsOptions 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
}

FilterBlobsOptions provides set of options for Client.FindBlobsByTags.

type FilterBlobsResponse

type FilterBlobsResponse = generated.ServiceClientFilterBlobsResponse

FilterBlobsResponse contains the response from method Client.FilterBlobs.

type GeoReplication added in v0.6.0

type GeoReplication = generated.GeoReplication

GeoReplication - Geo-Replication information for the Secondary Storage Service.

type GetAccountInfoOptions

type GetAccountInfoOptions struct {
}

GetAccountInfoOptions provides set of options for Client.GetAccountInfo

type GetAccountInfoResponse

type GetAccountInfoResponse = generated.ServiceClientGetAccountInfoResponse

GetAccountInfoResponse contains the response from method Client.GetAccountInfo.

type GetPropertiesOptions

type GetPropertiesOptions struct {
}

GetPropertiesOptions contains the optional parameters for the Client.GetProperties method.

type GetPropertiesResponse

type GetPropertiesResponse = generated.ServiceClientGetPropertiesResponse

GetPropertiesResponse contains the response from method Client.GetProperties.

type GetSASURLOptions added in v1.0.0

type GetSASURLOptions struct {
	StartTime *time.Time
}

GetSASURLOptions contains the optional parameters for the Client.GetSASURL method.

type GetStatisticsOptions

type GetStatisticsOptions struct {
}

GetStatisticsOptions provides set of options for Client.GetStatistics

type GetStatisticsResponse

type GetStatisticsResponse = generated.ServiceClientGetStatisticsResponse

GetStatisticsResponse contains the response from method Client.GetStatistics.

type GetUserDelegationCredentialOptions

type GetUserDelegationCredentialOptions struct {
}

GetUserDelegationCredentialOptions contains optional parameters for Service.GetUserDelegationKey method.

type GetUserDelegationKeyResponse

type GetUserDelegationKeyResponse = generated.ServiceClientGetUserDelegationKeyResponse

GetUserDelegationKeyResponse contains the response from method ServiceClient.GetUserDelegationKey.

type KeyInfo

type KeyInfo = generated.KeyInfo

KeyInfo contains KeyInfo struct.

type ListContainersInclude

type ListContainersInclude struct {
	// Tells the service whether to return metadata for each container.
	Metadata bool

	// Tells the service whether to return soft-deleted containers.
	Deleted bool

	// Tells the service whether to return system containers.
	System bool
}

ListContainersInclude indicates what additional information the service should return with each container.

type ListContainersIncludeType

type ListContainersIncludeType = generated.ListContainersIncludeType

ListContainersIncludeType defines values for ListContainersIncludeType

func PossibleListContainersIncludeTypeValues

func PossibleListContainersIncludeTypeValues() []ListContainersIncludeType

PossibleListContainersIncludeTypeValues returns the possible values for the ListContainersIncludeType const type.

type ListContainersOptions

type ListContainersOptions struct {
	Include ListContainersInclude

	// 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 ListContainersResponse

ListContainersResponse contains the response from method Client.ListContainersSegment.

type ListContainersSegmentResponse added in v1.0.0

type ListContainersSegmentResponse = generated.ListContainersSegmentResponse

ListContainersSegmentResponse - An enumeration of containers

type Logging

type Logging = generated.Logging

Logging - Azure Analytics Logging settings.

type Metrics

type Metrics = generated.Metrics

Metrics - a summary of request statistics grouped by API in hour or minute aggregates for blobs.

type PublicAccessType

type PublicAccessType = generated.PublicAccessType

PublicAccessType defines values for AccessType - private (default) or blob or container

const (
	PublicAccessTypeBlob      PublicAccessType = generated.PublicAccessTypeBlob
	PublicAccessTypeContainer PublicAccessType = generated.PublicAccessTypeContainer
)

func PossiblePublicAccessTypeValues

func PossiblePublicAccessTypeValues() []PublicAccessType

PossiblePublicAccessTypeValues returns the possible values for the PublicAccessType const type.

type RestoreContainerOptions

type RestoreContainerOptions = container.RestoreOptions

RestoreContainerOptions contains the optional parameters for the container.Client.Restore method.

type RestoreContainerResponse

type RestoreContainerResponse = generated.ContainerClientRestoreResponse

RestoreContainerResponse contains the response from method container.Client.Restore

type RetentionPolicy

type RetentionPolicy = generated.RetentionPolicy

RetentionPolicy - the retention policy which determines how long the associated data should persist.

type SKUName

type SKUName = generated.SKUName

SKUName defines values for SkuName - LRS, GRS, RAGRS, ZRS, Premium LRS

const (
	SKUNameStandardLRS   SKUName = generated.SKUNameStandardLRS
	SKUNameStandardGRS   SKUName = generated.SKUNameStandardGRS
	SKUNameStandardRAGRS SKUName = generated.SKUNameStandardRAGRS
	SKUNameStandardZRS   SKUName = generated.SKUNameStandardZRS
	SKUNamePremiumLRS    SKUName = generated.SKUNamePremiumLRS
)

func PossibleSKUNameValues

func PossibleSKUNameValues() []SKUName

PossibleSKUNameValues returns the possible values for the SKUName const type.

type SetPropertiesOptions

type SetPropertiesOptions 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
	// If version is not set - we default to "1.0"
	HourMetrics *Metrics

	// Azure Analytics Logging settings.
	// If version is not set - we default to "1.0"
	Logging *Logging

	// a summary of request statistics grouped by API in hour or minute aggregates for blobs
	// If version is not set - we default to "1.0"
	MinuteMetrics *Metrics

	// The properties that enable an account to host a static website.
	StaticWebsite *StaticWebsite
}

SetPropertiesOptions provides set of options for Client.SetProperties

type SetPropertiesResponse

type SetPropertiesResponse = generated.ServiceClientSetPropertiesResponse

SetPropertiesResponse contains the response from method Client.SetProperties.

type SharedKeyCredential

type SharedKeyCredential = exported.SharedKeyCredential

SharedKeyCredential contains an account's name and its primary or secondary key.

func NewSharedKeyCredential

func NewSharedKeyCredential(accountName, accountKey string) (*SharedKeyCredential, error)

NewSharedKeyCredential creates an immutable SharedKeyCredential containing the storage account's name and either its primary or secondary key.

type StaticWebsite

type StaticWebsite = generated.StaticWebsite

StaticWebsite - The properties that enable an account to host a static website.

type StorageServiceProperties

type StorageServiceProperties = generated.StorageServiceProperties

StorageServiceProperties - Storage Service Properties.

type StorageServiceStats

type StorageServiceStats = generated.StorageServiceStats

StorageServiceStats - Stats for the storage service.

type SubmitBatchOptions added in v1.1.0

type SubmitBatchOptions struct {
}

SubmitBatchOptions contains the optional parameters for the Client.SubmitBatch method.

type SubmitBatchResponse added in v1.1.0

type SubmitBatchResponse struct {
	// Responses contains the responses of the sub-requests in the batch
	Responses []*BatchResponseItem

	// ContentType contains the information returned from the Content-Type header response.
	ContentType *string

	// RequestID contains the information returned from the x-ms-request-id header response.
	RequestID *string

	// Version contains the information returned from the x-ms-version header response.
	Version *string
}

SubmitBatchResponse contains the response from method Client.SubmitBatch.

type UserDelegationCredential

type UserDelegationCredential = exported.UserDelegationCredential

UserDelegationCredential contains an account's name and its user delegation key.

type UserDelegationKey

type UserDelegationKey = generated.UserDelegationKey

UserDelegationKey contains UserDelegationKey.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL