Le client Go pour Object Storage Service (OSS) permet de gérer les ressources OSS, telles que les buckets et les fichiers. Pour envoyer une requête OSS avec le SDK Go, vous devez initialiser une instance de client. Vous pouvez également modifier la configuration par défaut selon vos besoins.
Prérequis
Avant d'initialiser le SDK OSS, configurez vos identifiants d'accès. Pour plus d'informations, consultez la rubrique Configurer les identifiants d'accès (Go SDK V1).
Créer un nouveau client
Signature V4 (recommandée)
Nous vous recommandons d'utiliser l'algorithme de signature V4, plus sécurisé. Lors de l'initialisation du client avec une signature V4, spécifiez l'endpoint et l'ID de région Alibaba Cloud standard. L'ID de région indique la région depuis laquelle la requête est émise, par exemple cn-hangzhou. Déclarez également oss.AuthV4. Les signatures V4 sont prises en charge à partir de la version 3.0.2 du SDK Go OSS.
L'exemple suivant montre comment initialiser un client avec une signature V4 en utilisant un nom de domaine OSS. Adaptez cet exemple à d'autres scénarios, tels que l'initialisation du client avec un nom de domaine personnalisé.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
// endpoint - The endpoint corresponding to the Bucket.
// region - The region information corresponding to the endpoint.
//
// Returns the created OSS client instance.
func setupClient(endpoint, region string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance and use V4 signature.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region(region))
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Fill in yourEndpoint with the endpoint corresponding to the Bucket. For example, for China East 1 (Hangzhou), fill in https://oss-cn-hangzhou.aliyuncs.com. For other regions, fill in according to the actual situation.
endpoint := "yourEndpoint"
// Fill in yourRegion with the region information corresponding to the endpoint, for example, cn-hangzhou.
region := "yourRegion"
// Check if environment variables are set, checking both empty strings and placeholder values.
if endpoint == "" || region == "" || endpoint == "yourEndpoint" || region == "yourRegion" {
log.Fatal("Please set yourEndpoint and yourRegion with valid values.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint, region)
if err != nil {
handleError(err)
}
// Output client information.
log.Printf("Client: %#v\n", client)
}
Signature V1 (non recommandée)
Créer un nouveau client en utilisant un nom de domaine OSS
Le code suivant montre comment initialiser un client en utilisant un nom de domaine OSS. Pour plus d'informations sur les noms de domaine OSS pour différentes régions, consultez la rubrique Régions et endpoints.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
//
// endpoint - The endpoint corresponding to the Bucket.
//
// Returns the created OSS client instance.
func setupClient(endpoint string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance.
// Fill in yourRegion with the region where the Bucket is located. For example, for China East 1 (Hangzhou), fill in cn-hangzhou. For other regions, fill in according to the actual situation.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set signature version
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New(endpoint, "", "", clientOptions...)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Fill in yourEndpoint with the endpoint corresponding to the Bucket. For example, for China East 1 (Hangzhou), fill in https://oss-cn-hangzhou.aliyuncs.com. For other regions, fill in according to the actual situation.
endpoint := "yourEndpoint"
// Check if environment variables are set.
if endpoint == "" {
log.Fatal("Please set yourEndpoint.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint)
if err != nil {
handleError(err)
}
// Output client information.
log.Printf("Client: %#v\n", client)
}
Créer un nouveau client en utilisant un nom de domaine personnalisé
Le code suivant montre comment créer un nouveau client en utilisant un nom de domaine personnalisé. Pour plus d'informations sur l'accès à OSS via un nom de domaine personnalisé, consultez la rubrique Accéder à OSS avec un nom de domaine personnalisé.
Vous ne pouvez pas utiliser la méthode ossClient.listBuckets avec un nom de domaine personnalisé.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance that supports CNAME.
// Parameters:
//
// endpoint - The custom domain name that is attached to the bucket.
//
// Returns the created OSS client instance.
func setupClient(endpoint string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance and enable CNAME support.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
clientOptions = append(clientOptions, oss.UseCname(true))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New(endpoint, "", "", clientOptions...)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Set yourEndpoint to the custom domain name of the bucket.
// Example: "custom-domain-for-your-bucket.com".
endpoint := "yourEndpoint"
// Check if the environment variables are set.
if endpoint == "" {
log.Fatal("Please set yourEndpoint.")
}
// Set up and create an OSS client instance that supports CNAME.
client, err := setupClient(endpoint)
if err != nil {
handleError(err)
}
// Print the client information.
log.Printf("Client: %#v\n", client)
}
Configurer le client
Configurez les paramètres du client, tels que le proxy, le délai de connexion et le nombre maximal de connexions.
Paramètre | Description | Méthode |
MaxIdleConns | Nombre maximal de connexions inactives. Valeur par défaut : 100. | oss.MaxConns |
MaxIdleConnsPerHost | Nombre maximal de connexions inactives par hôte. Valeur par défaut : 100. | oss.MaxConns |
MaxConnsPerHost | Nombre maximal de connexions par hôte. La valeur par défaut est vide. | oss.MaxConns |
ConnectTimeout | Délai d'attente HTTP en secondes. Valeur par défaut : 10 secondes. Une valeur de 0 signifie qu'il n'y a pas de délai d'attente. | oss.Timeout |
ReadWriteTimeout | Délai d'attente de lecture ou d'écriture HTTP en secondes. Valeur par défaut : 20 secondes. Une valeur de 0 signifie qu'il n'y a pas de délai d'attente. | oss.Timeout |
IsCname | Indique s'il faut utiliser un nom de domaine personnalisé comme endpoint. Cette fonctionnalité est désactivée par défaut. | oss.UseCname |
UserAgent | Définit l'en-tête User-Agent pour les requêtes HTTP. Valeur par défaut : aliyun-sdk-go. | oss.UserAgent |
ProxyHost | Indique s'il faut activer l'adresse hôte et le port du serveur proxy. Valeurs possibles :
| oss.AuthProxy |
ProxyUser | Nom d'utilisateur pour l'authentification auprès du serveur proxy. | oss.AuthProxy |
ProxyPassword | Mot de passe pour l'authentification auprès du serveur proxy. | oss.AuthProxy |
RedirectEnabled | Indique s'il faut activer la redirection HTTP. Valeurs possibles :
| oss.RedirectEnabled |
InsecureSkipVerify | Indique s'il faut activer la validation des certificats SSL. Valeurs possibles :
| oss.InsecureSkipVerify |
IsEnableCRC | Indique s'il faut activer la validation des données CRC. Valeurs possibles :
| oss.EnableCRC |
LogLevel | Définit le mode de journalisation. Valeurs possibles :
| oss.SetLogLevel |
Le code suivant fournit un exemple de configuration :
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
//
// endpoint - The Endpoint of the bucket.
//
// Returns the created OSS client instance.
func setupClient(endpoint string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Set the maximum number of connections to 10, the maximum number of idle connections per host to 20, and the maximum number of connections per host to 20.
conn := oss.MaxConns(10, 20, 20)
// Set the HTTP connection timeout to 20 seconds and the HTTP read/write timeout to 60 seconds.
time := oss.Timeout(20, 60)
// Specify whether to use a custom domain name as the Endpoint. The default value is false.
cname := oss.UseCname(true)
// Set the User-Agent header for HTTP requests. The default value is aliyun-sdk-go.
userAgent := oss.UserAgent("aliyun-sdk-go")
// Specify whether to enable HTTP redirection. The default value is true.
redirect := oss.RedirectEnabled(true)
// Specify whether to enable SSL certificate validation. The default value is to skip validation.
verifySsl := oss.InsecureSkipVerify(false)
// Set the address and port of the proxy server.
// proxy := oss.Proxy("yourProxyHost")
// Set the host address and port of the proxy server, and the username and password for proxy server authentication.
authProxy := oss.AuthProxy("yourProxyHost", "yourProxyUserName", "yourProxyPassword")
// Enable CRC data validation.
crc := oss.EnableCRC(true)
// Set the log mode.
logLevel := oss.SetLogLevel(oss.LogOff)
// Create an OSSClient instance.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, use the actual region.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4),
conn, time, cname, userAgent, authProxy, verifySsl, redirect, crc, logLevel)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Set yourEndpoint to the Endpoint of the bucket. For example, for China (Hangzhou), set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
endpoint := "yourEndpoint"
// Check if the environment variables are set.
if endpoint == "" {
log.Fatal("Please set yourEndpoint.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint)
if err != nil {
handleError(err)
}
// Print the client information.
log.Printf("Client: %#v\n", client)
}
Définir le contexte de la requête
Utilisez le contexte de la requête pour contrôler et gérer son cycle de vie, ainsi que pour transmettre des informations contextuelles.
Le code suivant montre comment définir le contexte de la requête. Cette fonctionnalité est prise en charge uniquement à partir de la version 2.2.9 du SDK Go OSS.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// uploadFile uploads a local file to an OSS bucket.
// Parameters:
//
// bucketName - The name of the bucket.
// objectName - The full path of the object. The full path does not include the bucket name.
// localFileName - The full path of the local file.
// endpoint - The Endpoint of the bucket.
//
// If the upload is successful, a success log is recorded. Otherwise, an error is returned.
func uploadFile(bucketName, objectName, localFileName, endpoint string) error {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return err
}
// Create an OSSClient instance.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, use the actual region.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
return err
}
// Get the bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
return err
}
// Set the request context.
ctx := context.Background()
// Specify a timeout for the request context.
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Upload the local file to OSS.
err = bucket.PutObjectFromFile(objectName, localFileName, oss.WithContext(ctx))
if err != nil {
select {
case <-ctx.Done():
return fmt.Errorf("Request cancelled or timed out")
default:
return err
}
}
// After the file is uploaded, record the log.
log.Printf("File uploaded successfully: %s/%s", bucketName, objectName)
return nil
}
func main() {
// Set yourEndpoint to the Endpoint of the bucket. For example, for China (Hangzhou), set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
endpoint := "yourEndpoint"
// Specify the bucket name, for example, examplebucket.
bucketName := "examplebucket"
// Set yourObjectName to the full path of the object. The full path does not include the bucket name.
objectName := "yourObjectName"
// Set yourLocalFile to the full path of the local file.
localFileName := "yourLocalFile"
// Check if the environment variables are set.
if endpoint == "" || bucketName == "" || objectName == "" || localFileName == "" {
log.Fatal("Please set yourEndpoint, bucketName, objectName, and localFileName.")
}
// Try to upload the file. If the upload fails, handle the error.
if err := uploadFile(bucketName, objectName, localFileName, endpoint); err != nil {
handleError(err)
}
// Print a message indicating that the upload is successful.
log.Println("Upload Success!")
}