En los buckets con el control de versiones habilitado, OSS admite la eliminación temporal y la eliminación permanente de objetos. El tipo de eliminación depende de si se especifica un versionId. Esta función permite eliminar un solo objeto, varios objetos o aquellos que comparten un prefijo específico.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Las credenciales de acceso de este tema se obtienen de variables de entorno. Para conocer cómo configurar las credenciales de acceso, consulte Configure access credentials.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para eliminar un objeto, debe contar con el permiso
oss:DeleteObject. Para obtener más información, consulte Grant a custom policy.
Comportamiento de eliminación con control de versiones
Esta sección describe cómo se eliminan los objetos cuando el control de versiones está habilitado.
-
Si no se especifica un versionId (eliminación temporal):
Cuando se ejecuta una operación de eliminación sin especificar un
versionId, la versión actual del objeto no se borra. En su lugar, OSS inserta un marcador de eliminación para dicha versión. Al ejecutar la operaciónGetObject, OSS detecta que la versión actual es un marcador de eliminación y devuelve404 Not Found. La respuesta también incluye el encabezadox-oss-delete-marker = truey el número de versión del nuevo marcador de eliminación enx-oss-version-id.El valor
trueenx-oss-delete-markerindica que la versión correspondiente alx-oss-version-iddevuelto es un marcador de eliminación.Para conocer cómo restaurar un objeto eliminado temporalmente, consulte Restore files.
-
Si se especifica un versionId (eliminación permanente):
Al especificar un
versionIddurante una operación de eliminación, OSS elimina permanentemente la versión que corresponde al parámetroversionIddentro deparams. Para eliminar la versión con el identificador "null", agregueparams['versionId'] = "null"al parámetroparams.
Código de ejemplo
Eliminar un solo archivo
A continuación se muestran ejemplos de código para eliminar de forma permanente o temporal un solo objeto.
Eliminar un objeto al especificar un versionId
El siguiente código muestra cómo eliminar permanentemente un objeto al especificar un versionId:
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, 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.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set yourBucketName to the name of the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Set youObjectName to the full path of the object. Do not include the bucket name.
// Set yourObjectVersionId to the versionId of the object. After you specify the versionId, the object of this version is permanently deleted.
objectName := "yourObjectName"
objectVersionId := "yourObjectVersionId"
err = bucket.DeleteObject(objectName, oss.VersionId(objectVersionId))
if err != nil {
log.Fatalf("Failed to delete object '%s' with version ID '%s': %v", objectName, objectVersionId, err)
}
log.Println("Object deleted successfully.")
}
Eliminar un objeto sin especificar un versionId
El siguiente código muestra cómo eliminar temporalmente un objeto sin especificar un versionId:
package main
import (
"log"
"net/http"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this 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.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set yourBucketName to the name of the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Soft delete the object without specifying a versionId. This operation adds a delete marker to the object.
// Set youObjectName to the full path of the object. Do not include the bucket name.
objectName := "yourObjectName"
var retHeader http.Header
err = bucket.DeleteObject(objectName, oss.GetResponseHeader(&retHeader))
if err != nil {
log.Fatalf("Failed to delete object '%s': %v", objectName, err)
}
// Print the delete marker information.
log.Printf("x-oss-version-id: %s", oss.GetVersionId(retHeader))
log.Printf("x-oss-delete-marker: %t", oss.GetDeleteMark(retHeader))
log.Println("Object deleted successfully.")
}
Eliminar varios archivos
Los siguientes ejemplos de código muestran cómo eliminar de forma permanente o temporal varios objetos o marcadores de eliminación.
Eliminar permanentemente varios objetos al especificar versionIds
El siguiente código muestra cómo eliminar permanentemente varios objetos al especificar sus versionId:
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, 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.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set yourBucketName to the name of the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Specify the versionIds of the objects to be permanently deleted.
keyArray := []oss.DeleteObject{
{Key: "objectName1", VersionId: "objectVersionId1"},
{Key: "objectName2", VersionId: "objectVersionId2"},
}
// Delete the specified object versions.
ret, err := bucket.DeleteObjectVersions(keyArray)
if err != nil {
log.Fatalf("Failed to delete objects: %v", err)
}
// Print the information about the deleted objects.
for _, object := range ret.DeletedObjectsDetail {
log.Printf("Key: %s, VersionId: %s", object.Key, object.VersionId)
}
log.Println("Objects deleted successfully.")
}
Eliminar permanentemente varios marcadores de eliminación al especificar versionIds
El siguiente código muestra cómo eliminar permanentemente varios marcadores de eliminación al especificar sus versionId:
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, 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.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set yourBucketName to the name of the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Specify the version information of the delete markers.
keyArray := []oss.DeleteObject{
{Key: "objectName1", VersionId: "objectVersionId1"},
{Key: "objectName2", VersionId: "objectVersionId2"},
}
// Permanently delete multiple delete markers by specifying their versionIds.
ret, err := bucket.DeleteObjectVersions(keyArray)
if err != nil {
log.Fatalf("Failed to delete objects: %v", err)
}
// Print the information about the deleted objects and delete markers.
for _, object := range ret.DeletedObjectsDetail {
log.Printf("Key: %s, VersionId: %s, DeleteMarker: %t, DeleteMarkerVersionId: %s",
object.Key, object.VersionId, object.DeleteMarker, object.DeleteMarkerVersionId)
}
log.Println("Objects deleted successfully.")
}
Eliminar temporalmente varios objetos sin especificar versionIds
El siguiente código muestra cómo eliminar temporalmente varios objetos sin especificar sus versionId:
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, 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.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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)
}
// Set yourBucketName to the name of the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Soft delete multiple objects without specifying their versionIds. This operation adds delete markers to the objects.
keyArray := []oss.DeleteObject{
{Key: "objectName1"},
{Key: "objectName2"},
}
// Execute the delete operation.
res, err := bucket.DeleteObjectVersions(keyArray)
if err != nil {
log.Fatalf("Failed to delete objects: %v", err)
}
// Print the delete markers of the objects.
for _, object := range res.DeletedObjectsDetail {
log.Printf("Key: %s, DeleteMarker: %t, DeleteMarkerVersionId: %s",
object.Key, object.DeleteMarker, object.DeleteMarkerVersionId)
}
log.Println("Objects deleted successfully.")
}
Referencias
Para obtener más información sobre la operación de API que elimina un solo objeto, consulte DeleteObject.
Para obtener más información sobre la operación de API que elimina una versión específica de un objeto, consulte DeleteObjectVersions.