Initialize a COS Client
masterTo use the SDK, you must create a client using cos.NewClient. This requires a cos.BaseURL containing your bucket's URL and an http.Client configured with an AuthorizationTransport for authentication.
Important Requirements:
- The bucket URL must follow the format:
https://<bucket>.cos.<region>.myqcloud.com. - The bucket name must follow the naming rule:
{name}-{appid}. - Authentication can be provided via
SecretIDandSecretKeydirectly or by using environment variablesCOS_SECRETIDandCOS_SECRETKEY.
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
"github.com/tencentyun/cos-go-sdk-v5"
)
func main() {
// Replace <bucket> and <region> with your actual information
u, _ := url.Parse("https://<bucket>.cos.<region>.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}
c := cos.NewClient(b, &http.Client{
Timeout: 100 * time.Second,
Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("COS_SECRETID"),
SecretKey: os.Getenv("COS_SECRETKEY"),
},
})
name := "test/hello.txt"
resp, err := c.Object.Get(context.Background(), name, nil)
if err != nil {
panic(err)
}
bs, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%s\n", string(bs))
}