简介


前面一篇博客介绍了关于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

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

  1. Connect China Azure Storage Blob By Container Token In Python SDK

    简介: 基于Python SDK,使用Container Token操作container对象.关于Token的生成可以使用Storage SDK创建,也可以使用工具快速创建供测试. 示例代码: fr ...

  2. 关于Azure Storage Blob Content-Disposition 使用学习

    概述 在常规的HTTP应答中,Content-Disposition 消息头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地.通俗的解释就是对 ...

  3. 【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)

    问题描述 在使用Azure存储服务,为了有效的保护Storage的Access Keys.可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可 ...

  4. Azure系列2.1 —— com.microsoft.azure.storage.blob

    网上azure的资料较少,尤其是API,全是英文的,中文资料更是少之又少.这次由于公司项目需要使用Azure,所以对Azure的一些学习心得做下笔记,文中不正确地方请大家指正. Azure Blob ...

  5. Azure Storage Blob文件重命名

    Azure Storage的SDK并没有提供文件重命名的方法,而且从StorageExplorer管理工具里操作修改文件名的时候也有明确提示: 是通过复制当前文件并命名为新文件名再删除旧文件,不保存快 ...

  6. Azure Storage Blob文件名区分大小写

    最近在使用Azure Storage的时候发现Storage的命名是区分大小写的,导致我们系统在更新图片的时候有时候更新不上,最终通过判断处理文件名解决. 因此我们在使用Storage需要注意一下文件 ...

  7. 如何获取Azure Storage Blob的MD5值

    问题表述 直接使用CloudBlockBlob对象获取的Properties是空的,无法获取到对象的MD5值,后台并未进行属性值的填充 前提:blob属性本省包含md5值,某些方式上传的blob默认并 ...

  8. Azure Storage Blob 属性设置

    概述 在使用SDK做Blob对象属性的获取或设置时,如果只是直接使用get或set方法,是无法成功获取或设置blob对象的属性.主要是因为在获取对象时,对象的属性默认并未被填充到对象,这就需要执行额外 ...

  9. 【Azure Developer】使用 Python SDK连接Azure Storage Account, 计算Blob大小代码示例

    问题描述 在微软云环境中,使用python SDK连接存储账号(Storage Account)需要计算Blob大小?虽然Azure提供了一个专用工具Azure Storage Explorer可以统 ...

随机推荐

  1. 洛谷 P3383 【模板】线性筛素数-线性筛素数(欧拉筛素数)O(n)基础题贴个板子备忘

    P3383 [模板]线性筛素数 题目描述 如题,给定一个范围N,你需要处理M个某数字是否为质数的询问(每个数字均在范围1-N内) 输入输出格式 输入格式: 第一行包含两个正整数N.M,分别表示查询的范 ...

  2. 18、Flask实战第18天:Flask-session

    session的基本概念 session和cookie的作用有点类似,都是为了存储用户相关的信息.不同的是,cookie是存储在本地浏览器,session是一个思路.一个概念.一个服务器存储授权信息的 ...

  3. oracle tablespace usage status

    select a.tablespace_name, a.bytes / 1024 / 1024 "Sum MB", (a.bytes - b.bytes) / 1024 / 102 ...

  4. java中的3大特性之继承

    继承的特点:继承父类的属性和方法.单继承(多层继承)c++里的继承是多继承 特性 :方法的复写(重写) java中的继承和OC中一样. 比如:人可以养狗; 人---->狗 :整体和部分(拥有)关 ...

  5. [BZOJ 4060] Word Equations

    Link: BZOJ 4060 传送门 Solution: 可以发现字符串间的关系可以构成一棵树 于是我们先用字符串哈希建树,再树形$dp$即可 设$dp[i][j]$为第$i$个节点从$P$字符串的 ...

  6. CodeForces - 981D Bookshelves

    Discription Mr Keks is a typical white-collar in Byteland. He has a bookshelf in his office with som ...

  7. ZOJ 3949 Edge to the Root(树形DP)

    [题目链接] http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3949 [题目大意] 给出一棵根为1的树,每条边边长为1,请你 ...

  8. react-native热更新从零到成功中的各种坑

    https://github.com/reactnativecn/react-native-pushy/blob/master/docs/guide.md Android NDK暂时没有安装 在你的项 ...

  9. [CF321C]Ciel the Commander

    题目大意: 给你一棵n个结点的树,给每个结点分级,最高为'A',最低为'Z'. 尝试构造一种分级方案,使得任意两个相同级别的结点路径上至少有一个更高级的结点. 思路: 贪心+树上点分. 递归处理每一棵 ...

  10. Java多线程——ReentrantLock源码阅读

    上一章<AQS源码阅读>讲了AQS框架,这次讲讲它的应用类(注意不是子类实现,待会细讲). ReentrantLock,顾名思义重入锁,但什么是重入,这个锁到底是怎样的,我们来看看类的注解 ...