Manage directories (OSS SDK for Go 1.0)
OSS provides directories that simulate a folder structure, making it easier to organize, locate, and perform bulk operations on large numbers of objects.
Notes
-
In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and Endpoints.
-
This topic demonstrates creating an OSSClient instance with an OSS endpoint. For alternative configurations, such as using a custom domain or authenticating with credentials from Security Token Service (STS), see Configure a client (Go SDK V1).
Sample code
Create a directory
The following code provides an example on how to create a directory:
package main
import (
"bytes"
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", 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("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Specify the name of the directory. The directory must end with a forward slash (/).
dirName := "exampledir/"
err = bucket.PutObject(dirName, bytes.NewReader([]byte("")))
if err != nil {
log.Fatalf("Failed to create directory '%s': %v", dirName, err)
}
log.Printf("Directory '%s' created successfully", dirName)
}
Delete a directory
Deleting a directory also deletes all its subdirectories and objects. Proceed with caution.
The following code provides an example on how to delete a directory named log/ and all objects in the directory:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", 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("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Specify the full path of the directory that you want to delete. Do not include the bucket name in the full path.
prefix := oss.Prefix("log/")
marker := oss.Marker("")
count := 0
for {
// List all objects whose names contain a specific prefix.
lor, err := bucket.ListObjects(marker, prefix)
if err != nil {
log.Fatalf("Failed to list objects in bucket '%s' with prefix '%s': %v", bucketName, prefix, err)
}
objects := []string{}
for _, object := range lor.Objects {
objects = append(objects, object.Key)
}
if len(objects) == 0 {
break
}
// Delete the directory and all objects stored in the directory.
// Set the oss.DeleteObjectsQuiet parameter to true. This setting indicates that OSS does not return a message after objects are deleted.
delRes, err := bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
if err != nil {
log.Fatalf("Failed to delete objects in bucket '%s': %v", bucketName, err)
}
if len(delRes.DeletedObjects) > 0 {
log.Fatalf("Some objects failed to delete: %v", delRes.DeletedObjects)
}
count += len(objects)
// Update the pagination parameters.
marker = oss.Marker(lor.NextMarker)
if !lor.IsTruncated {
break
}
}
log.Printf("Success, total delete object count: %d", count)
}
List a directory
The following code provides an example on how to list a directory:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", 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.
endpoint := "https://oss-cn-hangzhou.aliyuncs.com" // Replace yourEndpoint with the actual endpoint.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the source bucket.
bucketName := "example-bucket" // Replace yourBucketName with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Specify the position from which the list starts.
continueToken := ""
// Used to store all subdirectories.
var subdirectories []string
for {
// List all subdirectories.
lsRes, err := bucket.ListObjectsV2(
oss.ContinuationToken(continueToken),
oss.Prefix(""), // Without specifying a prefix, it indicates starting from the root directory.
oss.Delimiter("/"), // Simulate the folder structure by using "/".
)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display and collect the subdirectories (CommonPrefixes).
for _, prefix := range lsRes.CommonPrefixes {
log.Printf("Subdirectory: %s\n", prefix)
subdirectories = append(subdirectories, prefix)
}
// If you want to list more objects, update the value of the continueToken parameter.
if lsRes.IsTruncated {
continueToken = lsRes.NextContinuationToken
} else {
break
}
}
log.Println("All subdirectories have been listed.")
log.Printf("Total subdirectories: %d\n", len(subdirectories))
}
References
-
For more information about the API operation that you can call to create a directory, see PutObject.
-
For more information about the API operation that you can call to delete a directory and all objects in the directory, see DeleteObject.