概要 †azure-sdk-for-go では Azureサービスを管理、使用する為のGoパッケージが提供されているが、以下については別でパッケージが提供されている。
以下のURLを見る限り、azure-sdk-for-go の同等機能は将来的に廃止される予定らしい。 なので、ここでは azure-storage-blob-go を使用してBlobのファイルを読み書きする実装について確認する。 目次 †
準備 †Goパッケージのインストール go get github.com/Azure/azure-storage-blob-go/azblob ログイン az login リソースの作成 region=japanwest resourceGroup=リソースグループ名 storageAccountName=ストレージアカウント名 storageContainer=sample-container # リソースグループの作成 az group create \ --name $resourceGroup \ --location $region # ストレージアカウントの作成 az storage account create \ --name $storageAccountName \ --location $region \ --resource-group $resourceGroup \ --sku $storageSku # Storageコンテナの作成 az storage container create \ --name $storageContainer \ --resource-group $resourceGroup \ --account-name $storageAccountName 実装 †sample_sdk_blob.go package main
import (
"bytes"
"context"
"fmt"
"net/url"
"github.com/Azure/azure-storage-blob-go/azblob"
)
/**
* 環境変数の取得.
*/
func getEnv(envName string, defaultValue string) string {
value, exists := os.LookupEnv(envName)
if exists {
return value
} else {
return defaultValue
}
}
/**
* メイン処理.
*/
func main() {
fmt.Println("START main")
accountName := getEnv("storageAccountName", "")
accountKey := getEnv("storageAccountKey", "")
containerName := getEnv("storageContainer", "")
fileName := getEnv("storageBlobFileName", "")
containerUrlTempl := getEnv("storageContainerUrl", "https://%s.blob.core.windows.net/%s")
if accountName == "" || accountKey == "" || containerName == "" || fileName == "" {
fmt.Println("環境変数が設定されていません。")
return
}
ctx := context.Background()
containerUrlText := fmt.Sprintf(containerUrlTempl, accountName, containerName)
u, _ := url.Parse(fmt.Sprintf("%s/%s", containerUrlText, fileName))
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
fmt.Println(err)
}
/****************************
* アップロード
****************************/
blockBlobURL := azblob.NewBlockBlobURL(*u, azblob.NewPipeline(credential, azblob.PipelineOptions{}))
// サンプルデータ作成
data := []byte("sample1\nsample2\nsample3")
// アップロード
bufferSize := 2 * 1024 * 1024
maxBuffers := 3
_, err = azblob.UploadStreamToBlockBlob(ctx, bytes.NewReader(data), blockBlobURL,
azblob.UploadStreamToBlockBlobOptions{BufferSize: bufferSize, MaxBuffers: maxBuffers})
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Upload Success!")
}
/****************************
* ダウンロード
****************************/
p := azblob.NewPipeline(credential, azblob.PipelineOptions{})
cURL, _ := url.Parse(containerUrlText)
containerURL := azblob.NewContainerURL(*cURL, p)
blobURL := containerURL.NewBlobURL(fileName)
// サイズを取得
var blobSize int64 = 1024
blobPropResponse, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{})
if err != nil {
fmt.Println("GetProperties Error!")
fmt.Println(err)
} else {
fmt.Println("GetProperties Success!")
fmt.Printf("type: %s\n", blobPropResponse.ContentType())
fmt.Printf("size: %d\n", blobPropResponse.ContentLength())
blobSize = blobPropResponse.ContentLength()
}
// バッファに取得
downloadedData := make([]byte, blobSize)
err = azblob.DownloadBlobToBuffer(ctx, blobURL, 0, azblob.CountToEnd, downloadedData, azblob.DownloadFromBlobOptions{})
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Download Success!")
fmt.Println(string(downloadedData))
}
// ファイルにダウンロード
//err = azblob.DownloadBlobToFile(ctx, blobURL, 0, azblob.CountToEnd, file *os.File, o DownloadFromBlobOptions)
fmt.Println("END main")
}
動作確認 †アカウントキーの確認 az storage account keys list -n $storageAccountName 実行 export storageAccountName=ストレージアカウント名 export storageAccountKey="ストレージアカウントキー" export storageContainer=sample-container export storageBlobFileName=sample.txt go run sample_sdk_blob.go START main Upload Success! GetProperties Success! type: application/octet-stream size: 23 Download Success! sample1 sample2 sample3 END main ローカルエミュレータに対して実行する時 †ローカル実行する場合は、アカウント名、キー 及び コンテナURLを以下の通り設定する。 export storageAccountName=devstoreaccount1 export storageAccountKey="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" export storageContainerUrl=http://127.0.0.1:10000/%s/%s export storageContainer=sample-container export storageBlobFileName=sample.txt go run sample_sdk_blob.go |