All Products
Search
Document Center

:Delete objects

Last Updated:Apr 02, 2025

This topic describes how to delete a single object or multiple objects using OSS SDK for Go.

Notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints supported by Object Storage Service (OSS), see OSS 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.

  • The oss:DeleteObject permission is required to delete an object. For more information, see Grant custom permissions to RAM users.

Methods

Delete a single object

func (c *Client) DeleteObject(ctx context.Context, request *DeleteObjectRequest, optFns ...func(*Options)) (*DeleteObjectResult, error)

Delete multiple objects

func (c *Client) DeleteMultipleObjects(ctx context.Context, request *DeleteMultipleObjectsRequest, optFns ...func(*Options)) (*DeleteMultipleObjectsResult, error)

Request parameters

Parameter

Type

Description

ctx

context.Context

The context of the request, which can be used to specify the total duration of the request.

request

*DeleteObjectRequest

Parameters of an API operation, such as the name of the object. For more information, visit DeleteObjectRequest.

*DeleteMultipleObjectsRequest

Parameters of an API operation, such as the list of objects to delete. For more information, visit DeleteMultipleObjectsRequest.

optFns

...func(*Options)

Optional. The operation-level parameters. For more information, see Options.

Response parameters

Parameter

Type

Description

result

*DeleteObjectResult

The response to the operation. This parameter is valid when the value of err is nil. For more information, visit DeleteObjectResult.

*DeleteMultipleObjectsResult

The response to the operation. This parameter is valid when the value of err is nil. For more information, visit DeleteMultipleObjectsResult.

err

error

The status of the request. If the request fails, the value of err is not nil.

Sample code

Delete a single object

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.
	objectName string // Name of the object.
)

// 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.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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")
	}

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name 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 delete an object.
	request := &oss.DeleteObjectRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		Key:    oss.Ptr(objectName), // Name of the object.
	}

	// Execute the request and process the result.
	result, err := client.DeleteObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete object %v", err)
	}

	// Display the result.
	log.Printf("delete object result:%#v\n", result)
}

Delete multiple specified objects

package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"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.
	objects    string // List of object names (separated with commas).
)

// 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.")
	flag.StringVar(&objects, "objects", "", "The name of the objects (comma-separated).")
}

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")
	}

	// Check whether the list of object names is provided.
	if len(objects) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, objects name 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)

	// Convert the list of object names into a slice.
	var DeleteObjects []oss.DeleteObject
	objectSlice := strings.Split(objects, ",")
	for _, name := range objectSlice {
		DeleteObjects = append(DeleteObjects, oss.DeleteObject{Key: oss.Ptr(strings.TrimSpace(name))})
	}

	// Create a request to delete multiple objects.
	request := &oss.DeleteMultipleObjectsRequest{
		Bucket:  oss.Ptr(bucketName), // Name of the bucket.
		Objects: DeleteObjects,       // List of objects to delete.
	}

	// Execute the request and process the results.
	result, err := client.DeleteMultipleObjects(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete multiple objects %v", err)
	}

	// Display the results.
	log.Printf("delete multiple objects result:%#v\n", result)
}

References