oss

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package oss 提供统一的对象存储抽象。

oss 包只定义对象存储的通用接口、选项、错误模型和数据结构,不绑定具体云厂商。 具体实现放在 adapter 子包中,例如 github.com/f2xme/gox/oss/adapter/aliyun。

功能特性

  • 统一接口:抽象上传、下载、删除、元信息、列表和预签名 URL
  • 能力分层:基础对象操作与存储桶管理分离
  • 分页列表:List 返回对象、公共前缀、下一页令牌和截断状态
  • 错误模型:使用统一错误码,并提供 IsNotFound、IsAccessDenied 等判断函数
  • Options 模式:上传、下载、列表、预签名和存储桶操作都使用函数式选项
  • Adapter 扩展:新增云厂商实现时只需实现 Storage 接口

快速开始

使用阿里云 OSS adapter:

package main

import (
	"context"
	"strings"
	"time"

	"github.com/f2xme/gox/oss"
	"github.com/f2xme/gox/oss/adapter/aliyun"
)

func main() {
	storage, err := aliyun.New(
		aliyun.WithEndpoint("oss-cn-hangzhou.aliyuncs.com"),
		aliyun.WithCredentials("access-key-id", "access-key-secret"),
		aliyun.WithBucket("my-bucket"),
	)
	if err != nil {
		return
	}

	ctx := context.Background()
	_ = storage.Put(ctx, "hello.txt", strings.NewReader("hello"),
		oss.WithContentType("text/plain"),
	)

	body, err := storage.Get(ctx, "hello.txt")
	if err == nil {
		defer body.Close()
	}

	_, _ = storage.SignURL(ctx, "hello.txt",
		oss.WithMethod(oss.MethodGet),
		oss.WithExpires(time.Hour),
	)
}

核心接口

Storage 定义对象级操作:

type Storage interface {
	Put(ctx context.Context, key string, reader io.Reader, opts ...PutOption) error
	Get(ctx context.Context, key string, opts ...GetOption) (io.ReadCloser, error)
	Delete(ctx context.Context, key string) error
	Stat(ctx context.Context, key string) (*ObjectInfo, error)
	Exists(ctx context.Context, key string) (bool, error)
	List(ctx context.Context, opts ...ListOption) (*ListResult, error)
	SignURL(ctx context.Context, key string, opts ...SignOption) (string, error)
}

BucketStorage 定义可选的存储桶管理能力。业务代码只在确实需要创建、删除或列出 Bucket 时依赖该接口,普通对象读写只依赖 Storage。

列表分页

List 返回 ListResult:

result, err := storage.List(ctx,
	oss.WithPrefix("photos/"),
	oss.WithDelimiter("/"),
	oss.WithLimit(100),
)
if err != nil {
	return
}

for _, obj := range result.Objects {
	_ = obj.Key
}
if result.Truncated {
	next, _ := storage.List(ctx, oss.WithToken(result.NextToken))
	_ = next
}

错误处理

Adapter 会尽量把云厂商错误转换为 *oss.Error:

_, err := storage.Get(ctx, "missing.txt")
if oss.IsNotFound(err) {
	// 对象不存在
} else if oss.IsAccessDenied(err) {
	// 权限不足
}

Adapter 约定

新增 adapter 时建议放在 oss/adapter/<provider> 下,使用纯 Options 模式创建实例, 不依赖 gox 内部其他包,并实现 Storage。若 provider 支持 Bucket 管理,再额外实现 BucketStorage。

注意事项

  • Storage 实现应当是并发安全的
  • key 的组织方式由业务决定,oss 包不会修改 key
  • 预签名 URL 的方法必须使用 MethodGet、MethodPut 或 MethodDelete
  • 集成测试应显式依赖环境变量,避免默认访问真实云服务

Index

Constants

View Source
const (
	// ErrCodeNotFound 表示对象不存在
	ErrCodeNotFound = "NotFound"
	// ErrCodeAccessDenied 表示访问被拒绝
	ErrCodeAccessDenied = "AccessDenied"
	// ErrCodeInvalidArgument 表示参数无效
	ErrCodeInvalidArgument = "InvalidArgument"
	// ErrCodeBucketNotEmpty 表示存储桶不为空
	ErrCodeBucketNotEmpty = "BucketNotEmpty"
	// ErrCodeBucketExists 表示存储桶已存在
	ErrCodeBucketExists = "BucketAlreadyExists"
	// ErrCodeInternal 表示内部错误
	ErrCodeInternal = "InternalError"
)
View Source
const (
	// MethodGet 表示 HTTP GET 方法
	MethodGet = "GET"
	// MethodPut 表示 HTTP PUT 方法
	MethodPut = "PUT"
	// MethodDelete 表示 HTTP DELETE 方法
	MethodDelete = "DELETE"
)

Variables

This section is empty.

Functions

func DetectContentType

func DetectContentType(key string) string

DetectContentType 根据文件扩展名检测 Content-Type

