Para buckets com versionamento ativado, o OSS oferece suporte à exclusão reversível (soft delete) e à exclusão permanente de objetos. O tipo de exclusão depende de você especificar ou não um versionId. Esse recurso permite excluir um único objeto, vários objetos ou objetos com um prefixo específico.
Observações
Neste tópico, usamos o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Neste tópico, as credenciais de acesso são obtidas por meio de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.
Este tópico demonstra como criar uma instância OSSClient usando um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para excluir um objeto, você precisa ter a permissão
oss:DeleteObject. Para mais informações, consulte Grant a custom policy.
Comportamento de exclusão com versionamento
Esta seção descreve o comportamento de exclusão de objetos quando o versionamento está ativado.
-
Se você não especificar um versionId (exclusão reversível):
Ao executar uma operação de exclusão sem especificar um
versionId, a versão atual do objeto não é excluída. Em vez disso, o OSS insere um marcador de exclusão para a versão atual. Ao executar uma operaçãoGetObject, o OSS detecta que a versão atual é um marcador de exclusão e retorna404 Not Found. A resposta também inclui o cabeçalhox-oss-delete-marker = truee o número da versão do novo marcador de exclusão emx-oss-version-id.Um valor
trueemx-oss-delete-markerindica que a versão correspondente aox-oss-version-idretornado é um marcador de exclusão.Para mais informações sobre como restaurar um objeto com exclusão reversível, consulte Restore files.
-
Se você especificar um versionId (exclusão permanente):
Ao especificar um
versionIddurante uma operação de exclusão, o OSS exclui permanentemente a versão correspondente ao parâmetroversionIdemparams. Para excluir a versão com ID "null", adicioneparams['versionId'] = "null"ao parâmetroparams.
Código de exemplo
Excluir um único arquivo
Os exemplos de código a seguir mostram como excluir um único objeto de forma permanente e reversível.
Excluir um objeto especificando um versionId
O código a seguir mostra como excluir permanentemente um objeto especificando um 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.")
}
Excluir um objeto sem especificar um versionId
O código a seguir mostra como aplicar a exclusão reversível a um objeto sem especificar um 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.")
}
Excluir vários arquivos
Os exemplos de código a seguir mostram como excluir vários objetos ou marcadores de exclusão de forma permanente e reversível.
Excluir permanentemente vários objetos especificando versionIds
O código a seguir mostra como excluir permanentemente vários objetos especificando seus versionIds:
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.")
}
Excluir permanentemente vários marcadores de exclusão especificando versionIds
O código a seguir mostra como excluir permanentemente vários marcadores de exclusão especificando seus versionIds:
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.")
}
Exclusão reversível de vários objetos sem especificar versionIds
O código a seguir mostra como aplicar a exclusão reversível a vários objetos sem especificar seus versionIds:
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.")
}
Referências
Para mais informações sobre a operação de API para excluir um único objeto, consulte DeleteObject.
Para mais informações sobre a operação de API para excluir uma versão específica de um objeto, consulte DeleteObjectVersions.