De forma predeterminada, la operación GetObject devuelve únicamente la versión actual de un objeto almacenado en un bucket con control de versiones habilitado.
Contexto
Cuando se invoca la operación GetObject en un bucket, ocurre uno de los tres escenarios a continuación:
Si la versión actual del objeto es un marcador de eliminación, OSS devuelve 404 Not Found.
Si especifica el versionId del objeto en el parámetro de consulta, se devuelve la versión indicada. Si establece el versionId como "null", se devuelve la versión del objeto que tiene un versionId nulo.
Si intenta recuperar un marcador de eliminación mediante su versionId, OSS devuelve 405 Method Not Allowed.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Las credenciales de acceso de este tema se obtienen a partir de variables de entorno. Para conocer cómo configurar las credenciales de acceso, consulte Configure access credentials.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para descargar un objeto, debe contar con el permiso
oss:GetObject. Para obtener más información, consulte Grant a custom policy.
Código de ejemplo
A continuación se muestra un ejemplo de código para descargar un archivo.
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)
}
Referencias
Para consultar el código de ejemplo completo sobre cómo descargar un archivo, revise el ejemplo de GitHub.
Para obtener más información sobre la operación de API que se usa para descargar un archivo, consulte GetObject.