Todos os produtos
Search
Central de documentação

Object Storage Service:Escreva um handler de requisição GetObject

Última atualização: Jul 03, 2026

Ao usar um Object FC Access Point para chamar a operação GetObject, o Function Compute aciona a função vinculada. Chame a operação WriteGetObjectResponse na função para retornar apenas dados e cabeçalhos de resposta personalizados.

Procedimento

Este guia pressupõe que seu Object FC Access Point esteja configurado para invocar uma função do Function Compute para requisições GetObject. O Function Compute inclui a operação de API WriteGetObjectResponse, que permite à função fornecer uma resposta personalizada ao chamador de GetObject. Essa operação oferece controle abrangente sobre o código de status, os cabeçalhos de resposta e o corpo da resposta.

Use WriteGetObjectResponse para retornar um objeto totalmente transformado, parte dele ou uma resposta completamente diferente, conforme a lógica da sua aplicação.

Os exemplos a seguir demonstram como usar a operação de API WriteGetObjectResponse.

Exemplo: Responder com uma imagem transformada

  1. Compile uma função para processar requisições GetObject.

    Em algumas operações, como transformações de imagem, talvez seja necessário buscar todo o objeto de origem antes do processamento. Nesses casos, use WriteGetObjectResponse para retornar o objeto transformado completo à aplicação chamadora em uma única resposta.

    Java

    A versão do OSS SDK for Java deve ser 3.17.2 ou posterior.

    import com.aliyun.fc.runtime.Context;
    import com.aliyun.fc.runtime.Credentials;
    import com.aliyun.fc.runtime.StreamRequestHandler;
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.ObjectMetadata;
    import com.aliyun.oss.model.VoidResult;
    import com.aliyun.oss.model.WriteGetObjectResponseRequest;
    import org.codehaus.jettison.json.JSONException;
    import org.codehaus.jettison.json.JSONObject;
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Scanner;
    
    public class Example1 implements StreamRequestHandler {
        // In this example, the endpoint of the China (Qingdao) region is used. 
        String endpoint = "https://oss-cn-qingdao.aliyuncs.com";
        private static int status = 200;
    
        public static String convertToString(InputStream inputStream) {
            Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
            return scanner.hasNext() ?  scanner.next() : "";
        }
    
        @Override
        public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
            Credentials creds = context.getExecutionCredentials();
            // Obtain the AccessKey pair from the context. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());
    
            try {
                String result = convertToString(inputStream);
                JSONObject jsonObject = new JSONObject(result);
                String route = jsonObject.getJSONObject("getObjectContext").getString("outputRoute");
                String token = jsonObject.getJSONObject("getObjectContext").getString("outputToken");
                // Call BufferedImage to create an image object that has a resolution of 200 × 200 pixels and draw a red rectangle for the object. 
                // Write content to the body of the WriteGetObjectResponse request. 
                BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = image.createGraphics();
                graphics.setColor(Color.RED);
                graphics.fillRect(0, 0, 200, 200);
                graphics.dispose();
    
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                WriteGetObjectResponseRequest writeGetObjectResponseRequest = new WriteGetObjectResponseRequest(route, token, status,new ByteArrayInputStream(baos.toByteArray()));
    
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(baos.size());
                writeGetObjectResponseRequest.setMetadata(metadata);
    
                VoidResult voidResult = ossClient.writeGetObjectResponse(writeGetObjectResponseRequest);
                System.out.println("getRequestId:"+voidResult.getRequestId());
                System.out.println("status:"+voidResult.getResponse().getStatusCode());
                System.out.println("Headers:"+voidResult.getResponse().getHeaders().toString());
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message: " + oe.getMessage());
                System.out.println("Error Code:       " + oe.getErrorCode());
                System.out.println("Request ID:      " + oe.getRequestId());
                System.out.println("Host ID:           " + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                ossClient.shutdown();
            }
        }
    }
    

    Python

    A versão do OSS SDK for Python deve ser 2.18.3 ou posterior.

    # -*- coding: utf-8 -*-
    import io
    from PIL import Image
    import oss2
    import json
    
    # The endpoint of the China (Qingdao) region is used in this example.
    endpoint = 'http://oss-cn-qingdao.aliyuncs.com'
    fwd_status = '200'
    
    # FC function entry
    def handler(event, context):
        evt = json.loads(event)
        creds = context.credentials
        # Remember to include the security token.
        auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)
    
        headers = dict() 
        event_ctx = evt["getObjectContext"]
        route = event_ctx["outputRoute"]
        token = event_ctx["outputToken"]
        print(evt)
    
        endpoint = route
        service = oss2.Service(auth, endpoint)
        # Create a 200x200 pixel image and fill it with red color.
        # After the transformation, write the content to the body of the write_get_object_response request.
        image = Image.new('RGB', (200, 200), color=(255, 0, 0))
        transformed = io.BytesIO()
        image.save(transformed, "png")
    
        resp = service.write_get_object_response(route, token, fwd_status, transformed.getvalue(), headers)
    
        print('status: {0}'.format(resp.status))
        print(resp.headers)
    
        return 'success'

    Go

    A versão do OSS SDK for Go deve ser 1.2.2 ou posterior.

    package main
    
    import (
      "bytes"
      "context"
      "fmt"
      "github.com/aliyun/aliyun-oss-go-sdk/oss"
      "github.com/aliyun/fc-runtime-go-sdk/fc"
      "github.com/aliyun/fc-runtime-go-sdk/fccontext"
      "image"
      "image/color"
      "image/draw"
      "image/png"
    )
    // Specify the GetObjectContext structure, which contains the output route (outputRoute), output token (outputToken), and input OSS URL(inputOssUrl). 
    type GetObjectContext struct {
      OutputRoute string `json:"outputRoute"`
      OutputToken string `json:"outputToken"`
    }
    // Specify the StructEvent structure to receive the event data that triggers the function. 
    type StructEvent struct {
      GetObjectContext GetObjectContext `json:"getObjectContext"`
    }
    // Specify the HandleRequest function to process computing logic. 
    func HandleRequest(ctx context.Context, event StructEvent) error {
      fmt.Printf("event:%#v\n", event)
      endpoint := event.GetObjectContext.OutputRoute
      fwdStatus := "200"
      fctx, _ := fccontext.FromContext(ctx)
      // Obtain the AccessKey pair from the context. 
      client, err := oss.New(endpoint, fctx.Credentials.AccessKeyId, fctx.Credentials.AccessKeySecret, oss.SecurityToken(fctx.Credentials.SecurityToken), oss.AuthVersion(oss.AuthV4), oss.Region("cn-qingdao"))
      if err != nil {
        return fmt.Errorf("client new error: %v", err)
      }
      params := map[string]interface{}{}
      params["x-oss-write-get-object-response"] = nil
    
      // Create an image object that has a resolution of 200 × 200 pixels and draw a red rectangle for the object. 
      img := image.NewRGBA(image.Rect(0, 0, 200, 200))
      red := color.RGBA{255, 0, 0, 255}
      draw.Draw(img, img.Bounds(), &image.Uniform{red}, image.Point{}, draw.Src)
    
      // Save the image in the PNG format. 
      var buf bytes.Buffer
      err = png.Encode(&buf, img)
      if err != nil {
        return fmt.Errorf("png encode error: %v", err)
      }
      reader := bytes.NewReader(buf.Bytes())
      // Use the OSS client to upload the converted image by sending a POST request, and specify specific HTTP headers, such as x-oss-request-route, to facilitate the identification and processing of special forwarding requests. 
      headers := make(map[string]string)
      headers["x-oss-request-route"] = event.GetObjectContext.OutputRoute
      headers["x-oss-request-token"] = event.GetObjectContext.OutputToken
      headers["x-oss-fwd-status"] = fwdStatus
      resp, err := client.Conn.Do("POST", "", "", params, headers, reader, 0, nil)
      if err != nil {
        return fmt.Errorf("client conn do error: %v", err)
      }
      fmt.Println("status:", resp.StatusCode)
      fmt.Println(resp.Headers)
    
      return nil
    }
    // Call fc.Start(HandleRequest) to register and run the HandleRequest function and wait for and process the event triggers of Alibaba Cloud Function Compute. 
    func main() {
      fc.Start(HandleRequest)
    }
  2. Implante a função.

    Java

    1. Descompacte o arquivo .jar.

    2. Faça upload do arquivo .jar para o console do Function Compute.

      1. Faça login no console do Function Compute e clique em Back to Function Compute 2.0 no canto superior direito.

      2. No painel de navegação à esquerda, clique em Services & Functions.

      3. Na barra de navegação superior, selecione a região China (Qingdao).

      4. Na página Services, clique no serviço desejado e, em seguida, na função que usa o runtime Java 11.

      5. Na página de detalhes da função, escolha Upload Code > Upload JAR Package.

      6. Na caixa de diálogo, selecione o arquivo .jar empacotado, marque Deploy the function after the files are selected. e clique em Save and Deploy.

    3. Modifique o handler da função com base na função de exemplo.

      1. Na página de detalhes da função, clique na aba Configurations.

      2. Na seção Environment Information, clique em Modify.

      3. Altere o Handler.

        Se o runtime for Java, o valor atual estará no formato [package].[class]::[method]. Caso o valor atual seja example.HelloFC::handleRequest, o sistema invocará a função handleRequest da classe HelloFC no pacote example. Modifique o valor atual com base na função de exemplo real. Exemplo: com.aliyun.sts.sample.Example1::handleRequest.

    Python

    1. Faça login no console do Function Compute e clique em Back to Function Compute 2.0 no canto superior direito.

    2. No painel de navegação à esquerda, clique em Services & Functions.

    3. Na barra de navegação superior, selecione a região China (Qingdao).

    4. Na página Services, clique no serviço desejado e, em seguida, na função que usa o runtime Python 3.10.

    5. Na página de detalhes da função, clique na aba Code e escolha .

    6. No painel TERMINAL, execute o comando a seguir para atualizar a versão do OSS SDK for Python:

      pip install oss2 -t .
    7. Substitua o exemplo de código em index.py por um exemplo de função Python para lidar com requisições GetObject e clique em Deploy Function.

    Go

    1. Instale o ambiente de runtime do OSS SDK for Go.

    2. Compile o pacote de código. Para obter mais informações, consulte Compilar e empacotar código no Linux ou macOS.

      Durante a compilação, substitua o arquivo de compilação main.go pela função de exemplo usada para processar requisições GetObject fornecida na etapa anterior.

    3. Faça upload do arquivo binário compilado como um pacote ZIP para uma função com o Runtime Go 1 e configure o handler da função. Para obter mais informações, consulte Configurar um handler de função do FC.

Próximos passos

Usar Object FC Access Points