func ErrorCode added in v0.15.1

func ErrorCode(err error) string

ErrorCode 返回统一错误码

func IsAccessDenied added in v0.15.1

func IsAccessDenied(err error) bool

IsAccessDenied 判断错误是否为访问被拒绝

func IsCode added in v0.15.1

func IsCode(err error, code string) bool

IsCode 判断错误是否为指定错误码

func IsNotFound added in v0.15.1

func IsNotFound(err error) bool

IsNotFound 判断错误是否为对象不存在

func IsPermissionDenied deprecated added in v0.15.1

func IsPermissionDenied(err error) bool

IsPermissionDenied 判断错误是否为访问被拒绝

Deprecated: 使用 IsAccessDenied。

Types

type Bucket

type Bucket struct {
	// Name 存储桶名称
	Name string
	// CreationDate 创建时间
	CreationDate time.Time
	// Region 所属地域
	Region string
}

Bucket 定义存储桶信息

type BucketOption added in v0.15.1

type BucketOption func(*BucketOptions)

BucketOption 定义存储桶配置选项

func WithBucketACL added in v0.15.1

func WithBucketACL(acl string) BucketOption

WithBucketACL 设置存储桶访问控制策略

示例:

storage.CreateBucket(ctx, "my-bucket", oss.WithBucketACL("private"))

func WithBucketRegion added in v0.15.1

func WithBucketRegion(region string) BucketOption

WithBucketRegion 设置存储桶地域

示例:

storage.CreateBucket(ctx, "my-bucket", oss.WithBucketRegion("oss-cn-hangzhou"))

type BucketOptions added in v0.15.1

type BucketOptions struct {
	// Region 存储桶地域
	Region string
	// ACL 存储桶访问控制策略
	ACL string
}

BucketOptions 定义存储桶配置选项

func ApplyBucketOptions added in v0.15.1

func ApplyBucketOptions(opts ...BucketOption) BucketOptions

ApplyBucketOptions 合并存储桶选项

type BucketStorage added in v0.15.1

type BucketStorage interface {
	// CreateBucket 创建存储桶
	CreateBucket(ctx context.Context, bucket string, opts ...BucketOption) error
	// DeleteBucket 删除存储桶
	DeleteBucket(ctx context.Context, bucket string) error
	// ListBuckets 列出存储桶
	ListBuckets(ctx context.Context) ([]*Bucket, error)
}

BucketStorage 定义存储桶管理能力

type Error

type Error struct {
	// Code 错误码
	Code string
	// Message 错误消息
	Message string
	// Key 对象键(如果适用)
	Key string
	// Err 原始错误
	Err error
}

Error OSS 错误

func NewError

func NewError(code, message string, key ...string) *Error

NewError 创建一个新的 OSS 错误

func WrapError

func WrapError(code, message string, err error, key ...string) *Error

WrapError 包装一个错误为 OSS 错误

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type GetOption

type GetOption func(*GetOptions)

GetOption 定义下载选项函数

func WithRange

func WithRange(start, end int64) GetOption

WithRange 设置范围下载

示例:

// 下载前 1KB
storage.Get(ctx, key, oss.WithRange(0, 1023))

type GetOptions

type GetOptions struct {
	// RangeStart 起始字节位置,-1 表示不使用范围下载
	RangeStart int64
	// RangeEnd 结束字节位置
	RangeEnd int64
}

GetOptions 定义下载配置选项

func ApplyGetOptions added in v0.15.1

func ApplyGetOptions(opts ...GetOption) GetOptions

ApplyGetOptions 合并下载选项

type ListOption

type ListOption func(*ListOptions)

ListOption 定义列表选项函数

func WithDelimiter

func WithDelimiter(delimiter string) ListOption

WithDelimiter 设置分隔符

示例:

storage.List(ctx, oss.WithDelimiter("/"))

func WithLimit added in v0.15.1

func WithLimit(limit int) ListOption

WithLimit 设置最大返回数量

示例:

storage.List(ctx, oss.WithLimit(100))

func WithMarker deprecated

func WithMarker(marker string) ListOption

WithMarker 设置兼容旧调用的分页标记

Deprecated: 使用 WithToken。

func WithMaxKeys

func WithMaxKeys(maxKeys int) ListOption

WithMaxKeys 设置最大返回数量

示例:

storage.List(ctx, oss.WithMaxKeys(100))

func WithPrefix

func WithPrefix(prefix string) ListOption

WithPrefix 设置对象键前缀

示例:

storage.List(ctx, oss.WithPrefix("images/"))

func WithToken added in v0.15.1

func WithToken(token string) ListOption

WithToken 设置分页令牌

示例:

storage.List(ctx, oss.WithToken(result.NextToken))

type ListOptions

type ListOptions struct {
	// Prefix 对象键前缀
	Prefix string
	// Delimiter 分隔符,常用 "/" 模拟目录
	Delimiter string
	// Limit 最大返回数量
	Limit int
	// Token 分页令牌
	Token string
}

