Cuando descarga un solo objeto de un bucket, puede especificar condiciones de descarga basadas en la hora de última modificación o en el ETag (el identificador del contenido del objeto). Si se cumplen las condiciones especificadas, se descarga el objeto. En caso contrario, se devuelve un error y no se descarga. La descarga condicional reduce la transmisión por la red y el consumo de recursos, además de mejorar la eficiencia de la descarga.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre 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 conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
La descarga condicional requiere el permiso
oss:GetObject. Para obtener más información, consulte Grant a custom policy.
Condiciones
A continuación se describen las condiciones de descarga de objetos disponibles.
If-Modified-Since e If-Unmodified-Since se pueden usar juntos. También es posible combinar If-Match e If-None-Match.
Obtenga el ETag mediante la llamada a ossClient.getObjectMetadata.
|
Parámetro |
Descripción |
Método de configuración |
|
If-Modified-Since |
Si la hora especificada es anterior a la última modificación del objeto, este se puede descargar. De lo contrario, se devuelve 304 Not Modified. |
oss.IfModifiedSince |
|
If-Unmodified-Since |
Si la hora especificada es posterior o igual a la última modificación del objeto, este se puede descargar. De lo contrario, se devuelve 412 Precondition Failed. |
oss.IfUnmodifiedSince |
|
If-Match |
Si el ETag especificado coincide con el del objeto, este se puede descargar. De lo contrario, se devuelve 412 Precondition Failed. |
oss.IfMatch |
|
If-None-Match |
Si el ETag especificado no coincide con el del objeto, este se puede descargar. De lo contrario, se devuelve 304 Not Modified. |
oss.IfNoneMatch |
Ejemplos
El siguiente código de ejemplo muestra cómo realizar una descarga condicional:
package main
import (
"fmt"
"os"
"time"
"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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of your bucket.
bucket, err := client.Bucket("yourBucketName")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// For example, an object was last modified at 18:43:02, on November 21, 2023. If the specified time is earlier than the last modified time, the object meets the If-Modified-Since condition and the object is downloaded.
date := time.Date(2023, time.November, 21, 10, 40, 02, 0, time.UTC)
// The object is not downloaded if it does not meet the specified conditions.
// Specify the full path of the object. Do not include the bucket name in the full path.
err = bucket.GetObjectToFile("yourObjectName", "LocalFile", oss.IfUnmodifiedSince(date))
if err == nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// The object is downloaded if it meets the specified conditions.
err = bucket.GetObjectToFile("yourObjectName", "LocalFile", oss.IfModifiedSince(date))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}