V1 sürümüne (aliyun-oss-go-sdk) kıyasla mimari açıdan önemli iyileştirmeler sunan daha yeni OSS Go SDK V2 sürümünü (alibabacloud-oss-go-sdk-v2) kullanmanızı öneririz. V2; kimlik doğrulama, istek yeniden denemeleri ve hata yönetimini basitleştirir; ayrıca sayfalayıcılar, aktarım yöneticileri ve dosya benzeri arayüzler gibi gelişmiş arayüzler ekler. Yükseltme yapmak için Go SDK V1'den V2'ye Geçiş Kılavuzu konusuna bakın.
Hızlı entegrasyon
OSS Go SDK V1'i entegre etmek için aşağıdaki adımları tamamlayın.
Ortamı hazırlayın
Go derleme ve çalışma zamanı ortamını indirip yükleyin. Daha fazla bilgi için Go'yu Yükleyin konusuna bakın. Go 1.13 veya sonraki bir sürümü kullanın.
Go 1.13 ve sonraki sürümler, paket bağımlılıklarını yönetmek için varsayılan olarak modül modunu etkinleştirir.
GOPATHdeğerini manuel olarak ayarlamanız gerekmez.Go 1.12 ve önceki sürümlerde
GOPATHsistem ortam değişkenini ayarlamanız ve bu değişkeni kod dizininize yönlendirmeniz gerekir.
Go sürümünü görüntülemek için go version komutunu çalıştırabilirsiniz.
SDK'yı yükleyin
Geliştirme ortamınıza uygun bir yükleme yöntemi seçin. En son SDK sürümünü kullanmanızı öneririz.
go mod (Önerilen)
Aşağıdaki bağımlılığı go.mod dosyasına ekleyin. Bu örnekte 3.0.2 sürümü kullanılmıştır. İhtiyacınız olan sürümle değiştirin.
require (
github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
)
Kaynak koddan
SDK'yı yüklemek için aşağıdaki komutu çalıştırın:
go get github.com/aliyun/aliyun-oss-go-sdk/oss
Yükleme işlemi sırasında herhangi bir istem görüntülenmez. Yükleme zaman aşımına uğrarsa komutu tekrar çalıştırın.
Erişim kimlik bilgilerini yapılandırın
Bir RAM kullanıcısının AccessKey çiftiyle erişim kimlik bilgilerini yapılandırın.
RAM konsolu içinde Permanent AccessKey Pair seçeneğiyle bir RAM kullanıcısı oluşturun. AccessKey çiftini kaydedin ve kullanıcıya
AliyunOSSFullAccessiznini verin.-
RAM kullanıcısının AccessKey çiftini kullanarak ortam değişkenlerini yapılandırın.
Linux
-
Komut satırı arayüzünde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bashrcdosyasına ekleyin.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.
source ~/.bashrc -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Varsayılan kabuk türünü görüntülemek için terminalde aşağıdaki komutu çalıştırın.
echo $SHELL -
Varsayılan kabuk türüne göre aşağıdaki işlemleri gerçekleştirin.
Zsh
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.zshrcdosyasına ekleyin.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.
source ~/.zshrc -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bash_profiledosyasına ekleyin.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.
source ~/.bash_profile -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
CMD'de aşağıdaki komutları çalıştırın.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
PowerShell'de aşağıdaki komutları çalıştırın.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
İstemciyi başlatın
Aşağıdaki örnek kod, China (Hangzhou) bölgesinin genel uç noktasını kullanarak bir istemci başlatır ve mevcut hesap altındaki paketleri listeler. Bölgelerin ve uç noktaların tam listesi için Bölgeler ve uç noktalar konusuna bakın.
package main
// Sample code for initializing a client in OSS Go SDK V1
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
provider, _ := oss.NewEnvironmentVariableCredentialsProvider()
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
)
// List all buckets.
buckets, err := client.ListBuckets()
if err != nil {
fmt.Printf("Failed to list buckets: %v\n", err)
return
}
// Print the bucket list.
fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))
for _, bucket := range buckets.Buckets {
fmt.Printf("%s\n", bucket.Name)
}
}
İstemci yapılandırması
Bir istemci başlatırken ağ ve performans gereksinimlerinize uygun olarak uç nokta türü, zaman aşımı süresi ve bağlantı havuzu boyutu gibi parametreleri özelleştirebilirsiniz.
İç ağ uç noktası kullanın
OSS'e iç ağ üzerinden erişmek için OSS istemcisini başlatırken bir iç ağ uç noktası belirtin.
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou-internal.aliyuncs.com", // The internal endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
)
Özel alan adı kullanın
OSS'e özel bir alan adı kullanarak erişmek için uç nokta olarak bu alan adını belirtin ve istemci başlatma sırasında oss.UseCname(true) ile CNAME seçeneğini etkinleştirin.
Özel bir alan adı kullanmadan önce bu alan adının bir pakete eşlendiğinden emin olun. Daha fazla bilgi için Özel alan adı aracılığıyla OSS'e erişin konusuna bakın.
// Specify whether to use a custom domain name as the endpoint. The default value is false.
cname := oss.UseCname(true)
// Create an OSS client instance.
client, _ := oss.New(
"http://kitkat-cloud.cn", // A custom domain name.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
cname,
)
Zaman aşımı kontrolü
HTTP bağlantı zaman aşımı süresini ve okuma/yazma zaman aşımı süresini saniye cinsinden ayarlamak için oss.Timeout parametresini kullanın.
// Set the HTTP connection timeout period to 20 seconds and the HTTP read or write timeout period to 60 seconds.
time := oss.Timeout(20, 60)
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
time,
)
Bağlantı havuzu boyutunu ayarlayın
Bağlantı havuzu boyutunu ayarlamak için oss.MaxConns parametresini kullanın.
// Set the maximum number of idle connections (MaxIdleConns) to 10. The default value is 100.
// Set the maximum number of idle connections per host (MaxIdleConnsPerHost) to 20. The default value is 100.
// Set the maximum number of connections per host (MaxConnsPerHost) to 50. The default value is empty.
conn := oss.MaxConns(10, 20, 50)
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
conn,
)
CRC veri doğrulamasını devre dışı bırakın
CRC veri doğrulamasını devre dışı bırakmak için oss.EnableCRC(false) ayarını yapın.
CRC veri doğrulamasının etkin kalmasını şiddetle öneririz. Bu özelliği devre dışı bırakırsanız OSS, yükleme ve indirme işlemleri sırasında verilerin bütünlüğünü garanti edemez.
// Disable CRC data validation.
crc := oss.EnableCRC(false)
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
crc,
)
İmza sürümü
Alibaba Cloud Object Storage Service V1 imzaları aşağıdaki takvime göre kullanım dışı bırakılacaktır. Hizmetlerinizin etkilenmemesini sağlamak için mümkün olan en kısa sürede V4 imzalara yükseltin.
1 Mart 2025 tarihinden itibaren yeni kullanıcılar V1 imzalarını kullanamaz.
1 Eylül 2025 tarihinden itibaren V1 imzalarının bakımı ve güncellemeleri kademeli olarak durdurulacak ve yeni oluşturulan paketler V1 imzalarını kullanamayacaktır.
Aşağıdaki örnek kod, V1 imzasıyla bir istemci başlatır. V4 imza başlatma için İstemciyi başlatın bölümüne bakın.
package main
// Sample code for initializing a client with a V1 signature in OSS Go SDK V1
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
provider, _ := oss.NewEnvironmentVariableCredentialsProvider()
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
)
// List all buckets.
buckets, err := client.ListBuckets()
if err != nil {
fmt.Printf("Failed to list buckets: %v\n", err)
return
}
// Print the bucket list.
fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))
for _, bucket := range buckets.Buckets {
fmt.Printf("%s\n", bucket.Name)
}
}
İstek bağlamını ayarlayın
İsteklerin yaşam döngüsünü kontrol etmek için istek bağlamını kullanın.
Yalnızca OSS Go SDK 2.2.9 ve sonraki sürümler istek bağlamının ayarlanmasını destekler.
package main
// Sample code for setting the request context in OSS Go SDK V1
import (
"context"
"fmt"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
provider, _ := oss.NewEnvironmentVariableCredentialsProvider()
// Create an OSS client instance.
client, _ := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
)
// Get the bucket object.
bucket, _ := client.Bucket("example-bucket-hz")
// Configure object information.
key := "oss-browser2-mac-arm64-2.1.0.dmg" // The path of the object in OSS.
file_path := "oss-browser2-mac-arm64-2.1.0.dmg" // The local path to save the object.
// Set the request context.
ctx := context.Background()
// Specify that the request context expires in 5 seconds.
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Download the object from OSS to the specified local path and set the request context.
err := bucket.GetObjectToFile(key, file_path, oss.WithContext(ctx))
if err != nil {
select {
case <-ctx.Done():
fmt.Printf("Request canceled or timed out: %v\n", err)
default:
fmt.Printf("Download failed: %v\n", err)
}
return
}
fmt.Printf("Object downloaded: %s -> %s\n", key, file_path)
}
Hata yönetimi
OSS'e erişim sırasında bir hata oluştuğunda SDK; HTTP durum kodu, hata iletisi, istek kimliği ve EC hata kodu dahil olmak üzere ayrıntıları döndürür. EC hata kodu, belirli nedeni tanımlar ve sorunu hızlı bir şekilde gidermenize yardımcı olur. Örneğin, var olmayan bir nesneyi indirmeye çalışırsanız aşağıdaki hata iletisi döndürülür:
oss: service returned error: StatusCode=404, ErrorCode=NoSuchKey, ErrorMessage="The specified key does not exist.", RequestId=69030EDB2E5F223030953167, Ec=0026-00000001
Hata iletisinde 'EC': '0026-00000001' EC hata kodudur. Sorunun nedenini ve çözümünü bulmak için bu hata kodunu kullanabilirsiniz.
Örnek kod
OSS Go SDK V1; paket yönetimi, nesne işlemleri, erişim kontrolü ve şifreli aktarım gibi temel özellikleri kapsayan örnek kodlar sağlar. Aşağıdaki tabloda kullanılabilir örnekler listelenmiştir:
|
|
|
|
|
|
|
|
|
|
|
|
Uç nokta bilgilerini sorgulayın
OSS Go SDK V1 ile tüm bölgeler veya belirtilen bölgeler için genel uç noktalar (IPv4), iç ağ uç noktaları (klasik ağ veya VPC) ve hızlandırma uç noktaları dahil olmak üzere uç nokta bilgilerini sorgulayabilirsiniz.
Go SDK 2.2.8 ve sonraki sürümler uç nokta bilgilerinin sorgulanmasını destekler.
package main
// Sample code for querying endpoint information in OSS Go SDK V1
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
fmt.Println("=== Query endpoint information for all supported regions ===\n")
// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
provider, _ := oss.NewEnvironmentVariableCredentialsProvider()
// Create an OSS client instance.
client, err := oss.New(
"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
"",
"",
oss.SetCredentialsProvider(&provider),
oss.AuthVersion(oss.AuthV4),
oss.Region("cn-hangzhou"),
)
if err != nil {
fmt.Printf("Failed to create client: %v\n", err)
return
}
// Query endpoint information for all supported regions.
result, err := client.DescribeRegions()
if err != nil {
fmt.Printf("Failed to query endpoint information: %v\n", err)
return
}
// Traverse all region information.
for _, region := range result.Regions {
fmt.Printf("Region: %s\n", region.Region)
fmt.Printf(" Public endpoint (IPv4): %s\n", region.InternetEndpoint)
fmt.Printf(" Internal endpoint (classic network or VPC): %s\n", region.InternalEndpoint)
fmt.Printf(" Acceleration endpoint (global upload and download acceleration): %s\n", region.AccelerateEndpoint)
fmt.Println("--------------------------------------------------------------------------------")
}
// Print statistics.
fmt.Printf("\nFound endpoint information for %d regions\n", len(result.Regions))
}
Belirli bir bölge için uç nokta bilgilerini sorgulamak üzere DescribeRegions yönteminde OSS'ye özel bölge kimliğini belirtin.
result, err := client.DescribeRegions(oss.AddParam("regions", "oss-cn-hangzhou"))
Erişim kimlik bilgisi yapılandırması
OSS, birden çok kimlik bilgisi başlatma yöntemini destekler. Kimlik doğrulama ve yetkilendirme gereksinimlerinize göre bir yöntem seçin.
RAM kullanıcısının AccessKey çiftini kullanın
Sık kimlik bilgisi rotasyonu gerektirmeden uzun süreli OSS erişimi isteyen ve güvenli bir ortamda dağıtılan uygulamalar için uygundur. Kimlik bilgisi sağlayıcısını bir Alibaba Cloud hesabının veya RAM kullanıcısının AccessKey çiftiyle (AccessKey ID ve AccessKey secret) başlatırsınız. Bu yöntem, manuel AccessKey çifti bakımı gerektirir ve güvenlik riskleri oluşturabilir.
Bir Alibaba Cloud hesabı kaynaklar üzerinde tam izne sahiptir. AccessKey çifti sızdırılırsa sisteminiz için önemli bir risk oluşturur. Bir Alibaba Cloud hesabının AccessKey çiftini kullanmanızı önermiyoruz. Gerekli minimum izinlere sahip bir RAM kullanıcısının AccessKey çiftini kullanın.
Bir RAM kullanıcısı için AccessKey çifti oluşturmak için AccessKey çifti oluşturun konusuna bakın. Bir RAM kullanıcısının AccessKey ID'si ve AccessKey secret'ı yalnızca AccessKey çifti oluşturulurken görüntülenir. Bunları unutursanız eskisinin yerine geçmesi için yeni bir AccessKey çifti oluşturun.
Ortam değişkenleri
-
Bir RAM kullanıcısının AccessKey çiftini kullanarak ortam değişkenlerini yapılandırın.
Linux
-
Komut satırı arayüzünde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bashrcdosyasına ekleyin.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.
source ~/.bashrc -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Varsayılan kabuk türünü görüntülemek için terminalde aşağıdaki komutu çalıştırın.
echo $SHELL -
Varsayılan kabuk türüne göre aşağıdaki işlemleri gerçekleştirin.
Zsh
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.zshrcdosyasına ekleyin.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.
source ~/.zshrc -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bash_profiledosyasına ekleyin.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.
source ~/.bash_profile -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
CMD'de aşağıdaki komutları çalıştırın.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
PowerShell'de aşağıdaki komutları çalıştırın.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Sistem ortam değişkenlerini değiştirdikten sonra derleme ve çalışma zamanı ortamını yeniden başlatın veya yenileyin. Buna IDE'ler, komut satırı arayüzleri, diğer masaüstü uygulamaları ve arka uç hizmetleri dahildir; böylece en son sistem ortam değişkenleri yüklenir.
-
Kimlik bilgisi bilgilerini aktarmak için ortam değişkenlerini kullanın.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
Statik kimlik bilgileri
Kimlik bilgilerinin kaynak kodda sabit kodlanmasını önlemek için bunları çalışma zamanında ortam değişkenlerinden, yapılandırma dosyalarından veya diğer harici kaynaklardan okuyan değişkenler aracılığıyla referans verin. Aşağıdaki örnekte bir yapılandırma dosyası kullanılmıştır:
-
go-ini kitaplığını yükleyebilirsiniz.
go get -u github.com/go-ini/ini -
config.iniadlı bir yapılandırma dosyası oluşturabilirsiniz.[credentials] alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID> alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET> -
Yapılandırma dosyasından kimlik bilgisi bilgilerini okumak ve OSS istemcisini başlatmak için kod yazabilirsiniz.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" "gopkg.in/ini.v1" ) type defaultCredentials struct { config *oss.Config } func (defCre *defaultCredentials) GetAccessKeyID() string { return defCre.config.AccessKeyID } func (defCre *defaultCredentials) GetAccessKeySecret() string { return defCre.config.AccessKeySecret } func (defCre *defaultCredentials) GetSecurityToken() string { return defCre.config.SecurityToken } type defaultCredentialsProvider struct { config *oss.Config } func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials { return &defaultCredentials{config: defBuild.config} } func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) { var provider defaultCredentialsProvider if accessID == "" { return provider, fmt.Errorf("access key id is empty!") } if accessKey == "" { return provider, fmt.Errorf("access key secret is empty!") } config := &oss.Config{ AccessKeyID: accessID, AccessKeySecret: accessKey, SecurityToken: token, } return defaultCredentialsProvider{ config, }, nil } func main() { cfg, err := ini.Load("config.ini") if err != nil { fmt.Println("Error loading config file:", err) return } accessKeyID := cfg.Section("credentials").Key("alibaba_cloud_access_key_id").String() accessKeySecret := cfg.Section("credentials").Key("alibaba_cloud_access_key_secret").String() provider, err := NewDefaultCredentialsProvider(accessKeyID, accessKeySecret, "") if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
STS geçici erişim kimlik bilgilerini kullanın
Geçici OSS erişimine ihtiyaç duyan uygulamalar için uygundur. Kimlik bilgisi sağlayıcısını STS'den alınan geçici kimlik bilgileriyle (AccessKey ID, AccessKey secret ve Security Token) başlatırsınız. Bu yöntem, manuel STS belirteci bakımı gerektirir. OSS'e birden çok kez erişmek için belirtecin süresi dolmadan önce manuel olarak yenilemeniz gerekir.
OpenAPI kullanarak hızlı bir şekilde STS belirteci almak için AssumeRole - RAM rolü için geçici kimlik bilgilerini alın konusuna bakın.
Bir SDK kullanarak STS belirteci almak için OSS'e erişmek için STS belirteci kullanın konusuna bakın.
Bir STS belirteci oluştururken bir sona erme süresi belirtmeniz gerekir. Belirtecin süresi dolduğunda geçersiz hale gelir ve tekrar kullanılamaz.
STS uç noktalarının listesi için Uç noktalar konusuna bakın.
-
Geçici kimlik bilgilerini kullanarak ortam değişkenlerini ayarlayın.
Mac OS/Linux/Unix
ÖnemliBir RAM kullanıcısının AccessKey çifti (AccessKey ID ve AccessKey secret) yerine STS'den alınan geçici kimlik bilgilerini (AccessKey ID, AccessKey secret ve Security Token) kullanın.
STS'den alınan AccessKey ID "STS." ile başlar, örneğin "STS.".
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>Windows
ÖnemliBir RAM kullanıcısının AccessKey çifti (AccessKey ID ve AccessKey secret) yerine STS'den alınan geçici kimlik bilgilerini (AccessKey ID, AccessKey secret ve Security Token) kullanın.
STS'den alınan AccessKey ID "STS." ile başlar, örneğin "STS.".
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN> -
Kimlik bilgisi bilgilerini ortam değişkenleri aracılığıyla aktarın.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Create an OSSClient instance. // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
RAM rolü ARN'sini kullanın
Hesaplar arası erişim gibi OSS'e yetkili erişim gerektiren uygulamalar için uygundur. Kimlik bilgisi sağlayıcısını bir RAM rolünün ARN'sini belirterek başlatırsınız. Credentials aracı, AssumeRole işlemi çağrılarak STS belirteçlerini otomatik olarak alır ve süresi dolmadan önce yeniler. Rolü daha küçük bir izin kümesiyle kısıtlamak için policy atayabilirsiniz.
Bir Alibaba Cloud hesabı kaynaklar üzerinde tam izne sahiptir. AccessKey çifti sızdırılırsa sisteminiz için önemli bir risk oluşturur. Bir Alibaba Cloud hesabının AccessKey çiftini kullanmanızı önermiyoruz. Gerekli minimum izinlere sahip bir RAM kullanıcısının AccessKey çiftini kullanın.
Bir RAM kullanıcısı için AccessKey çifti oluşturmak için AccessKey çifti oluşturun konusuna bakın. Bir RAM kullanıcısının AccessKey ID'si ve AccessKey secret'ı yalnızca AccessKey çifti oluşturulurken görüntülenir. Bunları hemen kaydedin. Unutursanız eskisinin yerine geçmesi için yeni bir AccessKey çifti oluşturun.
Bir RAM rolü ARN'si almak için RAM rolü oluşturun konusuna bakın.
-
Credentials bağımlılığını ekleyebilirsiniz.
go get github.com/aliyun/credentials-go/credentials -
Erişim kimlik bilgisi olarak AccessKey çiftini ve RAM rolü ARN'sini yapılandırın.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/aliyun/credentials-go/credentials" ) type Credentials struct { AccessKeyId string AccessKeySecret string SecurityToken string } type defaultCredentialsProvider struct { cred credentials.Credential } func (credentials *Credentials) GetAccessKeyID() string { return credentials.AccessKeyId } func (credentials *Credentials) GetAccessKeySecret() string { return credentials.AccessKeySecret } func (credentials *Credentials) GetSecurityToken() string { return credentials.SecurityToken } func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials { cred, _ := defBuild.cred.GetCredential() return &Credentials{ AccessKeyId: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, } } func NewRamRoleArnCredentialsProvider(credential credentials.Credential) defaultCredentialsProvider { return defaultCredentialsProvider{ cred: credential, } } func main() { config := new(credentials.Config). // The credential type. Set the value to ram_role_arn. SetType("ram_role_arn"). // The AccessKey ID and AccessKey secret of the RAM user. The values are obtained from environment variables. SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")). SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")). // The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters. // The ARN of the RAM role to assume. The value is obtained from an environment variable. Format: acs:ram::$accountID:role/$roleName. SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN. // A custom name for the role session to distinguish different tokens. SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. // (Optional) Restrict the permissions of the STS token. SetPolicy(""). // (Optional) Limit the validity period of the STS token. SetRoleSessionExpiration(3600) arnCredential, err := credentials.NewCredential(config) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } provider := NewRamRoleArnCredentialsProvider(arnCredential) // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
ECS örneği RAM rolünü kullanın
ECS örneklerinde, ECI örneklerinde veya Container Service for Kubernetes çalışan düğümlerinde çalışan uygulamalar için önerilir. Bir ECS örneği RAM rolü, bir rolü örnekle ilişkilendirir ve AccessKey çifti veya STS belirteci sağlamadan otomatik STS belirteci yenilemeyi etkinleştirir. Bir ECS örneği RAM rolünü nasıl alacağınız hakkında bilgi için RAM rolü oluşturun konusuna bakın. Bir rolü bir ECS örneğiyle nasıl ilişkilendireceğiniz hakkında bilgi için Örnek RAM rolleri konusuna bakın.
-
Credentials bağımlılığını ekleyebilirsiniz.
go get github.com/aliyun/credentials-go/credentials -
Erişim kimlik bilgisi olarak ECS örneği RAM rolünü yapılandırın.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/aliyun/credentials-go/credentials" ) type Credentials struct { AccessKeyId string AccessKeySecret string SecurityToken string } type CredentialsProvider struct { cred credentials.Credential } func (credentials *Credentials) GetAccessKeyID() string { return credentials.AccessKeyId } func (credentials *Credentials) GetAccessKeySecret() string { return credentials.AccessKeySecret } func (credentials *Credentials) GetSecurityToken() string { return credentials.SecurityToken } func (defBuild CredentialsProvider) GetCredentials() oss.Credentials { cred, _ := defBuild.cred.GetCredential() return &Credentials{ AccessKeyId: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, } } func NewEcsCredentialsProvider(credential credentials.Credential) CredentialsProvider { return CredentialsProvider{ cred: credential, } } func main() { config := new(credentials.Config). // The credential type. Set the value to ecs_ram_role. SetType("ecs_ram_role"). // (Optional) The role name. If you do not specify this parameter, OSS automatically obtains the role. We recommend that you specify the role name to reduce the number of requests. SetRoleName("RoleName") ecsCredential, err := credentials.NewCredential(config) if err != nil { return } provider := NewEcsCredentialsProvider(ecsCredential) // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
OIDC rolü ARN'sini kullanın
Container Service for Kubernetes çalışan düğümlerinde dağıtılan güvenilmeyen uygulamalar için Hizmet Hesapları için RAM Rolleri (RRSA) özelliği, pod düzeyinde kimlik bilgisi yalıtımı sağlar. RRSA, genel meta hizmet aracılığıyla çalışan düğümün örnek RAM rolünü paylaşmak yerine her poda bir hizmet hesabı OIDC belirteci dosyası monte eder ve yapılandırmayı ortam değişkenlerine enjekte eder. Credentials aracı daha sonra OIDC belirtecini bir STS belirteciyle değiştirmek için AssumeRoleWithOIDC işlemi çağırır. AccessKey çifti veya STS belirteci gerekmez. Daha fazla bilgi için Pod düzeyinde izin yalıtımı sağlamak için RRSA kullanarak bir ServiceAccount için RAM izinlerini yapılandırın konusuna bakın.
-
Credentials bağımlılığını ekleyebilirsiniz.
go get github.com/aliyun/credentials-go/credentials -
Erişim kimlik bilgisi olarak OIDC RAM rolünü yapılandırın.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/aliyun/credentials-go/credentials" ) type Credentials struct { AccessKeyId string AccessKeySecret string SecurityToken string } type CredentialsProvider struct { cred credentials.Credential } func (credentials *Credentials) GetAccessKeyID() string { return credentials.AccessKeyId } func (credentials *Credentials) GetAccessKeySecret() string { return credentials.AccessKeySecret } func (credentials *Credentials) GetSecurityToken() string { return credentials.SecurityToken } func (defBuild CredentialsProvider) GetCredentials() oss.Credentials { cred, _ := defBuild.cred.GetCredential() return &Credentials{ AccessKeyId: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, } } func NewOIDCRoleARNCredentialsProvider(credential credentials.Credential) CredentialsProvider { return CredentialsProvider{ cred: credential, } } func main() { config := new(credentials.Config). // The file path of the OIDC token. SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")). // The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters. // The credential type. Set the value to oidc_role_arn. SetType("oidc_role_arn"). // The ARN of the OIDC provider. Format: acs:ram::account-id:oidc-provider/provider-name. SetOIDCProviderArn("acs:ram::113511544585****:oidc-provider/TestOidcProvider"). // The standard environment variable name for OIDCProviderArn is ALIBABA_CLOUD_OIDC_PROVIDER_ARN. // A custom name for the role session to distinguish different tokens. SetRoleSessionName("role_session_name"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. // The ARN of the role to assume. Format: acs:ram::113511544585****:oidc-provider/TestOidcProvider SetRoleArn("acs:ram::113511544585****:role/testoidc"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN. // (Optional) The policy to use when assuming the role. SetPolicy(""). SetSessionExpiration(3600) oidcCredential, err := credentials.NewCredential(config) if err != nil { return } provider := NewOIDCRoleARNCredentialsProvider(oidcCredential) // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
Function Compute bağlamından kimlik bilgilerini kullanın
Function Compute'da dağıtılan uygulama işlevleri için uygundur. Function Compute, işlev için yapılandırılan hizmet rolünü üstlenerek bir STS belirteci alır ve bunu bağlamdaki Credentials parametresi aracılığıyla iletir. Bu STS belirteci 36 saat geçerlidir ve işlev yürütme sırasında (maksimum 24 saat) süresi dolmaz, bu nedenle yenileme gerekmez. AccessKey çifti veya STS belirteci gerekmez. Function Compute'a OSS'e erişim izni verme hakkında bilgi için Function Compute'a diğer Alibaba Cloud hizmetlerine erişim izni vermek için işlev rolü kullanın konusuna bakın.
-
Function Compute bağlam bağımlılıklarını ekleyebilirsiniz.
go get github.com/aliyun/fc-runtime-go-sdk/fc go get github.com/aliyun/fc-runtime-go-sdk/fccontext -
Function Compute bağlamından kimlik bilgilerini kullanarak kimlik bilgisi sağlayıcısını başlatabilirsiniz.
package main import ( "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" ) type GetObjectContext struct { OutputRoute string `json:"outputRoute"` OutputToken string `json:"outputToken"` InputOssUrl string `json:"inputOssUrl"` } type StructEvent struct { GetObjectContext GetObjectContext `json:"getObjectContext"` } func HandleRequest(ctx context.Context, event StructEvent) error { endpoint := event.GetObjectContext.OutputRoute fctx, _ := fccontext.FromContext(ctx) client, err := oss.New(endpoint, fctx.Credentials.AccessKeyId, fctx.Credentials.AccessKeySecret, oss.SecurityToken(fctx.Credentials.SecurityToken)) if err != nil { return fmt.Errorf("client new error: %v", err) } fmt.Printf("client:%#v\n", client) return nil } func main() { fc.Start(HandleRequest) }
CredentialsURI kullanın
Kimlik bilgilerini harici bir sistemden alan uygulamalar için uygundur. Credentials aracı, belirtilen URI'den STS belirteçlerini alır ve bunları otomatik olarak yeniler. AccessKey çifti veya STS belirteci gerekmez.
CredentialsURI, STS belirtecinin alındığı sunucu adresidir.
CredentialsURI yanıtını sağlayan arka uç hizmeti, uygulamanın her zaman geçerli kimlik bilgilerini alabilmesini sağlamak için otomatik STS belirteci yenileme mantığını uygulamalıdır.
-
Credentials aracının STS belirtecini doğru şekilde ayrıştırıp kullanabilmesi için URI'nin aşağıdaki yanıt protokolüne uyması gerekir:
Yanıt durum kodu: 200
-
Yanıt gövdesi yapısı:
{ "Code": "Success", "AccessKeySecret": "AccessKeySecret", "AccessKeyId": "AccessKeyId", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "SecurityToken" }
-
Credentials bağımlılığını ekleyebilirsiniz.
go get github.com/aliyun/credentials-go/credentials -
Erişim kimlik bilgisi olarak CredentialsURI'yi yapılandırın.
package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/aliyun/credentials-go/credentials" ) type Credentials struct { AccessKeyId string AccessKeySecret string SecurityToken string } type CredentialsProvider struct { cred credentials.Credential } func (credentials *Credentials) GetAccessKeyID() string { return credentials.AccessKeyId } func (credentials *Credentials) GetAccessKeySecret() string { return credentials.AccessKeySecret } func (credentials *Credentials) GetSecurityToken() string { return credentials.SecurityToken } func (defBuild CredentialsProvider) GetCredentials() oss.Credentials { cred, _ := defBuild.cred.GetCredential() return &Credentials{ AccessKeyId: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, } } func NewCredentialsUriCredentialsProvider(credential credentials.Credential) CredentialsProvider { return CredentialsProvider{ cred: credential, } } func main() { config := new(credentials.Config). // The credential type. Set the value to credentials_uri. SetType("credentials_uri"). // Specify the URL address. You can also set an environment variable and use os.Getenv("<variable_name>") to pass the parameter. // The standard environment variable name for URLCredential is ALIBABA_CLOUD_CREDENTIALS_URI. SetURLCredential("http://127.0.0.1") uriCredential, err := credentials.NewCredential(config) if err != nil { return } provider := NewCredentialsUriCredentialsProvider(uriCredential) // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. 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 { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
Otomatik dönen AccessKey çiftini kullanın
Uzun süreli OSS erişimi gerektiren ancak AccessKey çifti sızdırma riski bulunan ortamlarda dağıtılan uygulamalar için uygundur. Kimlik bilgisi sağlayıcısını bir ClientKey ile başlatırsınız. Key Management Service (KMS), yönetilen RAM kullanıcısının AccessKey çiftini periyodik bir programda otomatik olarak döndürerek statik bir kimlik bilgisini dinamik hale getirir. KMS, sızdırma durumunda hızlı değiştirme için anında rotasyonu da destekler. Bir ClientKey'i nasıl alacağınız hakkında bilgi için Uygulama erişim noktası oluşturun konusuna bakın.
-
Credential istemci bağımlılığını ekleyebilirsiniz.
go get -u github.com/aliyun/aliyun-secretsmanager-client-go -
secretsmanager.propertiesadlı bir yapılandırma dosyası oluşturabilirsiniz.# Access credential type credentials_type=client_key # The password used to decrypt the client key. The password can be read from an environment variable or a file. client_key_password_from_env_variable=#your client key private key password environment variable name# client_key_password_from_file_path=#your client key private key password file path# # The path of the client key's private key file. client_key_private_key_path=#your client key private key file path# # The region of the associated KMS service. cache_client_region_id=[{"regionId":"#regionId#"}] -
Kimlik bilgisi bilgilerini aktarmak için yapılandırma dosyasını kullanabilirsiniz.
package main import ( "encoding/json" "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/aliyun/aliyun-secretsmanager-client-go/sdk" ) type defaultCredentials struct { config *oss.Config } func (defCre *defaultCredentials) GetAccessKeyID() string { return defCre.config.AccessKeyID } func (defCre *defaultCredentials) GetAccessKeySecret() string { return defCre.config.AccessKeySecret } func (defCre *defaultCredentials) GetSecurityToken() string { return defCre.config.SecurityToken } type defaultCredentialsProvider struct { config *oss.Config } func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials { return &defaultCredentials{config: defBuild.config} } func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) { var provider defaultCredentialsProvider if accessID == "" { return provider, fmt.Errorf("access key id is empty!") } if accessKey == "" { return provider, fmt.Errorf("access key secret is empty!") } config := &oss.Config{ AccessKeyID: accessID, AccessKeySecret: accessKey, SecurityToken: token, } return defaultCredentialsProvider{ config, }, nil } func main() { client, err := sdk.NewClient() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } secretInfo, err := client.GetSecretInfo("#secretName#") if err != nil { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("SecretValue:%s\n", secretInfo.SecretValue) var m map[string]string err = json.Unmarshal([]byte(secretInfo.SecretValue), &m) if err != nil { fmt.Println("Error decoding JSON:", err) os.Exit(-1) } accessKeyId := m["AccessKeyId"] accessKeySecret := m["AccessKeySecret"] provider, err := NewDefaultCredentialsProvider(accessKeyId, accessKeySecret, "") if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed. // Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed. clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)} clientOptions = append(clientOptions, oss.Region("yourRegion")) // Set the signature version. clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4)) ossClient, err := oss.New("yourEndpoint", "", "", clientOptions...) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", ossClient) }
Özel erişim kimlik bilgilerini kullanın
Yukarıdaki yöntemlerden hiçbiri gereksinimlerinizi karşılamıyorsa Credential Providers arayüzünü kullanarak özel bir kimlik bilgisi sağlayıcısı uygulayabilirsiniz. Altta yatan kimlik bilgileri STS tabanlıysa belirteç yenilemeyi ele almanız gerekir.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
type CustomerCredentialsProvider struct {
config *oss.Config
}
func NewCustomerCredentialsProvider() CustomerCredentialsProvider {
return CustomerCredentialsProvider{}
}
func (s CustomerCredentialsProvider) GetCredentials() oss.Credentials {
// Return long-term credentials.
config := &oss.Config{
AccessKeyID: "id",
AccessKeySecret: "secret",
}
return &CustomerCredentialsProvider{
config,
}
// Return temporary credentials.
//config := &oss.Config{
// AccessKeyID: "id",
// AccessKeySecret: "secret",
// SecurityToken: "token",
//}
//return &CustomerCredentialsProvider{
// config,
//}
}
func (s *CustomerCredentialsProvider) GetAccessKeyID() string {
return s.config.AccessKeyID
}
func (s *CustomerCredentialsProvider) GetAccessKeySecret() string {
return s.config.AccessKeySecret
}
func (s *CustomerCredentialsProvider) GetSecurityToken() string {
return s.config.SecurityToken
}
func main() {
provider := NewCustomerCredentialsProvider()
// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("client:%#v\n", client)
}
SSS
SDK'yı kullanırken AccessDenied hatasını nasıl giderebilirim?
AccessDenied hatası genellikle yetersiz izinleri gösterir. Sorunu gidermek için şu adımları izleyin:
AccessKey ID ve AccessKey secret'ı onaylayın: Doğru AccessKey ID ve AccessKey secret'ı kullandığınızdan emin olun.
RAM kullanıcı izinlerini kontrol edin: RAM kullanıcısının paket veya nesne işlemleri için gerekli izinlere sahip olup olmadığını onaylayın.
Paket ilkesini kontrol edin: Hata iletisi "Access denied by bucket policy" içeriyorsa erişimin bir paket ilkesi tarafından reddedildiği anlamına gelir.
Diğer hata türlerini sorgulama ve yaygın erişim kontrolü hatalarını giderme hakkında daha fazla bilgi için Hata yönetimi konusuna bakın.