All Products
Search
Document Center

Object Storage Service:List objects using OSS SDK for Go 2.0

Last Updated:Jun 04, 2026

List all objects in a bucket with OSS SDK for Go.

Notes

  • The sample code uses the China (Hangzhou) region ID cn-hangzhou and the public endpoint. To access the bucket from other Alibaba Cloud services in the same region, use an internal endpoint. OSS regions and endpoints.

  • Access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • Listing objects requires the oss:ListObjects permission. Grant custom permissions to RAM users.

Methods

Advanced API operation for listing objects

Important
  • OSS SDK for Go V2 provides a paginator that handles automatic pagination across multiple API calls.

  • The paginator object uses the <OperationName>Paginator naming convention, created by New<OperationName>Paginator. It implements the HasNext and NextPage methods. HasNext checks for remaining pages and NextPage fetches the next page.

API details:

type ListObjectsV2Paginator struct

func (p *ListObjectsV2Paginator) HasNext() bool

func (p *ListObjectsV2Paginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListObjectsV2Result, error)

func (c *Client) NewListObjectsV2Paginator(request *ListObjectsV2Request, optFns ...func(*PaginatorOptions)) *ListObjectsV2Paginator

Request parameters

Parameter

Type

Description

request

*ListObjectsV2Request

API operation parameters. ListObjectsV2Request

optFns

...func(*PaginatorOptions)

Optional. Operation-level parameter. PaginatorOptions.

Common parameters of ListObjectsV2:

Parameter

Description

prefix

The prefix that returned object names must contain.

maxKeys

The maximum number of objects returned each time.

delimiter

The character used to group objects by name. Objects with the same string from the specified prefix to the first delimiter are grouped as a CommonPrefixes element.

startAfter

The position from which the list operation starts.

fetchOwner

Whether to include owner information in the response.

  • true: The response includes the owner information.

  • false: The response does not include the owner information.

Response parameters

Response parameter

Description

*ListObjectsV2Paginator

The paginator object that implements the HasNext and NextPage methods. HasNext checks for remaining pages and NextPage fetches the next page.

Basic API operation for listing objects

func (c *Client) ListObjectsV2(ctx context.Context, request *ListObjectsV2Request, optFns ...func(*Options)) (*ListObjectsV2Result, error)

Request parameters

Parameter

Type

Description

ctx

context.Context

The request context. Can set the total request duration.

request

*ListObjectsV2Request

API operation parameters. ListObjectsV2Request.

optFns

...func(*Options)

Optional. Operation-level parameters. Options.

Response parameters

Response parameter

Type

Description

result

*ListObjectsV2Result

The operation response, available when err is nil. ListObjectsV2Result.

err

error

The error status. Non-nil if the request fails.

Sample code

List objects using the advanced API operation

List all objects in a bucket using the paginator.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket: oss.Ptr(bucketName),
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		// Obtain the data on the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Display information about each object on the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

List objects using the basic API operation

List all objects in a bucket by calling ListObjectsV2.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg) 
 
	// Create a ListObjectsV2 request.
	request := &oss.ListObjectsV2Request{
		Bucket:            oss.Ptr(bucketName),
	}

	for {
		// Perform the operation to list all objects.
		lsRes, err := client.ListObjectsV2(context.TODO(), request)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Display the results.
		for _, object := range lsRes.Contents {
			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 there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
		if lsRes.IsTruncated {
			request.ContinuationToken = lsRes.NextContinuationToken
		} else {
			break // End the cycle if there are no more objects.
		}
	}

	log.Println("All objects have been listed.")
}

Common scenarios

List all objects in a directory

Use the paginator

Lists all objects in a specified directory using the Prefix parameter.

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket:  oss.Ptr(bucketName),
		Prefix:  oss.Ptr("exampledir/"), // List all objects in the specified directory
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		fmt.Printf("Page %v\n", i)

		// Obtain the data on the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Print the continuation token.
		log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
		// Display information about each object on the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

Use ListObjectsV2

Lists all objects in a specified directory using the Prefix parameter.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a ListObjectsV2 request.
	request := &oss.ListObjectsV2Request{
		Bucket:            oss.Ptr(bucketName),
		Prefix:            oss.Ptr("exampledir/"), // List all objects in the specified directory.
	}

	for {
		lsRes, err := client.ListObjectsV2(context.TODO(), request)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Display the results.
		for _, object := range lsRes.Contents {
			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 there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
		if lsRes.IsTruncated {
			request.ContinuationToken = lsRes.NextContinuationToken
		} else {
			break // End the cycle if there are no more objects.
		}
	}

	log.Println("All objects have been listed.")
}

