このトピックでは、Object Storage Service (OSS) SDK for Goを使用して一般的な操作を実行する方法について説明します。 OSS SDK for Goのインストール方法、アクセス資格情報の設定方法、およびバケットの作成とアップロード、オブジェクトのダウンロード、一覧表示、削除などの基本的な操作の実行方法を学習できます。
Goコンパイルとランタイム環境のインストール
[ソースからGoをインストールする] を参照して、Goコンパイルおよびランタイム環境をダウンロードしてインストールします。 次のコマンドを実行して、Goがインストールされているかどうかを確認します。
go version
OSS SDK for Goのインストール
次のコマンドを実行して、コードパッケージを取得します。
go get github.com/aliyun/aliyun-oss-go-sdk/oss
アクセス資格情報の設定
OSS SDK for Goを使用する前に、アクセス資格情報を設定する必要があります。 この例では、RAMユーザーのAccessKeyペアが使用されます。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。 RAMユーザーのAccessKeyペアを取得する方法の詳細については、「CreateAccessKey」をご参照ください。
次のコマンドを実行して、RAMユーザーのAccessKeyペアを使用してアクセス資格情報を設定します。
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Windows
set OSS_ACCESS_KEY_ID <ALIBABA_CLOUD_ACCESS_KEY_ID>
set OSS_ACCESS_KEY_SECRET <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
デモプロジェクト
次のデモでは、OSSClientインスタンスを作成し、バケットを作成し、オブジェクトをアップロード、ダウンロード、リスト、および削除する方法を示します。
デモプロジェクトのディレクトリにmain.goファイルを作成します。
package main import ( "log" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) var client *oss. Client // Specify the global variable used to store the OSSClient instance. func main() { // Specify the name of the bucket. bucketName := "yourBucketName" // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. endpoint := "yourEndpoint" // Check whether the environment variables are configured. if endpoint == "" || bucketName == "" { log.Fatal("Please set yourEndpoint and bucketName.") } // Obtain access credentials from environment variables. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { handleError(err) } // Create an OSSClient instance. // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Specify the version of the signature algorithm. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) client, err := oss.New(endpoint, "", "", clientOptions...) if err != nil { handleError(err) } // Display the client information. log.Printf("Client: %#v\n", client) // Sample operation: create a bucket. if err := createBucket(bucketName); err != nil { handleError(err) } // Sample operation: upload an object. objectName := "file.txt" localFileName := "/path/to/local/file.txt" if err := uploadFile(bucketName, objectName, localFileName); err != nil { handleError(err) } // Sample operation: download an object. downloadedFileName := "/path/to/downloaded/file.txt" if err := downloadFile(bucketName, objectName, downloadedFileName); err != nil { handleError(err) } // Sample operation: list an object. if err := listObjects(bucketName); err != nil { handleError(err) } // Sample operation: delete an object. if err := deleteObject(bucketName, objectName); err != nil { handleError(err) } } // Call handleError to handle unrecoverable errors and terminate the program after recording the error messages. func handleError(err error) { log.Fatalf("Error: %v", err) } // Call CreateBucket to create an OSS bucket. // Specify the following parameters: // // bucketName: the name of the bucket. // endpoint: the endpoint of the region in which the bucket is located. // // If the bucket is created, a log is generated. Otherwise, an error message is returned. func createBucket(bucketName string) error { // Create the bucket. err := client.CreateBucket(bucketName) if err != nil { return err } // After the bucket is created, a log is generated. log.Printf("Bucket created successfully: %s", bucketName) return nil } // Call uploadFile to upload a local file to an OSS bucket. // Specify the following parameters: // // bucketName: the name of the bucket. // objectName: the full path of the object. Do not include the bucket name in the full path. // localFileName: the full path of the local file. // endpoint: the endpoint of the region in which the bucket is located. // // If the local file is uploaded, a log is generated. Otherwise, an error message is returned. func uploadFile(bucketName, objectName, localFileName string) error { // Obtain the bucket information. bucket, err := client.Bucket(bucketName) if err != nil { return err } // Upload the local file. err = bucket.PutObjectFromFile(objectName, localFileName) if err != nil { return err } // After the local file is uploaded, a log is generated. log.Printf("File uploaded successfully to %s/%s", bucketName, objectName) return nil } // Call downloadFile to download an object from an OSS bucket to a local path. // Specify the following parameters: // // bucketName: the name of the bucket. // objectName: the full path of the object. Do not include the bucket name in the full path. // downloadedFileName: the full path of the local file that you want to store the downloaded object. // endpoint: the endpoint of the region in which the bucket is located. // // If the object is downloaded, a log is generated. Otherwise, an error message is returned. func downloadFile(bucketName, objectName, downloadedFileName string) error { // Obtain the bucket information. bucket, err := client.Bucket(bucketName) if err != nil { return err } // Download the object. err = bucket.GetObjectToFile(objectName, downloadedFileName) if err != nil { return err } // After the object is downloaded, a log is generated. log.Printf("File downloaded successfully to %s", downloadedFileName) return nil } // Call listObjects to list all objects in an OSS bucket. // Specify the following parameters: // // bucketName: the name of the bucket. // endpoint: the endpoint of the region in which the bucket is located. // // If the objects are listed, all objects are displayed. Otherwise, an error message is returned. func listObjects(bucketName string) error { // Obtain the bucket information. bucket, err := client.Bucket(bucketName) if err != nil { return err } // List objects. marker := "" for { lsRes, err := bucket.ListObjects(oss.Marker(marker)) if err != nil { return err } // Display the listed objects. By default, 100 objects are returned at a time. for _, object := range lsRes.Objects { log.Printf("Object: %s", object.Key) } if !lsRes.IsTruncated { break } marker = lsRes.NextMarker } return nil } // Call deleteObject to delete an object from an OSS bucket. // Specify the following parameters: // // bucketName: the name of the bucket. // objectName: the name of the object that you want to delete. // endpoint: the endpoint of the region in which the bucket is located. // // If the object is deleted, a log is generated. Otherwise, an error message is returned. func deleteObject(bucketName, objectName string) error { // Obtain the bucket information. bucket, err := client.Bucket(bucketName) if err != nil { return err } // Delete the object. err = bucket.DeleteObject(objectName) if err != nil { return err } // After the object is deleted, a log is generated. log.Printf("Object deleted successfully: %s/%s", bucketName, objectName) return nil }
main.goファイルのbucketName、endpoint、objectName、localFileName、およびdownloadedFileNameを、ビジネス要件に基づいた実際の値に置き換えます。
以下のコマンドを実行します。
go run main.go