Help us shape the future of Go! Take the 2026 Go Developer Survey

storage

package
v1.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 1, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

Storage 包

对象存储统一封装,支持阿里云 OSS、腾讯云 COS、AWS S3。

安装

go get github.com/tsopia/go-kit/storage

快速开始

package main

import (
	"context"
	"log"
	"os"
	"strings"
	"time"

	"github.com/tsopia/go-kit/storage"
)

func main() {
	// 初始化
	cfg := &storage.Config{
		Type:            storage.TypeOSS,
		Bucket:          "my-bucket",
		Region:          "cn-hangzhou",
		AccessKeyID:     os.Getenv("OSS_ACCESS_KEY_ID"),
		AccessKeySecret: os.Getenv("OSS_ACCESS_KEY_SECRET"),
	}

	if err := storage.Configure(cfg); err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	// 上传文件
	data := strings.NewReader("hello world")
	if err := storage.Upload(ctx, "test/hello.txt", data); err != nil {
		log.Fatal(err)
	}

	// 生成临时访问链接
	url, err := storage.SignedURL(ctx, "test/hello.txt", 30*time.Minute)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("URL:", url)
}

配置说明

字段 类型 必填 说明
Type Type 是 存储类型: oss/cos/s3
Bucket string 是 存储桶名称
Region string 是 地域,如 cn-hangzhou
Endpoint string 否 自定义端点
AccessKeyID string 是 Access Key ID
AccessKeySecret string 是 访问密钥
DefaultSignExpire duration 否 签名 URL 默认过期时间,默认 15m

API 文档

上传
err := storage.Upload(ctx, "key", reader,
    storage.WithContentType("application/json"),
    storage.WithMetadata("author", "alice"),
    storage.WithMetadata("source", "web"),
)
下载
reader, err := storage.Download(ctx, "key")
if err != nil {
    return err
}
defer reader.Close()
删除
err := storage.Delete(ctx, "key")
预签名 URL

SignedURL 适合基础签名访问或低约束上传场景;如果需要对象存储校验 Content-Type、checksum、metadata 等条件,应该使用下面的“安全直传授权”。

url, err := storage.SignedURL(ctx, "key", 30*time.Minute)
安全直传授权
auth, err := storage.AuthorizeDirectUpload(ctx, storage.DirectUploadRequest{
	ObjectKey:   objectKey,
	ContentType: "image/png",
	Metadata: map[string]string{
		"owner": userID,
	},
	Checksum: &storage.DirectUploadChecksum{
		Algorithm: storage.DirectUploadChecksumMD5,
		Value:     checksum,
	},
})
if err != nil {
	return err
}

// 客户端按 auth.Method / auth.URL / auth.Headers / auth.FormFields 发起上传。
上传后校验

VerifyDirectUploadObject 会校验对象是否存在、Content-Type、metadata 和 size。 checksum 校验依赖 provider 能否从对象元信息回读对应算法:

  • OSS 可回读 Content-MD5
  • S3 仅在对象保存了对应 checksum 时可校验
  • COS 当前只暴露 CRC64,不直接回读 MD5/SHA256
result, err := storage.VerifyDirectUploadObject(ctx, storage.DirectUploadVerificationRequest{
	ObjectKey:   objectKey,
	ContentType: "image/png",
	Metadata: map[string]string{
		"owner": userID,
	},
})
if err != nil {
	return err
}
if !result.Matched {
	return fmt.Errorf("uploaded object does not match authorization")
}
分片上传
// 初始化
upload, err := storage.InitMultipart(ctx, "large.zip")

// 上传分片
part1, err := storage.UploadPart(ctx, upload.UploadID, 1, reader1)
part2, err := storage.UploadPart(ctx, upload.UploadID, 2, reader2)

// 完成
err = storage.CompleteMultipart(ctx, upload.UploadID, []*storage.PartInfo{part1, part2})

多客户端

如果需要使用多个不同的存储配置:

// 获取配置的客户端
client := storage.GetClient()

// 或者使用指定客户端
storage.UploadWithClient(ctx, client, "key", reader)

Documentation

Overview

Package storage 提供对象存储统一封装。

支持阿里云 OSS、腾讯云 COS、AWS S3,通过配置自动切换。

基本使用:

storage.Configure(&storage.Config{
	Type:            storage.TypeOSS,
	Bucket:          "my-bucket",
	Region:          "cn-hangzhou",
	AccessKeyID:     "...",
	AccessKeySecret: "...",
})

if err := storage.Upload(ctx, "file.txt", reader); err != nil {
	return err
}

