初始化SDK
在天翼云官网下载OSS_GO_SDK.rar,下载地址:OSS_GO_SDK.rar
AccessKey(AK)和SecretAccessKey(SK)是用户访问媒体存储服务的密钥,密钥的管理和获取方式请查阅媒体存储帮助中心-密钥管理内容。
EndPoint的获取方式请查阅媒体存储帮助中心-基础信息内容。
下面过程以实现列出媒体存储服务中的bucket功能为例,说明了如何使用媒体存储go-sdk进行应用开发。
-
初始化go mod
新建一个项目文件夹go-sdk-demo,在该文件夹路径下执行命令
go mod init {moduleName}
生成go.mod文件,例如:go mod init sdk-demo
-
导入sdk代码
将下载的媒体存储go-sdk代码解压,获得vendor文件夹。在项目文件夹下执行命令导入依赖:
go mod edit -require=github.com/aws/aws-sdk-go@v1.35.5
执行命令将依赖替换为本地包:
go mod edit -replace=github.com/aws/aws-sdk-go@v1.35.5={path of vendor}/github.com/aws/aws-sdk-go
其中{path of vendor}是vendor文件夹在本地的路径,例如:
go mod edit -replace=github.com/aws/aws-sdk-go@v1.35.5=/Users/admin/Desktop/vendor/github.com/aws/aws-sdk-go
执行命令:
go mod vendor
-
新建一个demo.go文件,其内容为:
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
const (
Endpoint = "YourEndpoint"
AccessKey = "YourAccessKey"
SecretAccessKey = "YourSecretAccessKey"
)
func BuildClient() *s3.S3 {
conf := &aws.Config{
Endpoint: aws.String(Endpoint),
S3ForcePathStyle: aws.Bool(false),
DisableSSL: aws.Bool(true),
Credentials: credentials.NewStaticCredentials(AccessKey, SecretAccessKey, ""),
LogLevel: aws.LogLevel(aws.LogDebug)}
sess := session.Must(session.NewSessionWithOptions(session.Options{Config: *conf}))
svc := s3.New(sess)
return svc
}
func main() {
svc := BuildClient()
result, err := svc.ListBuckets(&s3.ListBucketsInput{})
if err != nil {
fmt.Printf("fail to list buckets. %v\n", err)
} else {
fmt.Println(result)
}
}
- 执行命令
go run ./demo.go
运行程序并查看结果。
整个项目的内容层次如下:
go-sdk-demo/
├── demo.go
├── go.mod
├── go.sum
└── vendor