List objects (Go SDK V1)
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.
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.
-
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).
To list objects, you must have the
oss:ListObjectspermission. For more information, see Grant a custom policy.-
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
FAQ
Can I sort objects by last modified time when I list them?
No. To sort objects by 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.