Azure Storage Blob Go SDK示例

简介


前面一篇博客介绍了关于Azure ManagerAPI Go SDK的使用,本篇继续介绍使用Blob Go SDK 操作中国区Azure Blob。

SDK下载:

go get github.com/Azure/azure-storage-blob-go/2016-05-31/azblob

示例程序:

package main

import (
    "bufio"
    "bytes"
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "math/rand"
    "net/url"
    "os"
    "strconv"
    "time"

    "github.com/Azure/azure-storage-blob-go/2016-05-31/azblob"
)

func randomString() string {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    return strconv.Itoa(r.Int())
}

func handleErrors(err error) {
    if err != nil {
        if serr, ok := err.(azblob.StorageError); ok { // This error is a Service-specific
            switch serr.ServiceCode() { // Compare serviceCode to ServiceCodeXxx constants
            case azblob.ServiceCodeContainerAlreadyExists:
                fmt.Println("Received 409. Container already exists")
                return
            }
        }
        log.Fatal(err)
    }
}

func main() {
    fmt.Printf("Azure Blob storage quick start sample\n")

    var accountName string = "<storage account name>"
    var accountKey string = "<storage account key>"
    if len(accountName) == 0 || len(accountKey) == 0 {
        log.Fatal("Either the AZURE_STORAGE_ACCOUNT or AZURE_STORAGE_ACCESS_KEY environment variable is not set")
    }

    // Create a default request pipeline using your storage account name and account key.
    credential := azblob.NewSharedKeyCredential(accountName, accountKey)
    p := azblob.NewPipeline(credential, azblob.PipelineOptions{})

    // Create a random string for the quick start container
    containerName := fmt.Sprintf("quickstart-%s", randomString())

    // From the Azure portal, get your storage account blob service URL endpoint.
    URL, _ := url.Parse(
        fmt.Sprintf("https://%s.blob.core.chinacloudapi.cn/%s", accountName, containerName))

    // Create a ContainerURL object that wraps the container URL and a request
    // pipeline to make requests.
    containerURL := azblob.NewContainerURL(*URL, p)

    // Create the container
    fmt.Printf("Creating a container named %s\n", containerName)
    ctx := context.Background() // This example uses a never-expiring context
    _, err := containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
    handleErrors(err)

    // Create a file to test the upload and download.
    fmt.Printf("Creating a dummy file to test the upload and download\n")
    data := []byte("hello world\nthis is a blob\n")
    fileName := randomString()
    err = ioutil.WriteFile(fileName, data, 0700)
    handleErrors(err)

    // Here‘s how to upload a blob.
    blobURL := containerURL.NewBlockBlobURL(fileName)
    file, err := os.Open(fileName)
    handleErrors(err)

    // You can use the low-level PutBlob API to upload files. Low-level APIs are simple wrappers for the Azure Storage REST APIs.
    // Note that PutBlob can upload up to 256MB data in one shot. Details: https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
    // Following is commented out intentionally because we will instead use UploadFileToBlockBlob API to upload the blob
    // _, err = blobURL.PutBlob(ctx, file, azblob.BlobHTTPHeaders{}, azblob.Metadata{}, azblob.BlobAccessConditions{})
    // handleErrors(err)

    // The high-level API UploadFileToBlockBlob function uploads blocks in parallel for optimal performance, and can handle large files as well.
    // This function calls PutBlock/PutBlockList for files larger 256 MBs, and calls PutBlob for any file smaller
    fmt.Printf("Uploading the file with blob name: %s\n", fileName)
    _, err = azblob.UploadFileToBlockBlob(ctx, file, blobURL, azblob.UploadToBlockBlobOptions{
        BlockSize:   4 * 1024 * 1024,
        Parallelism: 16})
    handleErrors(err)

    // List the blobs in the container
    for marker := (azblob.Marker{}); marker.NotDone(); {
        // Get a result segment starting with the blob indicated by the current Marker.
        listBlob, err := containerURL.ListBlobs(ctx, marker, azblob.ListBlobsOptions{})
        handleErrors(err)

        // ListBlobs returns the start of the next segment; you MUST use this to get
        // the next segment (after processing the current result segment).
        marker = listBlob.NextMarker

        // Process the blobs returned in this result segment (if the segment is empty, the loop body won‘t execute)
        for _, blobInfo := range listBlob.Blobs.Blob {
            fmt.Print("Blob name: " + blobInfo.Name + "\n")
        }
    }

    // Here‘s how to download the blob. NOTE: This method automatically retries if the connection fails
    // during download (the low-level GetBlob function does NOT retry errors when reading from its stream).
    stream := azblob.NewDownloadStream(ctx, blobURL.GetBlob, azblob.DownloadStreamOptions{})
    downloadedData := &bytes.Buffer{}
    _, err = downloadedData.ReadFrom(stream)
    handleErrors(err)

    // The downloaded blob data is in downloadData‘s buffer. :Let‘s print it
    fmt.Printf("Downloaded the blob: " + downloadedData.String())

    // Cleaning up the quick start by deleting the container and the file created locally
    fmt.Printf("Press enter key to delete the sample files, example container, and exit the application.\n")
    bufio.NewReader(os.Stdin).ReadBytes(‘\n‘)
    fmt.Printf("Cleaning up.\n")
    containerURL.Delete(ctx, azblob.ContainerAccessConditions{})
    file.Close()
    os.Remove(fileName)
}

测试结果:

