跳到主要内容
版本:valkey_v0.x.x

S3

Release Discord Test Security Linter

使用 aws/aws-sdk-go-v2 的 S3 存储驱动。

注意: 如果未提供凭据的配置字段,则凭据将使用环境变量、~/.aws/credentials 或 EC2 实例角色。如果提供了凭据的配置字段,则凭据将使用配置中的值。请参阅:指定凭据

注意:需要 Go 1.19 及以上版本

目录

签名

func New(config ...Config) Storage
func (s *Storage) Get(key string) ([]byte, error)
func (s *Storage) Set(key string, val []byte, exp time.Duration) error
func (s *Storage) Delete(key string) error
func (s *Storage) Reset() error
func (s *Storage) Close() error
func (s *Storage) Conn() *s3.Client

// Additional useful methods.
func (s *Storage) CreateBucket(bucket string) error
func (s *Storage) DeleteBucket(bucket string) error
func (s *Storage) DeleteMany(keys ...string) error
func (s *Storage) SetWithChecksum(key string, val []byte, checksum map[types.ChecksumAlgorithm][]byte) error

安装

S3 在支持模块的最近两个 Go 版本上进行了测试。因此,如果尚未初始化,请务必先初始化一个。

go mod init github.com/<user>/<repo>

然后安装 s3 实现

go get github.com/gofiber/storage/s3/v2

示例

导入 storage 包。

import "github.com/gofiber/storage/s3/v2"

您可以使用以下方法创建存储

// Initialize default config
store := s3.New()

// Initialize custom config
store := s3.New(s3.Config{
Bucket: "my-bucket-url",
Endpoint: "my-endpoint",
Region: "my-region",
Reset: false,
})

使用 Set() 创建对象

err := store.Set("my-key", []byte("my-value"))

或者,调用 SetWithChecksum() 创建带校验和的对象,以要求 S3 服务器在服务器端验证数据完整性

目前支持 4 种算法

  • types.ChecksumAlgorithmCrc32 (CRC32)
  • types.ChecksumAlgorithmCrc32c (CRC32C)
  • types.ChecksumAlgorithmSha1 (SHA1)
  • types.ChecksumAlgorithmSha256 (SHA256)

更多信息请参阅 PutObjectInput

key := "my-key"
val := []byte("my-value")

hash := sha256.New()
hash.Write(val)
sha256sum := hash.Sum(nil)

// import "github.com/aws/aws-sdk-go-v2/service/s3/types"
checksum = map[types.ChecksumAlgorithm][]byte{
types.ChecksumAlgorithmSha256: sha256sum,
}

err := store.SetWithChecksum(key, val, checksum)

配置

// Config defines the config for storage.
type Config struct {
// S3 bucket name
Bucket string

// AWS endpoint
Endpoint string

// AWS region
Region string

// Request timeout
//
// Optional. Default is 0 (no timeout)
RequestTimeout time.Duration

// Reset clears any existing keys in existing Bucket
//
// Optional. Default is false
Reset bool

// Credentials overrides AWS access key and AWS secret access key. Not recommended.
//
// Optional. Default is Credentials{}
Credentials Credentials

// The maximum number of times requests that encounter retryable failures should be attempted.
//
// Optional. Default is 3
MaxAttempts int

}

type Credentials struct {
AccessKey string
SecretAccessKey string
}

默认配置

默认配置缺少 Bucket、Region 和 Endpoint,这些都是必需的,必须被覆盖

// ConfigDefault is the default config
var ConfigDefault = Config{
Bucket: "",
Region: "",
Endpoint: "",
Credentials: Credentials{},
MaxAttempts: 3,
RequestTimeout: 0,
Reset: false,
}