Por padrão, a operação GetObject retorna apenas a versão atual de um objeto em um bucket com versionamento ativado.
Informações gerais
Ao chamar a operação GetObject em um bucket, um dos três cenários a seguir ocorre:
Se a versão atual do objeto for um marcador de exclusão, o OSS retorna 404 Not Found.
Caso você especifique o versionId do objeto no parâmetro de consulta, a versão especificada é retornada. Se o versionId for definido como "null", a versão do objeto com versionId nulo é retornada.
Ao tentar recuperar um marcador de exclusão especificando seu versionId, o OSS retorna 405 Method Not Allowed.
Observações
Neste tópico, é utilizado o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros Alibaba Cloud services na mesma região que o OSS, utilize 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 a partir de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para baixar um objeto, você deve ter a permissão
oss:GetObject. Para mais informações, consulte Grant a custom policy.
Código de exemplo
O código a seguir apresenta um exemplo de como baixar um arquivo.
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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
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)
}
var retHeader http.Header
// Download the file of the yourObjectVersionId version to the cache.
// Set yourObjectName to the full path of the object. The full path does not include the bucket name.
objectName := "yourObjectName"
objectVersionId := "yourObjectVersionId"
_, err = bucket.GetObject(objectName, oss.VersionId(objectVersionId), oss.GetResponseHeader(&retHeader))
if err != nil {
log.Fatalf("Failed to get object '%s' with version ID '%s': %v", objectName, objectVersionId, err)
}
// Print x-oss-version-id.
versionId := oss.GetVersionId(retHeader)
log.Printf("x-oss-version-id: %s", versionId)
}
Referências
Para o código de exemplo completo de download de um arquivo, consulte o exemplo no GitHub.
Para mais informações sobre a operação de API utilizada para baixar um arquivo, consulte GetObject.