すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:OSS SDK for Goの使用を開始する

最終更新日:Jan 10, 2025

このトピックでは、Object Storage Service (OSS) SDK for Go V2を使用して一般的な操作を実行する方法について説明します。 OSS SDK for Goのインストール方法、アクセス資格情報の設定方法、およびバケットの作成とアップロード、オブジェクトのダウンロード、一覧表示、削除などの基本的な操作の実行方法を学習できます。

ノート

  • OSSでサポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。

  • OSS SDK for Goを使用してOSSへのリクエストを開始する前に、OSSClientインスタンスを初期化して設定する必要があります。 この例では、デフォルト設定をロードすることによってOSSClientインスタンスが作成されます。 OSSクライアントの設定方法の詳細については、「OSSClientインスタンスの設定」をご参照ください。

前提条件

環境変数の設定

AccessKeyペアの環境変数を設定します。

Linux

  1. CLIで次のコマンドを実行して、環境変数の設定を ~/.bashrcファイルに追加します。

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. 次のコマンドを実行して変更を適用します。

    source ~/.bashrc
  3. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. ターミナルで次のコマンドを実行して、デフォルトのシェルタイプを表示します。

    echo $SHELL
  2. デフォルトのシェルタイプに基づいて環境変数を設定します。

    Zsh

    1. 次のコマンドを実行して、環境変数の設定を ~/.zshrcファイルに追加します。

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. 次のコマンドを実行して変更を適用します。

      source ~/.zshrc
    3. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    バッシュ

    1. 次のコマンドを実行して、環境変数の設定を ~/.bash_profileファイルに追加します。

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. 次のコマンドを実行して変更を適用します。

      source ~/.bash_profile
    3. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. CMDで次のコマンドを実行します。

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. PowerShellで次のコマンドを実行します。

    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

OSS SDK for GOのインストール

  • Go 1.18以降のコンパイルおよびランタイム環境をダウンロードしてインストールします。 次のコマンドを実行して、Goがインストールされているかどうかを確認します。

    go version

    既存のコンパイル環境とランタイム環境のが要件を満たしていない場合は、[ソースからのgoのインストール] に移動して環境をダウンロードしてインストールします。

  • プロジェクトディレクトリを作成し、Goモジュールを初期化します。

    mkdir oss-go-example && cd oss-go-example && go mod init oss-go-example
  • 次のコマンドを実行して、OSS SDK for Goパッケージを取得します。

    go get github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss
  • 次のコードを実行して、OSS SDK for Goパッケージをインポートします。

    import "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"

デモプロジェクト

次のデモでは、バケットを作成し、オブジェクトをアップロード、ダウンロード、一覧表示、および削除する方法について説明します。

バケットの作成

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	request := &oss.PutBucketRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Execute a request to create a bucket.
	result, err := client.PutBucket(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket %v", err)
	}

	// Display the result of the bucket creation.
	log.Printf("put bucket result:%#v\n", result)
}

オブジェクトのアップロード

package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the content that you want to upload.
	content := "hi oss"

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to upload an object.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName),        // The name of the bucket.
		Key: oss.Ptr(objectName),        // The name of the object.
		Body:   strings.NewReader(content), // The content that you want to upload.
	}

	// Execute the request to upload an object.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload.
	log.Printf("put object result:%#v\n", result)
}

オブジェクトのダウンロード

package main

import (
	"context"
	"flag"
	"io"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the object.
	request := &oss.GetObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// Query the object and process the results.
	result, err := client.GetObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get object %v", err)
	}
	defer result.Body.Close() // Make sure that the response body is closed when the function is complete.

	log.Printf("get object result:%#v\n", result)

	// Read the content of the object.
	data, _ := io.ReadAll(result.Body)
	log.Printf("body:%s\n", data)
}

リストオブジェクト

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		// Obtain the data of the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Display information about each object in the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

オブジェクトの削除

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete an object.
	request := &oss.DeleteObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// Delete the object and process the results.
	result, err := client.DeleteObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete object %v", err)
	}

	// Display the result of the object deletion.
	log.Printf("delete object result:%#v\n", result)
}

  1. デモプロジェクトのディレクトリにmain.goファイルを作成します。 ビジネス要件に基づいて、上記のサンプルコードをmain.goファイルにコピーします。

  2. 次のコマンドの "yourRegion" 、"yourBucketName" 、および "yourObjectName" を実際の設定に置き換えます。 "yourRegion" をバケットのリージョンに置き換えます。 たとえば、バケットが中国 (杭州) リージョンにある場合、リージョンをcn-Hangzhouに設定します。

    go run main.go --region "yourRegion" --bucket "yourBucketName" --object "yourObjectName"

関連ドキュメント

  • サンプルコードの詳細については、『GitHub』をご参照ください。