Exclua um único objeto, vários objetos por nome, objetos correspondentes a um prefixo ou um diretório inteiro.
Objetos excluídos não podem ser recuperados. Proceda com cautela.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços do Alibaba Cloud na mesma região, utilize um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
O exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, 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.
Excluir um único objeto
O código a seguir exclui um objeto chamado exampleobject.txt de um bucket chamado 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)
}
Excluir vários objetos
Você pode excluir até 1.000 objetos por vez por nome, prefixo ou diretório.
Também é possível configurar regras de ciclo de vida para excluir objetos automaticamente. Para mais informações, consulte Regras de ciclo de vida baseadas na última modificação.
Excluir objetos por nome
Excluir objetos por prefixo ou diretório
Referências
Código de exemplo completo para excluir objetos: GitHub.
Para mais informações sobre a operação de API usada para excluir um objeto, consulte DeleteObject.
Referência da API para excluir vários objetos: DeleteObjects.