简介


前面一篇博客介绍了关于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. STL模板整理 set

    SET set作为一个容器也是用来存储同一数据类型的数据类型,并且能从一个数据集合中取出数据,在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序.应该注意的是set中数元素的值不能直接被 ...

  2. 巧用nth_element求容器前n%大小的那个数

    #include <algorithm> #include <vector> #include <iostream> #include <string> ...

  3. Git命令使用指南

    继续git相关的东西,网上很多讲解的,但是还是喜欢这个图:(爱屋及乌,当然内容也很好,文章链接:http://me.iblogc.com/2015/01/16/Git命令使用指南/) Git是软件开发 ...

  4. CodeVS 1226 倒水问题【DFS/BFS】

    题目描述 Description 有两个无刻度标志的水壶,分别可装 x 升和 y 升 ( x,y 为整数且均不大于 100 )的水.设另有一水 缸,可用来向水壶灌水或接从水壶中倒出的水, 两水壶间,水 ...

  5. 15、Flask实战第15天:Flask-WTF

    WTForms表单验证基本使用 Flask-WTF是简化了WTForms操作的一个第三方库.WTForm表单的两个主要功能是验证用户提交数据的合法性以及渲染模板.当然还包括一些其他的功能:CSRF保护 ...

  6. FFT&NTT&多项式相关

    打了FFT 感觉以后多项式不虚了 ~滑稽~ PS 关于详见没写完.... code #include<cmath> #include<cstdio> #include<c ...

  7. 【动态规划】Gym - 101147H - Commandos

    裸dp,看代码. #include<cstdio> #include<algorithm> #include<cstring> using namespace st ...

  8. 编译boost到各个系统平台 mac,iOS,linux,android,wind

    编译boost到各个系统平台 mac,iOS,linux,android,wind git地址:https://github.com/czjone/boost git仓库:https://github ...

  9. 关于char类型的说明

    #include<iostream> using namespace std; int main() {  char ch=128;//VC编译器默认是有符号的.但c并未明确给出.由编译器 ...

  10. 收藏起来,史上最全的 MySQL 高性能优化实战总结!

    转自:https://mp.weixin.qq.com/s/sRsJzFO9dPtKhovJNWN3Dg 一.前言 MySQL 对于很多 Linux 从业者而言,是一个非常棘手的问题,多数情况都是因为 ...