Tüm Ürünler
Search
Belge Merkezi

:Configure a client (Go SDK V1)

Son Güncelleme:Oct 01, 2026

Client, Object Storage Service (OSS) kaynaklarını (paketler ve dosyalar gibi) yönetmenizi sağlayan Go istemcisidir. Go SDK ile bir OSS isteği göndermek için bir Client örneği başlatmanız gerekir. Ayrıca varsayılan yapılandırmaları ihtiyaçlarınıza göre değiştirebilirsiniz.

Ön koşullar

OSS SDK'yı başlatmadan önce erişim kimlik bilgilerinizi yapılandırmanız gerekir. Daha fazla bilgi için bkz. Erişim kimlik bilgilerini yapılandırma (Go SDK V1).

Yeni bir Client oluşturun

V4 imzası (Önerilir)

Daha güvenli olan V4 imzalama algoritmasını kullanmanızı öneririz. İstemciyi V4 imzasıyla başlatırken uç nokta ve genel amaçlı Alibaba Cloud bölge kimliğini belirtmeniz gerekir. Bölge kimliği, isteğin başlatıldığı bölgeyi belirtir (örneğin, cn-hangzhou). Ayrıca oss.AuthV4 bildirimini yapmanız gerekir. V4 imzaları, OSS Go SDK 3.0.2 ve sonraki sürümlerde desteklenir.

Aşağıdaki örnek, bir OSS etki alanı adı kullanarak V4 imzasıyla bir istemcinin nasıl başlatılacağını gösterir. Örneği, istemciyi özel bir etki alanı adı ile başlatmak gibi diğer senaryolar için uyarlayabilirsiniz.

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

V1 imzası (Önerilmez)

Önemli

1 Mart 2025 tarihinden itibaren Alibaba Cloud Object Storage Service (OSS), yeni kullanıcılar için (yani yeni UID'ler için) V1 imzasını sunmamaktadır. 1 Eylül 2025 tarihinden itibaren OSS, V1 imzasını güncellemeyi ve bakımını durduracak ve yeni nesne depolama paketleri için V1 imzasını sunmayacaktır. Hizmet kesintilerini önlemek için mümkün olan en kısa sürede V4 imzasına geçiş yapın. Daha fazla bilgi için bkz. Duyuru.

Bir OSS etki alanı adı kullanarak yeni bir Client oluşturun

Aşağıdaki kod, bir OSS etki alanı adı kullanarak bir istemcinin nasıl başlatılacağını gösterir. Farklı bölgeler için OSS etki alanı adları hakkında daha fazla bilgi için bkz. Bölgeler ve Uç Noktalar.

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

Özel bir etki alanı adı kullanarak yeni bir Client oluşturun

Aşağıdaki kod, özel bir etki alanı adı kullanarak yeni bir Client'ın nasıl oluşturulacağını gösterir. OSS'e özel bir etki alanı adı ile erişme hakkında daha fazla bilgi için bkz. Özel etki alanı adı ile OSS'e erişin.

Önemli

Özel bir etki alanı adı ile ossClient.listBuckets yöntemini kullanamazsınız.

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

Client'ı Yapılandırın

Proxy, bağlantı zaman aşımı ve maksimum bağlantı sayısı gibi Client parametrelerini yapılandırabilirsiniz.

Parametre

Açıklama

Yöntem

MaxIdleConns

Maksimum boşta bağlantı sayısı. Varsayılan değer: 100.

oss.MaxConns

MaxIdleConnsPerHost

Her ana bilgisayar için maksimum boşta bağlantı sayısı. Varsayılan değer: 100.

oss.MaxConns

MaxConnsPerHost

Her ana bilgisayar için maksimum bağlantı sayısı. Varsayılan değer boştur.

oss.MaxConns

ConnectTimeout

Saniye cinsinden HTTP zaman aşımı süresi. Varsayılan değer: 10 saniye. 0 değeri zaman aşımı olmadığını belirtir.

oss.Timeout

ReadWriteTimeout

Saniye cinsinden HTTP okuma veya yazma zaman aşımı süresi. Varsayılan değer: 20 saniye. 0 değeri zaman aşımı olmadığını belirtir.

oss.Timeout

IsCname

Uç nokta olarak özel bir etki alanı adının kullanılıp kullanılmayacağını belirtir. Bu özellik varsayılan olarak devre dışıdır.

oss.UseCname

UserAgent

HTTP istekleri için User-Agent üstbilgisini ayarlar. Varsayılan değer: aliyun-sdk-go.

oss.UserAgent

ProxyHost

Proxy sunucusu ana bilgisayar adresini ve bağlantı noktasını etkinleştirip etkinleştirmeyeceğini belirtir. Geçerli değerler:

  • true: Proxy sunucusu ana bilgisayar adresini ve bağlantı noktasını etkinleştirir.

  • false (varsayılan): Proxy sunucusu ana bilgisayar adresini ve bağlantı noktasını devre dışı bırakır.

oss.AuthProxy

ProxyUser

Proxy sunucusu kimlik doğrulaması için kullanıcı adı.

oss.AuthProxy

ProxyPassword

Proxy sunucusu kimlik doğrulaması için parola.

oss.AuthProxy

RedirectEnabled

HTTP yönlendirmesinin etkinleştirilip etkinleştirilmeyeceğini belirtir. Geçerli değerler:

  • true (varsayılan): HTTP yönlendirmesini etkinleştirir.

  • false: HTTP yönlendirmesini devre dışı bırakır.

oss.RedirectEnabled

InsecureSkipVerify

SSL sertifika doğrulamasının etkinleştirilip etkinleştirilmeyeceğini belirtir. Geçerli değerler:

  • true (varsayılan): SSL sertifika doğrulamasını atlar.

  • false: SSL sertifika doğrulamasını etkinleştirir.

oss.InsecureSkipVerify

IsEnableCRC

CRC veri doğrulamasının etkinleştirilip etkinleştirilmeyeceğini belirtir. Geçerli değerler:

  • true (varsayılan): CRC veri doğrulamasını etkinleştirir.

  • false: CRC veri doğrulamasını devre dışı bırakır.

    Önemli

    CRC veri doğrulamasını devre dışı bırakmayın. Bu özelliği devre dışı bırakırsanız Alibaba Cloud, yükleme ve indirme sırasında veri bütünlüğünü garanti edemez.

oss.EnableCRC

LogLevel

Günlük modunu ayarlar. Geçerli değerler:

  • oss.LogOff

  • oss.Debug

  • oss.Error

  • oss.Warn

  • oss.Info

oss.SetLogLevel

Aşağıdaki kod bir yapılandırma örneği sağlar:

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

İstek bağlamını ayarlayın

İstek yaşam döngüsünü kontrol etmek ve yönetmek ile bağlamla ilgili bilgileri iletmek için istek bağlamını kullanabilirsiniz.

Aşağıdaki kod, istek bağlamının nasıl ayarlanacağını gösterir. İstek bağlamının ayarlanması yalnızca OSS Go SDK 2.2.9 ve sonraki sürümlerde desteklenir.

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!")
}