设置service client

使用SDK访问OSS服务,首先需要提供正确的AccessKey和SecretAccessKey以及服务端地址EndPoint,用于设置一个service client。

  • 创建session

    配置service client首先需要创建一个session, session包含了service client的配置信息,例如AccessKey、SecretAccessKey以及发送请求的附加信息等。一个session可以被用于创建多个service client。

    代码示例:

import (
    "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        = "YOUR_ENDPOINT"
    AccessKey       = "YOUR_ACCESS_KEY"
    SecretAccessKey = "YOUR_SECRET_ACCESS_KEY"
)

// BuildSession 创建并返回一个session
func BuildSession() *session.Session {
conf := &aws.Config{
    Endpoint: aws.String(Endpoint),
    S3ForcePathStyle: aws.Bool(false),
    // 设置true为使用HTTP协议,设置为false为使用HTTPS协议
    DisableSSL:  aws.Bool(true),
    Credentials: credentials.NewStaticCredentials(AccessKey, SecretAccessKey, ""),
    LogLevel:    aws.LogLevel(aws.LogDebug)}
    sess := session.Must(session.NewSessionWithOptions(session.Options{Config: *conf}))
    return sess
}
  • 创建service client

    代码示例:

// BuildClient 创建并返回一个service client
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
}