Azure Blob storage quick start sample
Creating a container named quickstart-6677502160360014613
Creating a dummy file to test the upload and download
Uploading the file with blob name: 186632235901289029
Blob name: 186632235901289029
Downloaded the blob: hello world
this is a blob
Press enter key to delete the sample files, example container, and exit the application.

Cleaning up.

参考链接:

storage-blobs-go-quickstart

原文地址:https://www.cnblogs.com/taro/p/9057980.html

时间: 2024-08-07 12:26:11

Azure Storage Blob Go SDK示例的相关文章

Azure Storage Blob文件名区分大小写

最近在使用Azure Storage的时候发现Storage的命名是区分大小写的,导致我们系统在更新图片的时候有时候更新不上,最终通过判断处理文件名解决. 因此我们在使用Storage需要注意一下文件的命名规则: 下面是Azure Storage 命名规则的官方具体说明文档: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Naming-and-Referencing-Containers--Blobs

Azure CLI下载Azure Storage Container内的所有文件

在某些场景下,客户需要把Azure Storage的某一个container内的内容都下载到本地.当然采用PowerShell可以定时的进行下载的动作,但有时客户的环境是Linux或MacOS,这时需要采用Azure xplate CLI实现这个功能.本文将介绍如何采用Azure CLI实现这个功能. 安装Azure CLI,可以参考: http://www.cnblogs.com/hengwei/p/5183493.html http://www.cnblogs.com/hengwei/p/4

Azure Storage用法:使用Blob Storage

Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在C# 消息队列-Microsoft Azure service bus 服务总线中介绍了 Queue Storage 的基本用法,本文将介绍 Blob Storage 的主要使用方法. Blob Storage可以看做是云端的文件系统.与桌面操作系统上不同,我们是通过REST API来进行对文件的操作.有关REST API的详细信息,请参见Blo

Windows Azure Storage (19) 再谈Azure Block Blob和Page Blob

<Windows Azure Platform 系列文章目录> 请读者在参考本文之前,预习相关背景知识:Windows Azure Storage (1) Windows Azure Storage Service存储服务 最近被一些客户问到,什么场景下需要用到Azure Block Blob和Azure Page Blob?这里我简单总结一下. 一.Azure Block Blob (1)Azure Block Blob概念类似网盘,可以直接存放图片.文件.照片等二进制文件,并且可以直接被客

[转]探索 Windows Azure Storage

本文转自:https://msdn.microsoft.com/zh-tw/jj573842 概觀 儲存服務 (Storage services) 在 Windows Azure 運算模擬器中提供了可永續保存並強固的儲存能力,並且包含了 blob,table 與 queue 等服務.另外,使用 Windows Azure Drives,您執行於雲端的 Windows Azure 應用程式將會使用 NTFS APIs 存取植基於 blob storage 的穩固磁碟機.在本手作實驗中,您將會在本地

浅谈Azure Storage的安全性

在今天的博文中我们将讨论Azure Storage的安全性以及如何使用共享访问签名(SAS)和存储的访问策略来控制对容器和Blob的访问.SAS基本上是带有查询参数的URI,该查询参数指定诸如到期时间,权限和签名等选项.我将在本文后面详细介绍这些内容.请注意,共享访问签名也可以与表和队列一起使用,但是我将仅在Blob存储方面进行讨论 什么是共享访问签名(SAS)共享访问签名(SAS)是URI,它允许使用者在指定时间范围具有访问存储资源(例如blob或容器)所允许的权限.时间跨度和权限可以从存储的

备份SQL Server数据库到Azure Storage

对于生产数据来讲,数据的安全性是至关重要的,任何数据的丢失都可能产生严重的的后果.而备份作为数据的副本,可以在当数据库出现故障或者遭到破坏时可以根据备份的数据库及事务日志文件还原到最近的时间点将损失降到最低点.对于传统的备份来讲,一般都是使用数据库自带的备份或使用第三方的备份软件将数据库备份到本地的磁盘/磁带存储,这种备份方式的前提是需要有一个大的存储池用来按照备份文件的生命周期来存储我们的备份文件.这就意味着我们需要准备一个大的存储池.考虑到准备存储池需要一定得资源,那么很多小伙伴肯定就会问了

Azure IoT Hub 十分钟入门系列 (4)- 实现从设备上传日志文件/图片到 Azure Storage

本文主要分享一个案例: 10分钟内通过Device SDK上传文件到IoTHub B站视频:https://www.bilibili.com/video/av90224073/ 本文主要有如下内容: 1. 了解IoT Hub中文件存储在了哪里 2. 使用Node.js Device SDK 上传TXT文件 3. 在Storage中查看IOT设备上传的文件 图文内容: 本案例参考:https://docs.azure.cn/zh-cn/iot-hub/iot-hub-node-node-file-

细说 Azure Storage 的冗余策略

当我们想要把应用搬到云端的时候,首先要关注的便是数据的安全性.当然所有的云服务厂商都会对用户数据承诺一个非常高的安全性,但万一出现意外呢?我们是不是还要有适当的应对方案?比如今年的3月8日晚间,Azure 某个区域中的存储几乎全部不能访问,持续达两个多小时.当时最担心的是:用户的数据万一丢掉怎么办?同时,我们是不是可以根据云服务提供的数据服务的特点来优化程序的性能呢?基于如此种种的原因,我们需要了解云端数据服务的一些特性的详情,这将对我们很有帮助.本文将和大家一起探讨 Azure Storage