ListOptions 定义列表配置选项

func ApplyListOptions added in v0.15.1

func ApplyListOptions(opts ...ListOption) ListOptions

ApplyListOptions 合并列表选项

type ListResult added in v0.15.1

type ListResult struct {
	// Objects 对象列表
	Objects []*Object
	// Prefixes 按分隔符折叠出的公共前缀
	Prefixes []string
	// NextToken 下一页令牌,空值表示没有下一页
	NextToken string
	// Truncated 表示结果是否被截断
	Truncated bool
}

ListResult 定义对象列表结果

type Object

type Object struct {
	// Key 对象键
	Key string
	// Size 对象大小,单位字节
	Size int64
	// LastModified 最后修改时间
	LastModified time.Time
	// ETag 对象实体标签
	ETag string
	// ContentType 内容类型
	ContentType string
}

Object 定义对象列表中的基础信息

type ObjectInfo

type ObjectInfo struct {
	// Key 对象键
	Key string
	// Size 对象大小,单位字节
	Size int64
	// LastModified 最后修改时间
	LastModified time.Time
	// ETag 对象实体标签
	ETag string
	// ContentType 内容类型
	ContentType string
	// Metadata 用户自定义元数据
	Metadata map[string]string
}

ObjectInfo 定义对象元信息

type PresignedOption deprecated

type PresignedOption = SignOption

PresignedOption 定义兼容旧名称的预签名选项函数

Deprecated: 使用 SignOption。

type PresignedOptions deprecated

type PresignedOptions = SignOptions

PresignedOptions 定义兼容旧名称的预签名配置选项

Deprecated: 使用 SignOptions。

type PutOption

type PutOption func(*PutOptions)

PutOption 定义上传选项函数

func WithContentType

func WithContentType(contentType string) PutOption

WithContentType 设置内容类型

示例:

storage.Put(ctx, key, reader, oss.WithContentType("image/jpeg"))

func WithMetadata

func WithMetadata(metadata map[string]string) PutOption

WithMetadata 设置自定义元数据

示例:

storage.Put(ctx, key, reader, oss.WithMetadata(map[string]string{
	"author": "alice",
	"version": "1.0",
}))

type PutOptions

type PutOptions struct {
	// ContentType 内容类型,空值时根据对象键自动推断
	ContentType string
	// Metadata 用户自定义元数据
	Metadata map[string]string
}

PutOptions 定义上传配置选项

func ApplyPutOptions added in v0.15.1

func ApplyPutOptions(opts ...PutOption) PutOptions

ApplyPutOptions 合并上传选项

type SignOption added in v0.15.1

type SignOption func(*SignOptions)

SignOption 定义预签名选项函数

func WithExpires

func WithExpires(expires time.Duration) SignOption

WithExpires 设置过期时间

示例:

storage.SignURL(ctx, key, oss.WithExpires(30*time.Minute))

func WithMethod

func WithMethod(method string) SignOption

WithMethod 设置 HTTP 方法

示例:

storage.SignURL(ctx, key, oss.WithMethod(oss.MethodPut))

func WithSignContentType added in v0.15.1

func WithSignContentType(contentType string) SignOption

WithSignContentType 设置预签名请求的内容类型

示例:

storage.SignURL(ctx, key, oss.WithMethod(oss.MethodPut), oss.WithSignContentType("image/png"))

type SignOptions added in v0.15.1

type SignOptions struct {
	// Method HTTP 方法
	Method string
	// Expires 过期时间
	Expires time.Duration
	// ContentType PUT 预签名时使用的内容类型
	ContentType string
}

SignOptions 定义预签名配置选项

func ApplySignOptions added in v0.15.1

func ApplySignOptions(opts ...SignOption) SignOptions

ApplySignOptions 合并预签名选项

type Storage

type Storage interface {
	// Put 上传对象
	Put(ctx context.Context, key string, reader io.Reader, opts ...PutOption) error
	// Get 下载对象
	Get(ctx context.Context, key string, opts ...GetOption) (io.ReadCloser, error)
	// Delete 删除对象
	Delete(ctx context.Context, key string) error
	// Stat 获取对象元信息
	Stat(ctx context.Context, key string) (*ObjectInfo, error)
	// Exists 检查对象是否存在
	Exists(ctx context.Context, key string) (bool, error)
	// List 列出对象
	List(ctx context.Context, opts ...ListOption) (*ListResult, error)
	// SignURL 生成预签名 URL
	SignURL(ctx context.Context, key string, opts ...SignOption) (string, error)
}

Storage 对象存储统一接口

Directories

Path Synopsis
adapter
memory
Package memory 提供基于内存的 oss.Storage 和 oss.BucketStorage 实现。
Package memory 提供基于内存的 oss.Storage 和 oss.BucketStorage 实现。
aliyun module

Jump to

Keyboard shortcuts

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