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
Use the V1 signature algorithm
Create an OSSClient instance by using an OSS endpoint
The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint. For more information about the OSS endpoints of different regions, 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. Before you run the sample code, make sure that the 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.
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 sample code provides an example on how to create an OSSClient instance by using a custom domain name. For more information, see Map a custom domain name to the default domain name of a bucket.
If you use a custom domain name, the ossClient.listBuckets method is unavailable
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 environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Set yourEndpoint to the custom domain name of the bucket.
// Set oss.UseCname to true to enable CNAME. 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)
}
Use the V4 signature algorithm (recommended)
If you want to use the V4 signature algorithm which is more secure, you must specify the region information of the endpoint and declare oss.AuthV4 during initialization. OSS SDK for Go 3.0.2 and later support V4 signatures.
The following sample code provides an example on how to use an OSS endpoint to create an OSSClient instance and sign the request by using the V4 signature algorithm. If you want to use other methods to create an OSSClient instance, refer to the following sample code and change the variables.
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 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.
// Specify the endpoint of the region in which the bucket is located.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("yourRegion"))
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 server, connection timeout period, 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 |
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.