Todos los productos
Search
Centro de documentos

Object Storage Service:Callbacks de carga (OSS SDK for Go 1.0)

Última actualización: Sep 22, 2026

Object Storage Service (OSS) puede enviar callbacks a su servidor de aplicaciones cuando finalizan las operaciones de carga simple (PutObject y PutObjectFromFile) y de carga multiparte (UploadFile). Para habilitar los callbacks de carga, agregue los parámetros de callback obligatorios a la solicitud de carga enviada a OSS.

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 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).

Ejemplos

A continuación se muestra cómo configurar callbacks de carga al cargar una cadena de texto en el objeto exampleobject.txt, ubicado en el directorio examplefiles del bucket examplebucket:

package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"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 the bucket. Example: examplebucket. 
	bucket, err := client.Bucket("examplebucket")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Specify custom callback parameters. 
	callbackUrl := "http://your.callback.server.address" // Specify the URL of the callback server. 
	callbackMap := map[string]string{
		"callbackUrl": callbackUrl, // Specify the URL of the callback server. 
		"callbackBody": "bucket=${bucket}&object=${object}", // Specify the callback request body. 
		"callbackBodyType": "application/x-www-form-urlencoded", // Specify the type of the callback request body. 
	}

	// Convert the configurations of the callback parameters to a JSON string and encode the string in Base64. 
	callbackStr, err := json.Marshal(callbackMap)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	callbackBase64 := base64.StdEncoding.EncodeToString(callbackStr)

	// Specify the upload callback parameters. 
	options := []oss.Option{
		oss.Callback(callbackBase64),
	}

	// Construct a string that consists of 1024 x 1024 "a" character. 
	content := strings.Repeat("a", 1024*1024)

	// Upload the string. Do not include the bucket name in the object path. 
	objectPath := "examplefiles/exampleobject.txt"
	err = bucket.PutObject(objectPath, strings.NewReader(content), options...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// A message which indicates the object is uploaded is returned. 
	fmt.Println("Object uploaded with callback successfully.")
}

Referencias

  • Para consultar el código de ejemplo completo de los callbacks de carga, visite GitHub.

  • Para obtener más información sobre la operación de API correspondiente a los callbacks de carga, consulte Callback.