List objects whose names contain a specified prefix

Use the paginator

Lists all objects whose names match a specified prefix.

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket: oss.Ptr(bucketName),
		Prefix: oss.Ptr("my-object-"), // List all objects whose names contain the specified prefix.
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		fmt.Printf("Page %v\n", i)

		// Obtain the data on the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Print the continuation token.
		log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
		// Display information about each object on the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

Use ListObjectsV2

Lists all objects whose names match a specified prefix.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a ListObjectsV2 request.
	request := &oss.ListObjectsV2Request{
		Bucket:            oss.Ptr(bucketName),
		Prefix:            oss.Ptr("my-object-"),
	}

	for {
		lsRes, err := client.ListObjectsV2(context.TODO(), request)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Display the results.
		for _, object := range lsRes.Contents {
			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 there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
		if lsRes.IsTruncated {
			request.ContinuationToken = lsRes.NextContinuationToken
		} else {
			break // End the cycle if there are no more objects.
		}
	}

	log.Println("All objects have been listed.")
}

List a specified number of objects

Use the paginator

Lists a specified number of objects using the MaxKeys parameter.

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket:  oss.Ptr(bucketName),
		MaxKeys: 10, // The maximum number of objects returned each time.
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		fmt.Printf("Page %v\n", i)

		// Obtain the data on the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Print the continuation token.
		log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
		// Display information about each object on the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

Use ListObjectsV2

Lists a specified number of objects using the MaxKeys parameter.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a ListObjectsV2 request.
	request := &oss.ListObjectsV2Request{
		Bucket:            oss.Ptr(bucketName),
		MaxKeys:           10, // The maximum number of objects returned each time.
	}

	for {
		lsRes, err := client.ListObjectsV2(context.TODO(), request)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Display the results.
		for _, object := range lsRes.Contents {
			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 there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
		if lsRes.IsTruncated {
			request.ContinuationToken = lsRes.NextContinuationToken
		} else {
			break // End the cycle if there are no more objects.
		}
	}

	log.Println("All objects have been listed.")
}

List all objects from a specific position

Use the paginator

Lists objects starting after a specified position using the StartAfter parameter.

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket:     oss.Ptr(bucketName),
		StartAfter: oss.Ptr("my-object"), // Specify the starting position for listing objects
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		fmt.Printf("Page %v\n", i)

		// Obtain the data on the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Print the continuation token.
		log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
		// Display information about each object on the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

Use ListObjectsV2

Lists objects starting after a specified position using the StartAfter parameter.

package main

import (
	"context"
	"flag"
	"log"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	flag.Parse() // Parse command line parameters.

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a ListObjectsV2 request.
	request := &oss.ListObjectsV2Request{
		Bucket:            oss.Ptr(bucketName),
		StartAfter:        oss.Ptr("my-object"), // Specify the starting position for listing objects.
	}

	for {
		lsRes, err := client.ListObjectsV2(context.TODO(), request)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Display the results.
		for _, object := range lsRes.Contents {
			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 there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
		if lsRes.IsTruncated {
			request.ContinuationToken = lsRes.NextContinuationToken
		} else {
			break // End the cycle if there are no more objects.
		}
	}

	log.Println("All objects have been listed.")
}

List all objects in the root directory

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The bucket name.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	flag.Parse() // Parse the command-line parameters.

	// Check whether the bucket name is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Create a ListObjectsV2 request, and set the delimiter to a forward slash (/).
	request := &oss.ListObjectsV2Request{
		Bucket:            oss.Ptr(bucketName),
		Delimiter:         oss.Ptr("/"), // Use forward slashes (/) as delimiters.
		MaxKeys:           100,          // The maximum number of objects returned per request.
	}

	// Variable to store all subdirectories (CommonPrefixes).
	var subdirectories []oss.CommonPrefix

	for {
		lsRes, err := client.ListObjectsV2(context.TODO(), request)
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Log and collect subdirectories (CommonPrefixes).
		for _, prefix := range lsRes.CommonPrefixes {
			log.Printf("Subdirectory: %v\n", *prefix.Prefix)
			subdirectories = append(subdirectories, prefix)
		}

		// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
		if lsRes.IsTruncated {
			request.ContinuationToken = lsRes.NextContinuationToken
		} else {
			break // End the cycle if there are no more objects.
		}
	}

	log.Println("All subdirectories have been listed.")
	log.Printf("Total subdirectories: %d\n", len(subdirectories))
}

References