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.
Prerequisites
Access credentials are configured. For more information, see Configure access credentials.
Create an OSSClient instance
To create an OSSClient instance, you must specify the 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.
For more information about OSS endpoints, see Regions and endpoints.
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main(){
// Obtain access credentials from environment variables. You need to configure environment variables before you run the sample code.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// 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.
client, err := oss.New("yourEndpoint", "", "", 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 a custom domain name
The following code provides an example on how to create an OSSClient instance by using a custom domain name.
For more information about how to use a custom domain name to access OSS, see Map custom domain names.
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(){
// Obtain access credentials from environment variables. You need to configure environment variables before you run the sample code.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Set yourEndpoint to the custom domain name of the bucket.
// 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", "", "", oss.SetCredentialsProvider(&provider),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.
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. 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. 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. 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. Valid values:
| oss.RedirectEnabled |
InsecureSkipVerify | Specifies whether to enable SSL-based authentication. Valid values:
| oss.InsecureSkipVerify |
IsEnableCRC | Specifies whether to enable CRC-64. Valid values:
| oss.EnableCRC |
LogLevel | The log mode. Valid values:
| oss.SetLogLevel |
Configuration example:
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 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", "", "", oss.SetCredentialsProvider(&provider),conn,time,cname,userAgent,authProxy,verifySsl,redirect,crc,logLevel)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Printf("%#v\n", client)
}
Set the request context
You can use the request context to manage the lifecycle of a request and pass context information related to the request.
The following code provides an example on how to set the request context. You can set the request context by using OSS SDK for Go 2.2.9 and later.
package main
import (
"context"
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
"time"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// 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 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", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Set the request context.
ctx := context.Background()
// Specify the expiration time of the request context.
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Upload the local file to OSS.
err = bucket.PutObjectFromFile("yourObjectName", "yourLocalFile", oss.WithContext(ctx))
if err != nil {
select {
case <-ctx.Done():
fmt.Println("Request cancelled or timed out")
default:
fmt.Println("Upload fail, Error:", err)
}
os.Exit(-1)
}
fmt.Println("Upload Success!")
}
What to do next
After you initialize OSS SDK for Go, you can use the OSSClient instance to initiate a request. For more information, see Getting started with OSS SDK for Go.