Em buckets com versionamento ativado, o OSS permite exclusões temporárias e permanentes de objetos. O tipo de exclusão depende da especificação de um versionId. Esse recurso possibilita excluir um único objeto, vários objetos ou objetos com um prefixo específico.
Observações
Este tópico usa 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, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
Para excluir um objeto, você precisa da permissão
oss:DeleteObject. Para mais detalhes, consulte Conceder uma política personalizada.
Comportamento de exclusão com versionamento
Esta seção descreve o comportamento de exclusão de objetos quando o versionamento está ativado.
-
Sem especificar um versionId (exclusão temporária):
Ao executar uma operação de exclusão sem especificar um
versionId, a versão atual do objeto não é removida. Em vez disso, o OSS insere um marcador de exclusão para a versão atual. Durante uma operaçãoGetObject, o OSS identifica 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.O valor
trueparax-oss-delete-markerindica que a versão correspondente aox-oss-version-idretornado é um marcador de exclusão.Para saber como restaurar um objeto excluído temporariamente, consulte Restaurar arquivos.
-
Especificando um versionId (exclusão permanente):
Se você especificar um
versionIddurante a exclusão, o OSS remove permanentemente a versão correspondente ao parâmetroversionIdemparams. Para excluir a versão com ID "null", adicioneparams['versionId'] = "null"ao parâmetroparams.
Exemplos de código
Excluir um único arquivo
Os exemplos de código a seguir mostram como excluir permanentemente e temporariamente um único objeto.
Excluir um objeto especificando um versionId
O código abaixo demonstra como excluir permanentemente um objeto ao especificar 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 ilustra como excluir temporariamente um objeto sem informar 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 demonstram como excluir permanentemente ou temporariamente vários objetos ou marcadores de exclusão.
Excluir permanentemente vários objetos especificando versionIds
Este exemplo mostra como remover permanentemente vários objetos por meio de 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 eliminar definitivamente vários marcadores de exclusão informando 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.")
}
Excluir temporariamente vários objetos sem especificar versionIds
O exemplo abaixo demonstra como aplicar a exclusão temporária em vários objetos sem fornecer os 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 obter mais informações sobre a operação de API usada para excluir um único objeto, consulte DeleteObject.
Para obter mais informações sobre a operação de API usada para excluir uma versão específica de um objeto, consulte DeleteObjectVersions.