Ao baixar um único objeto de um bucket, especifique condições de download com base na data da última modificação ou no ETag (identificador do conteúdo do objeto). Se as condições forem atendidas, o sistema baixa o objeto. Caso contrário, retorna um erro e interrompe o download. O download condicional reduz o tráfego de rede e o consumo de recursos, além de aumentar a eficiência.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este exemplo obtém credenciais de acesso de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Este tópico demonstra como criar 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).
O download condicional exige a permissão
oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.
Condições
A tabela a seguir descreve as condições disponíveis para download de objetos.
Use If-Modified-Since e If-Unmodified-Since em conjunto. Da mesma forma, combine If-Match e If-None-Match.
Obtenha o ETag chamando ossClient.getObjectMeta.
|
Parâmetro |
Descrição |
Método de configuração |
|
If-Modified-Since |
Baixa o objeto se a hora especificada for anterior à última modificação. Caso contrário, retorna 304 Not Modified. |
oss.IfModifiedSince |
|
If-Unmodified-Since |
Baixa o objeto se a hora especificada for posterior ou igual à última modificação. Caso contrário, retorna 412 Precondition Failed. |
oss.IfUnmodifiedSince |
|
If-Match |
Baixa o objeto se o ETag especificado corresponder ao ETag do objeto. Caso contrário, retorna 412 Precondition Failed. |
oss.IfMatch |
|
If-None-Match |
Baixa o objeto se o ETag especificado não corresponder ao ETag do objeto. Caso contrário, retorna 304 Not Modified. |
oss.IfNoneMatch |
Exemplos
O código de exemplo a seguir mostra como realizar um download 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)
}
}