SignedURL 适合基础签名访问;如果是客户端直传且需要约束 Content-Type、 checksum、metadata 等条件,应使用 AuthorizeDirectUpload,并在上传完成后 调用 VerifyDirectUploadObject 做对象事实校验。

注意:上传后 checksum 校验是否可用取决于 provider 能否从对象元信息回读 对应算法。

更多信息请参考 README.md。

Index

Constants

View Source
const (
	TypeOSS = internal.TypeOSS
	TypeCOS = internal.TypeCOS
	TypeS3  = internal.TypeS3

	DirectUploadModeAuto = internal.DirectUploadModeAuto
	DirectUploadModePut  = internal.DirectUploadModePut
	DirectUploadModePost = internal.DirectUploadModePost

	DirectUploadChecksumMD5    = internal.DirectUploadChecksumMD5
	DirectUploadChecksumSHA256 = internal.DirectUploadChecksumSHA256
)
View Source
const DefaultSignExpire = 15 * time.Minute

DefaultSignExpire 默认签名过期时间

Variables

View Source
var (
	ErrMissingClient                        = errors.New("storage: client not configured")
	ErrInvalidConfig                        = errors.New("storage: invalid configuration")
	ErrUnsupportedType                      = errors.New("storage: unsupported storage type")
	ErrObjectNotFound                       = providers.ErrObjectNotFound
	ErrBucketNotFound                       = providers.ErrBucketNotFound
	ErrAccessDenied                         = providers.ErrAccessDenied
	ErrInvalidCredentials                   = errors.New("storage: invalid credentials")
	ErrMultipartNotFound                    = errors.New("storage: multipart upload not found")
	ErrPartAlreadyExist                     = errors.New("storage: part already uploaded")
	ErrInvalidDirectUploadRequest           = errors.New("storage: invalid direct upload request")
	ErrUnsupportedDirectUploadConstraint    = providers.ErrUnsupportedDirectUploadConstraint
	ErrDirectUploadAuthorizationUnsupported = errors.New("storage: direct upload authorization not supported")
)

Functions

func AbortMultipart

func AbortMultipart(ctx context.Context, uploadID string) error

AbortMultipart 中止分片上传

func AbortMultipartWithClient

func AbortMultipartWithClient(ctx context.Context, c Client, uploadID string) error

AbortMultipartWithClient 使用指定客户端中止分片上传

func CompleteMultipart

func CompleteMultipart(ctx context.Context, uploadID string, parts []*PartInfo, opts ...UploadOptionFunc) error

CompleteMultipart 完成分片上传

func CompleteMultipartWithClient

func CompleteMultipartWithClient(ctx context.Context, c Client, uploadID string, parts []*PartInfo, opts ...UploadOptionFunc) error

CompleteMultipartWithClient 使用指定客户端完成分片上传

func Configure

func Configure(cfg *Config) error

Configure 初始化全局客户端

func Delete

func Delete(ctx context.Context, key string) error

Delete 删除文件

func DeleteBatch

func DeleteBatch(ctx context.Context, keys []string) error

DeleteBatch 批量删除文件

func DeleteBatchWithClient

func DeleteBatchWithClient(ctx context.Context, c Client, keys []string) error

DeleteBatchWithClient 使用指定客户端批量删除

func DeleteWithClient

func DeleteWithClient(ctx context.Context, c Client, key string) error

DeleteWithClient 使用指定客户端删除

func Download

func Download(ctx context.Context, key string, opts ...DownloadOptionFunc) (io.ReadCloser, error)

Download 下载文件

func DownloadWithClient

func DownloadWithClient(ctx context.Context, c Client, key string, opts ...DownloadOptionFunc) (io.ReadCloser, error)

DownloadWithClient 使用指定客户端下载

func Exists

func Exists(ctx context.Context, key string) (bool, error)

Exists 检查文件是否存在

func ExistsWithClient

func ExistsWithClient(ctx context.Context, c Client, key string) (bool, error)

ExistsWithClient 使用指定客户端检查存在

func SignedURL

func SignedURL(ctx context.Context, key string, expire time.Duration, opts ...SignOptionFunc) (string, error)

SignedURL 生成签名 URL

func SignedURLWithClient

func SignedURLWithClient(ctx context.Context, c Client, key string, expire time.Duration, opts ...SignOptionFunc) (string, error)

SignedURLWithClient 使用指定客户端生成签名 URL

func Upload

func Upload(ctx context.Context, key string, reader io.Reader, opts ...UploadOptionFunc) error

