To simplify the organization and management of large numbers of objects, which can be difficult in a flat structure, Object Storage Service (OSS) offers the directory feature that simulates a folder structure.
Usage 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.
In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configure OSSClient instances.
Sample code
Create a directory
The following code provides an example of 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 this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, specify the actual endpoint.
// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set the bucket name. For example, examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Set the directory name. The name 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 of how to delete the log/ directory and all files within it.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, specify the actual endpoint.
// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set the bucket name.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Set the full path of the directory to delete. The full path does not include the bucket name.
prefix := oss.Prefix("log/")
marker := oss.Marker("")
count := 0
for {
// List all objects that have the specified 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 files in it.
// Set oss.DeleteObjectsQuiet to true. This means the deletion result is not returned.
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 paging parameters.
marker = oss.Marker(lor.NextMarker)
if !lor.IsTruncated {
break
}
}
log.Printf("Success, total delete object count: %d", count)
}
List directories
The following code provides an example of how to list all subdirectories in the root directory.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, specify the actual endpoint.
endpoint := "https://oss-cn-hangzhou.aliyuncs.com" // Replace this with the actual endpoint.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Set the bucket name.
bucketName := "example-bucket" // Replace this with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// The initial continuation token.
continueToken := ""
// Used to store all subdirectories.
var subdirectories []string
for {
// List all subdirectories.
lsRes, err := bucket.ListObjectsV2(
oss.ContinuationToken(continueToken),
oss.Prefix(""), // Do not specify a prefix. This means the listing starts from the root directory.
oss.Delimiter("/"), // Use "/" to simulate a directory structure.
)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print and collect the subdirectories (CommonPrefixes).
for _, prefix := range lsRes.CommonPrefixes {
log.Printf("Subdirectory: %s\n", prefix)
subdirectories = append(subdirectories, prefix)
}
// If more objects need to be listed, update the continuation token and continue the loop.
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 to create a directory, see PutObject.
For more information about the API operation to delete a directory and all files within it, see DeleteObject.