简介


前面一篇博客介绍了关于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. java 连接带 kerberos 验证的 phoenix

    唉,网上的资料比较少,找了好久,压根不知道如入告诉 phoenix 客户端来使用 kerberos 啊.. 然后就想到了,这东西开源的应该有相关的单元测试吧..啊哈哈哈哈哈哈,果然 https://g ...

  2. django static文件的引入方式(转)

    1. 在django project中创建 static文件夹 2.settings.py中配置要在 STATIC_URL = '/static/'  下边 STATICFILES_DIRS = [ ...

  3. HDU 1308 What Day Is It?(模拟,日期)

    解题报告:输入一个年月日,让你求出那一天是星期几,但是做这题之前必须先了解一点历史.首先在1582年之前,判断是否是闰年的标准是只要能被四整除就是闰年, 然后在1752年9月2号的后的11天被抹去了, ...

  4. Codeforces 702C Cellular Network(二分)

    题目链接:http://codeforces.com/problemset/problem/702/C 题意: 在数轴上有N个城市和M个信号塔,给你这N个城市以及M个塔在数轴上的位置,求M个塔可以覆盖 ...

  5. luogu P1325 雷达安装

    题目描述 描述: 假设海岸线是一条无限延伸的直线.它的一侧是陆地,另一侧是海洋.每一座小岛是在海面上的一个点.雷达必须安装在陆地上(包括海岸线),并且每个雷达都有相同的扫描范围d.你的任务是建立尽量少 ...

  6. [BZOJ 4117] Weather Report

    Link: BZOJ 4117 传送门 Solution: 第一次写$Huffman Tree$相关,发现就是个合并果子? 此题可以将每一种情况的概率和排列总数算出,接下来就是按照$Haffman T ...

  7. Dom4jDemo应用-保存手机信息

    ---恢复内容开始--- import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStr ...

  8. PythonGUI编程--向列表框添加滚动条

    代码如下: from tkinter import * window = Tk() window.title("New England") yscroll = Scrollbar( ...

  9. oracle数据库维护常用操作

    查看用户相关信息 查看数据库里面所有用户,前提是你是有dba权限的帐号,如sys,system select * from dba_users; 查看你能管理的所有用户! select * from ...

  10. Tomcat部署时war和war exploded的区别

    转自徐刘根的Tomcat部署时war和war exploded区别以及平时踩得坑 一.war和war exploded的区别 在使用IDEA开发项目的时候,部署Tomcat的时候通常会出现下边的情况: ...