Tous les produits
Search
Centre de documentation

Object Storage Service:Data validation (Go SDK V1)

Dernière mise à jour :Sep 24, 2026

Le SDK OSS pour Go utilise la vérification MD5 et CRC-64 afin de garantir l'intégrité des données lors du chargement, du téléchargement et de la copie d'objets.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configurer un client (Go SDK V1).

Validation MD5

Lorsque vous chargez un fichier, spécifiez l'en-tête Content-MD5 pour garantir l'intégrité et l'exactitude des données. OSS calcule le hachage MD5 des données reçues. Si le hachage calculé ne correspond pas au hachage fourni, OSS renvoie une exception InvalidDigest. En cas d'exception InvalidDigest, vérifiez si le fichier a été modifié ou corrompu pendant la transmission, puis rechargez-le.

Remarque

Les opérations putObject, getObject, appendObject, postObject et uploadPart prennent en charge la validation MD5.

L'exemple de code suivant montre comment valider les données par MD5 lors du chargement d'un fichier.

package main

import (
	"crypto/md5"
	"encoding/base64"
	"log"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Calculate the MD5 checksum for the given content.
func calculateMD5(content string) string {
	h := md5.New()
	h.Write([]byte(content))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

func main() {
	// Load OSS access credentials from environment variables.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Replace with your actual bucket name.
	bucketName := "yourBucketName"

	// Create an OSS client.
	// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set it to cn-hangzhou. For other regions, use the actual region ID.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Get the specified bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket %s: %v", bucketName, err)
	}

	// The content to upload.
	content := "yourObjectValue"   // Replace with the actual content to upload.
	objectName := "yourObjectName" // Replace with the actual object name.

	// Calculate the MD5 checksum of the content.
	contentMD5 := calculateMD5(content)

	// Upload the file to OSS.
	err = bucket.PutObject(objectName, strings.NewReader(content), oss.ContentMD5(contentMD5))
	if err != nil {
		log.Fatalf("Failed to upload object %s: %v", objectName, err)
	}

	log.Printf("Object '%s' uploaded successfully.", objectName)
}

Validation CRC-64

Remarque

Remarques sur la validation CRC-64 :

  • Les opérations putObject, getObject, appendObject et uploadPart prennent en charge la validation CRC-64.

  • La validation des données CRC est activée par défaut pour les chargements, les téléchargements et les copies de fichiers. Si la valeur CRC calculée par le client ne correspond pas à la valeur renvoyée par le serveur, une erreur est retournée.

  • Les téléchargements partiels (range downloads) ne prennent pas en charge la validation CRC-64.

  • L'activation de la validation CRC-64 consomme des ressources CPU et affecte les vitesses de chargement et de téléchargement.

L'exemple de code suivant montre comment valider l'intégrité des données par CRC-64 lors de l'ajout de données à un objet.

package main

import (
	"log"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before running this code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set it to cn-hangzhou. For other regions, use the actual region ID.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Set yourBucketName to the name of your bucket.
	bucketName := "yourBucketName" // Replace with your actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket %s: %v", bucketName, err)
	}

	// Define the name of the object to which data will be appended.
	objectName := "yourObjectName" // Replace with the actual object name.

	// The position for the first append operation is 0. The return value indicates the position for the next append operation. Subsequent append positions are the length of the file before the append.
	request := &oss.AppendObjectRequest{
		ObjectKey: objectName,
		Reader:    strings.NewReader("YourObjectAppendValue1"),
		Position:  0,
	}

	// For the first append operation, initialize the CRC value to 0.
	options := []oss.Option{oss.InitCRC(0)}
	result, err := bucket.DoAppendObject(request, options)
	if err != nil {
		log.Fatalf("Failed to append object %s for the first time: %v", objectName, err)
	}
	log.Printf("First append successful. Next position: %d", result.NextPosition)

	// The position for the second append operation starts from the length returned by the first operation.
	request = &oss.AppendObjectRequest{
		ObjectKey: objectName,
		Reader:    strings.NewReader("YourObjectAppendValue2"),
		Position:  result.NextPosition,
	}

	// The initial CRC value for the second append operation is the return value from the first operation.
	options = []oss.Option{oss.InitCRC(result.CRC)}
	result, err = bucket.DoAppendObject(request, options)
	if err != nil {
		log.Fatalf("Failed to append object %s for the second time: %v", objectName, err)
	}
	log.Printf("Second append successful. Next position: %d", result.NextPosition)

	// You can perform multiple AppendObject operations.
	log.Printf("All appends completed successfully.")
}