Warning Delete objects with caution because deleted objects cannot be recovered.

For the complete code of deleting objects, see GitHub.

Delete an object

Run the following code to delete a single object:

package main

import (
	"fmt"
	"os"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Create an OSSClient instance.
	client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	bucketName := "<yourBucketName>"
	objectName := "<yourObjectName>"

	// Obtain the bucket.
	bucket, err := client.Bucket(bucketName)
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Delete an object.
	err = bucket.DeleteObject(objectName)
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Delete multiple objects

You can use Bucket.DeleteObjects to delete multiple objects and specify the DeleteObjectsQuiet parameter to determine whether the result of the delete operation is returned. The results of the deleted objects are returned by default.

Run the following code to delete multiple objects:

package main

import (
	"fmt"
	"os"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Create an OSSClient instance.
	client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	bucketName := "<yourBucketName>"

	// Obtain the bucket.
	bucket, err := client.Bucket(bucketName)
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// The results of deleted objects are returned.
	delRes, err := bucket.DeleteObjects([]string{"my-object-1", "my-object-2"})
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Println("Deleted Objects:", delRes.DeletedObjects)

	// The deletion results are not returned.
	_, err = bucket.DeleteObjects([]string{"my-object-3", "my-object-4"},
	oss.DeleteObjectsQuiet(true))
	if err ! = nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}