This topic describes how to list all objects, objects with a specific prefix, and objects and subdirectories in a specific directory within an Object Storage Service (OSS) bucket.
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.
To list objects, you must have the
oss:ListObjectspermission. For more information, see Attach a custom policy to a RAM user.OSS SDK for Go 2.2.5 and later supports returning RestoreInfo information.
Background information
You can call the ListObjectsV2 or ListObjects operation to list up to 1,000 objects in a bucket at a time. By specifying different parameters, you can implement various listing features, such as listing all objects after a specified start position, listing objects and subdirectories in a specified directory, and paginating the listing results. The main differences between these two operations are as follows:
When you use the
ListObjectsV2operation, you must use thefetchOwnerparameter to specify whether to include the Owner information of the objects in the results.When you use the
ListObjectsoperation, the Owner information of the objects is included in the results by default.NoteFor versioning-enabled buckets, you must use the ListObjectsV2 operation to list objects.
The following sections describe the parameters for listing objects using the ListObjectsV2 and ListObjects methods.
ListObjectsV2
The following table describes the parameters for listing objects using the ListObjectsV2 method.
Parameter | Description |
prefix | The prefix that the names of returned objects must contain. |
delimiter | A character for grouping object names. All object names that contain the same string from the prefix to the first occurrence of the delimiter are grouped as a single element (commonPrefixes). |
startAfter | The starting point for this listing operation. |
fetchOwner | Specifies whether to include Owner information in the results.
|
For more information, see ListObjectsV2.
ListObjects
The following table describes the parameters for listing objects using the ListObjects method.
Parameter | Description |
delimiter | A character for grouping object names. All object names that contain the same string from the prefix to the first occurrence of the delimiter are grouped as a single element (commonPrefixes). |
prefix | The prefix that the names of returned objects must contain. |
maxKeys | The maximum number of objects to return. The default value is 100. The maximum value is 1000. |
marker | The starting point for this listing operation. |
For more information, see ListObjects.
Examples
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to list 100 objects in a bucket.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace 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 := ""
for {
// List all objects.
lsRes, err := bucket.ListObjectsV2(oss.ContinuationToken(continueToken))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// 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 objects have been listed.")
}
ListObjects
The following sample code shows how to use the ListObjects method to list 100 objects in a bucket.
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List all objects.
marker := ""
for {
lsRes, err := bucket.ListObjects(oss.Marker(marker))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
for _, object := range lsRes.Objects {
log.Printf("Object Name: %s\n", object.Key)
}
// If more objects need to be listed, update the marker and continue the loop.
if lsRes.IsTruncated {
marker = lsRes.NextMarker
} else {
break
}
}
log.Println("All objects have been listed.")
}
Common scenarios
List a specific number of objects
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to list a specific number of objects.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Set MaxKeys to specify the maximum number of objects to list, and then list the objects.
maxKeys := 200
continueToken := ""
for {
lsRes, err := bucket.ListObjectsV2(oss.MaxKeys(maxKeys), oss.StartAfter(continueToken))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
}
// If more objects need to be listed, update the continuation token and continue the loop.
if lsRes.IsTruncated {
continueToken = lsRes.ContinuationToken
} else {
break
}
}
log.Println("All objects have been listed.")
}
ListObjects
The following sample code shows how to use the ListObjects method to list a specific number of objects.
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Set the maximum number of objects to list, and then list the objects.
maxKeys := 200
lsRes, err := bucket.ListObjects(oss.MaxKeys(maxKeys))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects:\n", len(lsRes.Objects))
for _, object := range lsRes.Objects {
log.Printf("Object: %s\n", object.Key)
}
if lsRes.IsTruncated {
log.Printf("More objects available. NextMarker: %s\n", lsRes.NextMarker)
} else {
log.Println("All objects have been listed.")
}
}
List objects with a specific prefix
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to list objects with a specific prefix.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Set the Prefix parameter to list objects whose names start with my-object-.
prefix := "my-object-"
lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
}
if lsRes.IsTruncated {
log.Printf("More objects available. Next Continuation Token: %s\n", lsRes.NextContinuationToken)
} else {
log.Println("All objects have been listed.")
}
}
ListObjects
The following sample code shows how to use the ListObjects method to list objects with a specific prefix.
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List objects with the specified prefix. By default, 100 objects are listed.
prefix := "my-object-"
lsRes, err := bucket.ListObjects(oss.Prefix(prefix))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s\n", object.Key)
}
if lsRes.IsTruncated {
log.Printf("More objects available. Next Marker: %s\n", lsRes.NextMarker)
} else {
log.Println("All objects have been listed.")
}
}
List objects after a specified starting point
ListObjectsV2
You can set the StartAfter parameter to specify the starting point for the listing. All objects that are in lexicographical order after the value of StartAfter are returned.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Specify to list objects after StartAfter. By default, 100 objects are listed.
startAfter := "my-object-"
lsRes, err := bucket.ListObjectsV2(oss.StartAfter(startAfter))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects starting after '%s':\n", len(lsRes.Objects), startAfter)
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
}
if lsRes.IsTruncated {
log.Printf("More objects available. Next Continuation Token: %s\n", lsRes.NextContinuationToken)
} else {
log.Println("All objects have been listed.")
}
}
ListObjects
You can set the Marker parameter to specify the starting point for the listing. All objects that are in lexicographical order after the value of Marker are returned.
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Initialize the marker.
marker := ""
// Loop to list all objects.
for {
lsRes, err := bucket.ListObjects(oss.Marker(marker))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects:\n", len(lsRes.Objects))
for _, object := range lsRes.Objects {
log.Printf("Object: %s\n", object.Key)
}
// If the result is truncated, update the marker and continue the loop.
if lsRes.IsTruncated {
marker = lsRes.NextMarker
} else {
break
}
}
log.Println("All objects have been listed.")
}
List all objects by page
ListObjectsV2
You can use the ListObjectsV2 method to list all objects in a bucket by page. You can set MaxKeys to specify the number of objects to list on each page.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List all objects by page. List 100 objects per page.
continueToken := ""
for {
lsRes, err := bucket.ListObjectsV2(oss.MaxKeys(100), oss.ContinuationToken(continueToken))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects:\n", len(lsRes.Objects))
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// If the result is truncated, update the continuation token and continue the loop.
if lsRes.IsTruncated {
continueToken = lsRes.NextContinuationToken
} else {
break
}
}
log.Println("All objects have been listed.")
}
ListObjects
You can use the ListObjects method to list all objects in a bucket by page. You can set MaxKeys to specify the number of objects to list on each page.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List all objects by page. List 100 objects per page.
marker := ""
for {
lsRes, err := bucket.ListObjects(oss.MaxKeys(100), oss.Marker(marker))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects:\n", len(lsRes.Objects))
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// If the result is truncated, update the continuation token and continue the loop.
if lsRes.IsTruncated {
marker = lsRes.NextMarker
} else {
break
}
}
log.Println("All objects have been listed.")
}
List objects with a specific prefix by page
ListObjectsV2
You can use the ListObjectsV2 method to list objects with a specific prefix by page. You can set MaxKeys to specify the number of objects to list on each page.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List objects with a specific prefix by page. List 80 objects per page.
prefix := "my-object-"
continueToken := ""
for {
lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.MaxKeys(80), oss.ContinuationToken(continueToken))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// If the result is truncated, update the continuation token and continue the loop.
if lsRes.IsTruncated {
continueToken = lsRes.NextContinuationToken
} else {
break
}
}
log.Println("All objects have been listed.")
}
ListObjects
You can use the ListObjects method to list objects with a specific prefix by page. You can set MaxKeys to specify the number of objects to list on each page.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List objects with the specified prefix by page. List 80 objects per page.
prefix := "my-object-"
marker := ""
for {
lsRes, err := bucket.ListObjects(oss.MaxKeys(80), oss.Marker(marker), oss.Prefix(prefix))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// If the result is truncated, update the marker and continue the loop.
if lsRes.IsTruncated {
marker = lsRes.NextMarker
} else {
break
}
}
log.Println("All objects have been listed.")
}
List information about all objects in a specific directory
ListObjectsV2
You can use the ListObjectsV2 method to list information about all objects in a specific directory (prefix), including the object size, last modified time, and object name.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List objects with the specified prefix by page. By default, 100 records are returned at a time.
continueToken := ""
prefix := "fun"
for {
lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results.
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// If the result is truncated, update the continuation token and continue the loop.
if lsRes.IsTruncated {
continueToken = lsRes.NextContinuationToken
} else {
break
}
}
log.Println("All objects have been listed.")
}
ListObjects
You can use the ListObjects method to list information about all objects in a specific directory (prefix), including the object size, last modified time, and object name.
package main
import (
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Traverse the objects.
marker := ""
prefix := "test"
for {
lor, err := bucket.ListObjects(oss.Marker(marker), oss.Prefix(prefix))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results.
for _, object := range lor.Objects {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
}
// If the result is truncated, update the marker and continue the loop.
if lor.IsTruncated {
marker = lor.NextMarker
} else {
break
}
}
log.Println("All objects have been listed.")
}
List information about all subdirectories in a specific directory
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to list information about all subdirectories in a specific directory (prefix).
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List folders with the specified prefix by page. By default, 100 records are returned at a time.
continueToken := ""
prefix := ""
for {
lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken), oss.Delimiter("/"))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results.
for _, dirName := range lsRes.CommonPrefixes {
log.Println("Directory Name:", dirName)
}
// If the result is truncated, update the continuation token and continue the loop.
if lsRes.IsTruncated {
continueToken = lsRes.NextContinuationToken
} else {
break
}
}
log.Println("All directories have been listed.")
}
ListObjects
The following sample code shows how to use the ListObjects method to list information about all subdirectories in a specific directory (prefix).
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List folders with the specified prefix by page. By default, 100 records are returned at a time.
marker := ""
prefix := "yourDirPrefix" // Replace with the actual prefix.
for {
lor, err := bucket.ListObjects(oss.Marker(marker), oss.Prefix(prefix), oss.Delimiter("/"))
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Print the results.
for _, dirName := range lor.CommonPrefixes {
log.Println("Directory Name:", dirName)
}
// If the result is truncated, update the continuation token and continue the loop.
if lor.IsTruncated {
marker = lor.NextMarker
} else {
break
}
}
log.Println("All directories have been listed.")
}
List objects and return Owner information
The following sample code shows how to use the ListObjectsV2 method to list objects and return their Owner information.
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, ensure 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, use 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, use the actual region.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name.
bucketName := "yourBucketName" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Obtain Owner information and list the objects.
lsRes, err := bucket.ListObjectsV2(oss.FetchOwner(true))
if err != nil {
log.Fatalf("Failed to list objects with owner information: %v", err)
}
// Print the results. By default, 100 records are returned at a time.
for _, object := range lsRes.Objects {
log.Printf("Object Key: %s, Owner ID: %s, Display Name: %s\n",
object.Key, object.Owner.ID, object.Owner.DisplayName)
}
log.Println("All objects have been listed.")
}
Folders
OSS uses a flat structure to store objects. A directory is a zero-byte object whose name ends with a forward slash (/). You can upload and download this object. By default, an object whose name ends with a forward slash (/) is displayed as a directory in the OSS console. For the complete sample code that is used to create directories, visit GitHub.
You can specify the delimiter and prefix parameters to list objects by directory.
If you set prefix to a directory name in the request, the objects and subdirectories whose names contain the prefix are listed.
If you specify a prefix and set delimiter to a forward slash (/) in the request, the objects and subdirectories whose names start with the specified prefix in the directory are listed. Each subdirectory is listed as a single result element in CommonPrefixes. The objects and directories in these subdirectories are not listed.
For example, a bucket contains the following objects: oss.jpg, fun/test.jpg, fun/movie/001.avi, and fun/movie/007.avi. The forward slash (/) is specified as the directory delimiter. The following examples describe how to list objects in simulated directories.
List all objects in a bucket
ListObjectsV2
The following sample code shows how to use ListObjectsV2 to list all objects in a bucket.
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, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // List all objects in the specified bucket. startAfter := "" continueToken := "" for { lsRes, err := bucket.ListObjectsV2(oss.StartAfter(startAfter), oss.ContinuationToken(continueToken)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the results. By default, 100 records are returned at a time. for _, object := range lsRes.Objects { log.Printf("Object Key: %s\n", object.Key) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { startAfter = lsRes.StartAfter continueToken = lsRes.NextContinuationToken } else { break } } log.Println("All objects have been listed.") }ListObjects
The following sample code shows how to use the ListObjects method to list all objects in a bucket.
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, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // List all objects in the specified bucket. marker := "" for { lsRes, err := bucket.ListObjects(oss.Marker(marker)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the results. By default, 100 records are returned at a time. for _, object := range lsRes.Objects { log.Printf("Object Key: %s\n", object.Key) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { marker = lsRes.NextMarker } else { break } } log.Println("All objects have been listed.") }The following result is returned when you use the preceding two methods to list all objects in the bucket.
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg oss.jpg CommonPrefixes:
List all objects in a specific directory
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to list all objects in a specific 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, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // List all objects in the specified directory. prefix := "aaa/db-init" continueToken := "" for { lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the results. By default, 100 records are returned at a time. for _, object := range lsRes.Objects { log.Printf("Object Key: %s\n", object.Key) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { continueToken = lsRes.NextContinuationToken } else { break } } log.Println("All objects have been listed.") }ListObjects
The following sample code shows how to use the ListObjects method to list all objects in a specific 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, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // List all objects in the specified directory. prefix := "aaa/db-init" // Replace with the actual prefix. marker := "" for { lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the results. By default, 100 records are returned at a time. for _, object := range lsRes.Objects { log.Printf("Object Key: %s\n", object.Key) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { marker = lsRes.NextMarker } else { break } } log.Println("All objects have been listed.") }The following result is returned when you use the preceding two methods to list all objects in the specified directory.
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg CommonPrefixes:
List objects and subdirectories in a directory
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to list objects and subdirectories in 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 this sample code, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // List objects and subdirectories in the specified directory. prefix := "" // Set a prefix as needed. delimiter := "/" continueToken := "" for { lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.Delimiter(delimiter), oss.ContinuationToken(continueToken)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the results. By default, 100 records are returned at a time. for _, object := range lsRes.Objects { log.Printf("Object Key: %s\n", object.Key) } // Print the subdirectories. for _, commonPrefix := range lsRes.CommonPrefixes { log.Printf("Common Prefix: %s\n", commonPrefix) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { continueToken = lsRes.NextContinuationToken } else { break } } log.Println("All objects and subdirectories have been listed.") }ListObjects
The following sample code shows how to use the ListObjects method to list objects and subdirectories in 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 this sample code, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // List objects and subdirectories in the specified directory. prefix := "aaa/db-init/" // Replace with the actual prefix. marker := "" delimiter := "/" for { lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker), oss.Delimiter(delimiter)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the list of objects. for _, object := range lsRes.Objects { log.Printf("Object Key: %s\n", object.Key) } // Print the list of subdirectories. for _, commonPrefix := range lsRes.CommonPrefixes { log.Printf("Common Prefix: %s\n", commonPrefix) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { marker = lsRes.NextMarker } else { break } } log.Println("All objects and subdirectories have been listed.") }The following result is returned when you use the preceding two methods to list objects and subdirectories in the specified directory.
Objects: fun/test.jpg CommonPrefixes: fun/movie/
Obtain the size of objects in a specific directory
ListObjectsV2
The following sample code shows how to use the ListObjectsV2 method to obtain the size of objects in a specific 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, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Get the bucket. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // Get the size of objects in the specified directory. prefix := "/fun" // Replace with the actual prefix. continueToken := "" for { lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the list of objects and their sizes. for _, object := range lsRes.Objects { log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { continueToken = lsRes.NextContinuationToken } else { break } } log.Println("All objects have been listed with their sizes.") }ListObjects
The following sample code shows how to use the ListObjects method to obtain the size of objects in a specific 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, ensure 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, use 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, use the actual region. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4)) if err != nil { log.Fatalf("Failed to create OSS client: %v", err) } // Specify the bucket name. bucketName := "yourBucketName" // Replace with the actual bucket name. bucket, err := client.Bucket(bucketName) if err != nil { log.Fatalf("Failed to get bucket: %v", err) } // Get the size of objects in the specified directory. prefix := "test/" // Replace with the actual prefix. marker := "" for { lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker)) if err != nil { log.Fatalf("Failed to list objects: %v", err) } // Print the list of objects and their sizes. for _, object := range lsRes.Objects { log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size) } // If the result is truncated, update the continuation token and continue the loop. if lsRes.IsTruncated { marker = lsRes.NextMarker } else { break } } log.Println("All objects have been listed with their sizes.") }
FAQ
Can I sort objects by last modified time when I list them?
No. If you need to sort objects by their last modified time, use data indexing.
References
For the complete sample code for listing objects, see the GitHub example.
For more information about the API operations for listing objects, see ListObjectsV2 and ListObjects.