Todos os produtos
Search
Central de documentação

Object Storage Service:Excluir objetos (OSS SDK for Go 1.0)

Última atualização: Jul 03, 2026

Exclua um único objeto, vários objetos por nome, objetos correspondentes a um prefixo ou um diretório inteiro.

Aviso

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

Código de exemplo para excluir vários objetos por nome:

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")
}

Excluir objetos por prefixo ou diretório

Código de exemplo para excluir objetos por prefixo de nome ou remover um diretório inteiro e seu conteúdo.

Aviso

Se o prefixo não for especificado ou for definido como NULL, todos os objetos no bucket serão excluídos. Tenha cuidado ao especificar um prefixo em uma operação de exclusão.

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)
}

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.