No processamento síncrono (x-oss-process), o programa precisa aguardar a conclusão de uma tarefa antes de executar outras. Este tópico descreve como usar o Go SDK V2 para processamento síncrono em cenários como processamento de imagens e documentos.
Observações de uso
O código de exemplo deste tópico usa a região China (Hangzhou) (ID da região:
cn-hangzhou) como referência. Por padrão, o sistema usa um endpoint público. Para acessar o OSS a partir de outros produtos da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints do OSS.Este tópico apresenta um exemplo de obtenção de credenciais de acesso por meio de variáveis de ambiente. Para saber mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Definição do método
func (c *Client) ProcessObject(ctx context.Context, request *ProcessObjectRequest, optFns ...func(*Options)) (*ProcessObjectResult, error)
Parâmetros da solicitação
|
Parâmetro |
Tipo |
Descrição |
|
ctx |
context.Context |
Contexto da solicitação. Use este parâmetro para especificar o tempo total de timeout da solicitação. |
|
request |
*ProcessObjectRequest |
Parâmetros da solicitação para a operação específica da API. Para mais detalhes, consulte ProcessObjectRequest. |
|
optFns |
...func(*Options) |
(Opcional) Parâmetros de configuração no nível da operação. Para mais detalhes, consulte Options. |
Valores de retorno
|
Valor de retorno |
Tipo |
Descrição |
|
result |
*ProcessObjectResult |
Valor retornado pela operação da API. Este parâmetro é válido apenas quando err é nil. Para mais detalhes, consulte ProcessObjectResult. |
|
err |
error |
Status da solicitação. Se a solicitação falhar, err não será nil. |
Código de exemplo
O código de exemplo a seguir demonstra como usar o Go SDK V2 para redimensionar uma imagem e salvar o resultado em um bucket específico.
package main
import (
"context"
"encoding/base64"
"flag"
"fmt"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string
bucketName string
objectName string
)
// The init function is executed before the main function to initialize the program.
func init() {
// Set a command-line parameter to specify the region.
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
// Set a command-line parameter to specify the bucket name.
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
// Set a command-line parameter to specify the name of the image to be processed.
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
flag.Parse() // Parse command-line parameters.
// Check whether the region information is provided. If not, print the default parameters and exit the program.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the bucket name is provided. If not, print the default parameters and exit the program.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the object name is provided. If not, print the default parameters and exit the program.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Create a configuration object, and use environment variables as the credential provider and the specified region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := oss.NewClient(cfg) // Create a new OSS client using the configuration.
// Specify the name of the bucket used to store the processed image. The bucket must be in the same region as the bucket that stores the source image.
targetBucketName := bucketName
// Specify the name of the processed image. If the image is not in the root directory of the bucket, you must include the full path of the file, for example, exampledir/example.jpg.
targetImageName := "exampledir/example.jpg"
// Resize the image to a fixed width and height of 100 px and save it to the specified bucket.
style := "image/resize,m_fixed,w_100,h_100"
process := fmt.Sprintf("%s|sys/saveas,o_%v,b_%v", style, base64.URLEncoding.EncodeToString([]byte(targetImageName)), base64.URLEncoding.EncodeToString([]byte(targetBucketName)))
// Build a ProcessObjectRequest to initiate synchronous processing for a specific object.
request := &oss.ProcessObjectRequest{
Bucket: oss.Ptr(bucketName), // Specify the name of the bucket to operate on.
Key: oss.Ptr(objectName), // Specify the name of the image to process.
Process: oss.Ptr(process), // Specify the processing instruction.
}
// Execute the request to synchronously process the object and receive the return value.
result, err := client.ProcessObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to process object %v", err)
}
log.Printf("process object result:%#v\n", result)
}
Cenários
Adicionar marcas d'água invisíveis a uma imagem
Referências
Para obter mais informações sobre os parâmetros de processamento de imagens, consulte Parâmetros de processamento de imagens.
Para saber mais sobre o recurso de processamento síncrono, consulte Processamento síncrono.
Para detalhes adicionais sobre o processamento síncrono, consulte a operação da API ProcessObject.