OSSClient serves as the client of Object Storage Service (OSS) SDK for Go to manage OSS resources, such as buckets and objects. When you use OSS SDK for Go to initiate a request, you must initialize an OSSClient instance and modify the default configuration items based on your business requirements.
Create an OSSClient instance
You can use one of the following methods to create an OSSClient instance:
Create an OSSClient instance by using an OSS endpoint
The following code provides an example on how to create an OSSClient instance by using an OSS endpoint:
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main(){
// 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.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("client:%#v\n", client)
}
Create an OSSClient instance by using a custom domain name
The following code provides an example on how to create an OSSClient instance by using a custom domain name.
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main(){
// 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.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
// oss.UseCname(true) indicates that CNAME is enabled. CNAME is used to map a custom domain name to a bucket.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.UseCname(true))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("client:%#v\n", client)
}
For the complete code of custom domain names, visit GitHub.
Create an OSSClient instance by using STS
The following code provides an example on how to create an OSSClient instance by using Security Token Service (STS):
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main(){
// 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 AccessKey pair obtained from STS. An AccessKey pair consists of an AccessKey pair ID and an AccessKey secret.
// Specify the security token obtained from STS.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken("yourSecurityToken"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("client:%#v\n", client)
}
Create an OSSClient instance by using EcsRamRole
The following code provides an example on how to use EcsRamRole to create an OSSClient instance:
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/credentials-go/credentials"
"os"
)
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 {
id,_ := defBuild.cred.GetAccessKeyId()
secret,_ := defBuild.cred.GetAccessKeySecret()
token,_ := defBuild.cred.GetSecurityToken()
return &Credentials{
AccessKeyId: *id,
AccessKeySecret: *secret,
SecurityToken: *token,
}
}
func NewStaticCredentialsProvider(credential credentials.Credential) CredentialsProvider {
return CredentialsProvider{
cred: credential,
}
}
func main(){
config := new(credentials.Config).
// Set the type of the credential to ecs_ram_role.
SetType("ecs_ram_role").
// (Optional) Specify the role name. If you do not specify the role name, OSS automatically generates a role name. We recommend that you specify a role name to reduce the number of requests.
SetRoleName("RoleName")
ecsCredential, err := credentials.NewCredential(config)
if err != nil {
return
}
provider := NewStaticCredentialsProvider(ecsCredential)
client, err := oss.New("oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("client:%#v\n", client)
}
Create an OSSClient instance by using STSAssumeRole
The following code provides an example on how to use STSAssumeRole to create an OSSClient instance:
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/credentials-go/credentials"
"os"
)
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 {
id,_ := defBuild.cred.GetAccessKeyId()
secret,_ := defBuild.cred.GetAccessKeySecret()
token,_ := defBuild.cred.GetSecurityToken()
return &Credentials{
AccessKeyId: *id,
AccessKeySecret: *secret,
SecurityToken: *token,
}
}
func NewCredentialsProvider(credential credentials.Credential) defaultCredentialsProvider {
return defaultCredentialsProvider{
cred: credential,
}
}
func main(){
config := new(credentials.Config).
// Set the type of the credential to ram_role_arn.
SetType("ram_role_arn").
// Specify the AccessKey pair of the RAM user.
SetAccessKeyId("AccessKeyId").
SetAccessKeySecret("AccessKeySecret").
// Specify the Alibaba Cloud Resource Name (ARN) of STSAssumeRole. The ARN is the ID of the role. Format: acs:ram::$accountID:role/$roleName.
SetRoleArn("acs:ram::15069***********:role/ram-oss-test").
// Specify the role session name to distinguish different tokens.
SetRoleSessionName("Role_Session_Name").
// (Optional) Specify the permissions of the STS token.
SetPolicy("").
// (Optional) Specify 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 := NewCredentialsProvider(arnCredential)
client, err := oss.New("oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("client:%#v\n", client)
}
Configure an OSSClient instance
You can use an OSSClient instance to configure parameters, such as the proxy, connection timeout, and the maximum number of connections. The following table describes the parameters.
Parameter | Description | Method |
---|---|---|
MaxIdleConns | The maximum number of idle connections. Default value: 100. | oss.MaxConns |
MaxIdleConnsPerHost | The maximum number of idle connections of a server. Default value: 100. | oss.MaxConns |
MaxConnsPerHost | The maximum number of connections of a server. By default, this parameter is empty. | oss.MaxConns |
ConnectTimeout | The timeout period of an HTTP connection. Unit: seconds. Default value: 10. Unit: seconds. The value 0 indicates that the HTTP connection does not time out. | oss.Timeout |
ReadWriteTimeout | The read or write timeout period of an HTTP connection. Unit: seconds. Default value: 20. Unit: seconds. The value 0 indicates that the HTTP connection does not time out. | oss.Timeout |
IsCname | Specifies whether a custom domain name can be used as an endpoint. By default, a custom domain name cannot be used as an endpoint. | oss.UseCname |
UserAgent | The User-Agent header. Default value: aliyun-sdk-go. | oss.UserAgent |
ProxyHost | Specifies whether to enable the IP address and the port of the proxy server. Default value: false. Valid values:
| oss.AuthProxy |
ProxyUser | The username that is used to log on to the proxy server. | oss.AuthProxy |
ProxyPassword | The password that is used to log on to the proxy server. | oss.AuthProxy |
RedirectEnabled | Specifies whether to enable HTTP redirection. Default value: true. Valid values:
| oss.RedirectEnabled |
InsecureSkipVerify | Specifies whether to enable SSL-based authentication. Default value: true. Valid values:
| oss.InsecureSkipVerify |
IsEnableCRC | Specifies whether to enable CRC-64. Default value: true. Valid values:
| oss.EnableCRC |
LogLevel | The log mode. Valid values:
| oss.SetLogLevel |
Example:
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main() {
// Set the number of connections to 10, the maximum number of idle connections of a server to 20, and the maximum number of connections of a server to 20.
conn := oss.MaxConns(10,20,20)
// Set the timeout period of an HTTP connection to 20 and the read or write timeout period of an HTTP connection to 60. Unit: seconds.
time := oss.Timeout(20,60)
// Specify whether a custom domain name can be used as an endpoint. By default, a custom domain name cannot be used as an endpoint.
cname := oss.UseCname(true)
// Specify the User-Agent header. Default value: aliyun-sdk-go.
userAgent := oss.UserAgent("aliyun-sdk-go")
// Specify whether to enable HTTP redirection. Default value: true.
redirect := oss.RedirectEnabled(true)
// Specify whether to enable SSL-based authentication. Default value: false.
verifySsl := oss.InsecureSkipVerify(false)
// Specify whether to enable the IP address and port of the proxy server.
//proxy := oss.Proxy("yourProxyHost")
// Specify the IP address and the port of the proxy server, and the username and the password that are used to log on to the proxy server.
authProxy := oss.AuthProxy("yourProxyHost","yourProxyUserName","yourProxyPassword")
// Enable CRC-64.
crc := oss.EnableCRC(true)
// Specify the log mode.
logLevel := oss.SetLogLevel(oss.LogOff)
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret",conn,time,cname,userAgent,authProxy,verifySsl,redirect,crc,logLevel)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("%#v\n", client)
}