This topic describes how to download an object from a bucket to your local computer.

The following code provides an example on how to download exampleobject.txt from the exampledir directory in examplebucket to the D:\localpath path. After the object is downloaded, the local file is named examplefile.txt.

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access Object Storage Service (OSS) because the account has permissions on all API operations. 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)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucket, err := client.Bucket("examplebucket")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Download the object to the specified local path. If the specified local file exists, the downloaded object replaces the local file. Otherwise, the local file is created. 
    // If you do not specify the path of the local file, the downloaded object is saved to the path of the project to which the sample program belongs. 
    // Specify the full path of the object. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. The full path of the object cannot contain bucket names. 
    err = bucket.GetObjectToFile("exampledir/exampleobject.txt", "D:\\localpath\\examplefile.txt")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}