Upload 上传文件

func UploadWithClient

func UploadWithClient(ctx context.Context, c Client, key string, reader io.Reader, opts ...UploadOptionFunc) error

UploadWithClient 使用指定客户端上传

Types

type Client

type Client = internal.Client

func GetClient

func GetClient() Client

GetClient 获取全局客户端

type Config

type Config = internal.Config

type DirectUploadAuthorization added in v1.3.3

type DirectUploadAuthorization = internal.DirectUploadAuthorization

func AuthorizeDirectUpload added in v1.3.3

func AuthorizeDirectUpload(ctx context.Context, req DirectUploadRequest) (*DirectUploadAuthorization, error)

AuthorizeDirectUpload 生成客户端直传授权结果。

func AuthorizeDirectUploadWithClient added in v1.3.3

func AuthorizeDirectUploadWithClient(ctx context.Context, c Client, req DirectUploadRequest) (*DirectUploadAuthorization, error)

AuthorizeDirectUploadWithClient 使用指定客户端生成客户端直传授权结果。

type DirectUploadChecksum added in v1.3.3

type DirectUploadChecksum = internal.DirectUploadChecksum

type DirectUploadChecksumAlgorithm added in v1.3.3

type DirectUploadChecksumAlgorithm = internal.DirectUploadChecksumAlgorithm

type DirectUploadConstraints added in v1.3.3

type DirectUploadConstraints = internal.DirectUploadConstraints

type DirectUploadMismatch added in v1.3.3

type DirectUploadMismatch = internal.DirectUploadMismatch

type DirectUploadMode added in v1.3.3

type DirectUploadMode = internal.DirectUploadMode

type DirectUploadRequest added in v1.3.3

type DirectUploadRequest = internal.DirectUploadRequest

type DirectUploadSize added in v1.3.3

type DirectUploadSize = internal.DirectUploadSize

type DirectUploadVerificationRequest added in v1.3.3

type DirectUploadVerificationRequest = internal.DirectUploadVerificationRequest

type DirectUploadVerificationResult added in v1.3.3

type DirectUploadVerificationResult = internal.DirectUploadVerificationResult

func VerifyDirectUploadObject added in v1.3.3

VerifyDirectUploadObject 校验客户端直传后的对象状态。

func VerifyDirectUploadObjectWithClient added in v1.3.3

func VerifyDirectUploadObjectWithClient(ctx context.Context, c Client, req DirectUploadVerificationRequest) (*DirectUploadVerificationResult, error)

VerifyDirectUploadObjectWithClient 使用指定客户端校验客户端直传后的对象状态。

type DownloadOption

type DownloadOption = internal.DownloadOption

type DownloadOptionFunc

type DownloadOptionFunc = internal.DownloadOptionFunc

type MultipartUpload

type MultipartUpload = internal.MultipartUpload

func InitMultipart

func InitMultipart(ctx context.Context, key string, opts ...UploadOptionFunc) (*MultipartUpload, error)

InitMultipart 初始化分片上传

func InitMultipartWithClient

func InitMultipartWithClient(ctx context.Context, c Client, key string, opts ...UploadOptionFunc) (*MultipartUpload, error)

InitMultipartWithClient 使用指定客户端初始化分片上传

type ObjectInfo

type ObjectInfo = internal.ObjectInfo

重新导出 internal 包中的类型

type PartInfo

type PartInfo = internal.PartInfo

func UploadPart

func UploadPart(ctx context.Context, uploadID string, partNum int, reader io.Reader, opts ...UploadOptionFunc) (*PartInfo, error)

UploadPart 上传分片

func UploadPartWithClient

func UploadPartWithClient(ctx context.Context, c Client, uploadID string, partNum int, reader io.Reader, opts ...UploadOptionFunc) (*PartInfo, error)

UploadPartWithClient 使用指定客户端上传分片

type SignOption

type SignOption = internal.SignOption

type SignOptionFunc

type SignOptionFunc = internal.SignOptionFunc

func WithSignMethod

func WithSignMethod(method string) SignOptionFunc

WithSignMethod 设置签名方法

type UploadOption

type UploadOption = internal.UploadOption

type UploadOptionFunc

type UploadOptionFunc = internal.UploadOptionFunc

func WithContentType

func WithContentType(ct string) UploadOptionFunc

WithContentType 设置 Content-Type

func WithMetadata added in v1.3.3

func WithMetadata(key, value string) UploadOptionFunc

WithMetadata 设置对象 metadata。

Directories

Path Synopsis
cos
oss
s3

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL