You can delete a single object, multiple specified objects, objects whose names contain a specific prefix, or delete a specific directory and all objects in the directory.
Warning Deleted objects cannot be recovered. Exercise caution when you delete objects.
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, endpoints and open ports.
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 Initialization.
To delete an object, you must have the oss:DeleteObject
permission. For more information, see Attach a custom policy to a RAM user.
Delete a single object
The following sample code provides an example on how to delete an object named exampleobject.txt from a bucket named examplebucket:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
// Set objectName to the full path of the object that you want to delete. The full path must contain the extension of the object name but cannot contain the bucket name. Example: exampledir/exampleobject.txt.
// If you want to delete a directory, set objectName to the directory name. If the directory contains objects, you must delete all objects from the directory before you can delete the directory.
objectName := "exampledir/exampleobject.txt"
// Create a bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Delete the object.
err = bucket.DeleteObject(objectName)
if err != nil {
log.Fatalf("Failed to delete object '%s': %v", objectName, err)
}
log.Printf("Successfully deleted object: %s\n", objectName)
}
Delete multiple objects
You can manually delete up to 1,000 objects at a time. You can delete multiple specified objects, objects whose names contain the specified prefix, or a directory and all objects in the directory.
You can also configure lifecycle rules to automatically delete objects. For more information, see Lifecycle rules based on the last modified time.
Delete multiple objects with specified names
The following sample code provides an example on how to delete multiple objects with specified names:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
// Create a bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Delete multiple objects and the result is returned.
objectsToDelete := []string{"my-object-1", "my-object-2"}
delRes, err := bucket.DeleteObjects(objectsToDelete)
if err != nil {
log.Fatalf("Failed to delete objects: %v", err)
}
log.Printf("Deleted Objects: %v\n", delRes.DeletedObjects)
// Delete multiple objects and the result is not returned.
objectsToDeleteQuiet := []string{"my-object-3", "my-object-4"}
_, err = bucket.DeleteObjects(objectsToDeleteQuiet, oss.DeleteObjectsQuiet(true))
if err != nil {
log.Fatalf("Failed to delete objects (quiet): %v", err)
}
log.Println("Objects deleted quietly")
}
Delete multiple objects with a specified object name prefix or in a specified directory
The following sample code provides an example on how to delete multiple objects with the specified prefix and how to delete the specified directory and all objects in the directory.
Warning If the prefix is not specified or is set to NULL in the following sample code, all objects in the bucket are deleted. Exercise caution when you specify a prefix in a delete operation.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. Example: examplebucket.
bucket, err := client.Bucket("examplebucket")
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// List all objects whose names contain the specified prefix and delete the objects.
marker := oss.Marker("")
// Specify the prefix of the names of the objects that you want to delete. If you want to delete all objects whose names contain the src prefix, set the prefix to src. After you set the prefix to src, all non-directory objects whose names contain the src prefix, the src directory, and all objects in the src directory are deleted.
prefix := oss.Prefix("src")
// If you want to delete only the src directory and all objects in the directory, set the prefix to src/.
// prefix := oss.Prefix("src/")
var totalDeleted int
for {
lor, err := bucket.ListObjects(marker, prefix)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
objects := make([]string, len(lor.Objects))
for i, object := range lor.Objects {
objects[i] = object.Key
}
// Delete the objects.
delRes, err := bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
if err != nil {
log.Fatalf("Failed to delete objects: %v", err)
}
if len(delRes.DeletedObjects) > 0 {
log.Fatalf("Some objects failed to delete: %v", delRes.DeletedObjects)
}
totalDeleted += len(objects)
// Update the marker.
marker = oss.Marker(lor.NextMarker)
if !lor.IsTruncated {
break
}
}
log.Printf("Success, total deleted object count: %d\n", totalDeleted)
}
References
For more information about the complete sample code that is used to delete objects, visit GitHub.
For more information about the API operation that you can call to delete an object, see DeleteObject.
For more information about the API operation that you can call to delete multiple objects, see DeleteObjects.