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

Note To create an OSSClient instance, you must specify an endpoint. For more information about endpoints, see Regions and endpoints.

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.

Note The ListBuckets operation is unavailable when a custom domain name is used.
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.

ParameterDescriptionMethod
MaxIdleConnsThe maximum number of idle connections. Default value: 100. oss.MaxConns
MaxIdleConnsPerHostThe maximum number of idle connections of a server. Default value: 100. oss.MaxConns
MaxConnsPerHostThe maximum number of connections of a server. By default, this parameter is empty. oss.MaxConns
ConnectTimeoutThe 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
ReadWriteTimeoutThe 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
IsCnameSpecifies 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
UserAgentThe User-Agent header. Default value: aliyun-sdk-go. oss.UserAgent
ProxyHostSpecifies whether to enable the IP address and the port of the proxy server. Default value: false. Valid values:
  • true: enables the IP address and the port of the proxy server.
  • false: disables the IP address and the port of the proxy server.
oss.AuthProxy
ProxyUserThe username that is used to log on to the proxy server. oss.AuthProxy
ProxyPasswordThe password that is used to log on to the proxy server. oss.AuthProxy
RedirectEnabledSpecifies whether to enable HTTP redirection. Default value: true. Valid values:
  • true: enables HTTP redirection.
  • false: disables HTTP redirection.
oss.RedirectEnabled
InsecureSkipVerifySpecifies whether to enable SSL-based authentication. Default value: true. Valid values:
  • true: enables SSL-based authentication.
  • false: disables SSL-based authentication.
oss.InsecureSkipVerify
IsEnableCRCSpecifies whether to enable CRC-64. Default value: true. Valid values:
  • true: enables CRC-64.
  • false: disables CRC-64.
    Important We recommend that you do not disable CRC-64. If you disable CRC-64, data integrity may be affected during object uploads and downloads.
oss.EnableCRC
LogLevelThe log mode. Valid values:
  • oss.LogOff
  • oss.Debug
  • oss.Error
  • oss.Warn
  • oss.Info
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)


}