cystore

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2025 License: MIT Imports: 7 Imported by: 0

README

CyStore - 统一云存储接口

CyStore 提供了一个统一的云存储接口,支持多种云存储服务,如 MinIO、S3、华为云 OBS、阿里云 OSS 等。

特性

  • 统一的接口定义,支持多种云存储服务
  • 简单易用的 API,支持常见的存储操作
  • 支持预签名 URL 生成
  • 支持元数据管理
  • 支持桶(Bucket)管理
  • 支持华为云 OBS 和阿里云 OSS

安装

首先,确保已添加所需的客户端依赖:

# MinIO 客户端
go get github.com/minio/minio-go/v7

# 华为云 OBS 客户端
go get github.com/huaweicloud/huaweicloud-sdk-go-obs/obs

# 阿里云 OSS 客户端
go get github.com/aliyun/aliyun-oss-go-sdk/oss

配置示例

新的配置结构已经统一,只需要指定一个提供商类型和对应的公共配置即可。

MinIO 配置
import (
    "github.com/fj1981/infrakit/pkg/cystore"
)

config := &cystore.Config{
    Provider:   cystore.ProviderMinio,
    Region:     "us-east-1",
    Secure:     true,
    Endpoint:   "play.min.io",
    AccessKey:  "your-access-key",
    SecretKey:  "your-secret-key",
    UseSSL:     true,
}

// 创建存储客户端
store, err := cystore.NewStore(config)
if err != nil {
    // 处理错误
}
华为云 OBS 配置
import (
    "github.com/fj1981/infrakit/pkg/cystore"
)

config := &cystore.Config{
    Provider:   cystore.ProviderHuaweiOBS,
    Region:     "cn-north-4",
    Secure:     true,
    Endpoint:   "obs.cn-north-4.myhuaweicloud.com",
    AccessKey:  "your-access-key",
    SecretKey:  "your-secret-key",
    UseSSL:     true,
    // 可选参数
    SessionToken: "your-security-token", // 如果需要使用临时凭证
}

// 创建存储客户端
store, err := cystore.NewStore(config)
if err != nil {
    // 处理错误
}
阿里云 OSS 配置
import (
    "github.com/fj1981/infrakit/pkg/cystore"
)

config := &cystore.Config{
    Provider:   cystore.ProviderAliyunOSS,
    Region:     "oss-cn-hangzhou",
    Secure:     true,
    Endpoint:   "oss-cn-hangzhou.aliyuncs.com",
    AccessKey:  "your-access-key",
    SecretKey:  "your-secret-key",
    UseSSL:     true,
}

// 创建存储客户端
store, err := cystore.NewStore(config)
if err != nil {
    // 处理错误
}
本地文件存储配置
import (
    "github.com/fj1981/infrakit/pkg/cystore"
)

config := &cystore.Config{
    Provider: cystore.ProviderLocal,
    BasePath: "/path/to/storage",
}

// 创建存储客户端
store, err := cystore.NewStore(config)
if err != nil {
    // 处理错误
}

使用示例

上传文件
import (
    "context"
    "os"
    "path/filepath"
)

func uploadFile(store *cystore.Store, bucketName, filePath string) error {
    // 打开文件
    file, err := os.Open(filePath)
    if err != nil {
        return err
    }
    defer file.Close()

    // 获取文件信息
    fileInfo, err := file.Stat()
    if err != nil {
        return err
    }

    // 获取文件名
    fileName := filepath.Base(filePath)
    
    // 获取内容类型
    contentType := cystore.GetContentType(fileName)

    // 上传文件
    ctx := context.Background()
    _, err = store.Upload(ctx, bucketName, fileName, file, fileInfo.Size(), contentType)
    return err
}
下载文件
func downloadFile(store *cystore.Store, bucketName, objectName, destPath string) error {
    ctx := context.Background()
    
    // 下载文件
    reader, _, err := store.Download(ctx, bucketName, objectName)
    if err != nil {
        return err
    }
    defer reader.Close()
    
    // 创建目标文件
    destFile, err := os.Create(destPath)
    if err != nil {
        return err
    }
    defer destFile.Close()
    
    // 复制内容
    _, err = io.Copy(destFile, reader)
    return err
}
生成预签名 URL
func getDownloadURL(store *cystore.Store, bucketName, objectName string) (string, error) {
    ctx := context.Background()
    
    // 生成有效期为 1 小时的下载链接
    return store.GetURL(ctx, bucketName, objectName, 3600)
}

func getUploadURL(store *cystore.Store, bucketName, objectName string) (string, error) {
    ctx := context.Background()
    
    // 生成有效期为 1 小时的上传链接
    return store.PutURL(ctx, bucketName, objectName, 3600)
}
列出文件
func listFiles(store *cystore.Store, bucketName, prefix string) ([]cystore.ObjectInfo, error) {
    ctx := context.Background()
    
    // 列出指定前缀的所有文件
    return store.ListFiles(ctx, bucketName, prefix)
}
删除文件
func deleteFile(store *cystore.Store, bucketName, objectName string) error {
    ctx := context.Background()
    
    // 删除文件
    return store.Delete(ctx, bucketName, objectName)
}

高级用法

直接使用底层 Provider

如果需要使用底层 Provider 提供的特定功能,可以通过 Provider() 方法获取:

// 获取底层 Provider
provider := store.Provider()

// 使用 Provider 特定的功能
ctx := context.Background()
buckets, err := provider.ListBuckets(ctx)

扩展

要添加新的存储提供商,只需实现 Provider 接口并在 NewStore 函数中添加相应的初始化逻辑。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidConfig     = errors.New("invalid storage configuration")
	ErrProviderNotFound  = errors.New("storage provider not found")
	ErrBucketNotFound    = errors.New("bucket not found")
	ErrObjectNotFound    = errors.New("object not found")
	ErrInvalidObjectName = errors.New("invalid object name")
)

Common errors

View Source
var (
	ErrBucketRequired = errors.New("bucket is required and no default bucket is set")
)

Functions

func BuildPath

func BuildPath(components ...string) string

BuildPath builds a path from components

func GetContentType

func GetContentType(filename string) string

GetContentType determines the content type based on file extension

func RegistProvider

func RegistProvider(name string, funcProvider FuncNewStore)

func SplitPath

func SplitPath(path string) (dir, file string)

SplitPath splits a path into directory and filename

Types

type BucketInfo

type BucketInfo struct {
	Name         string    // Name of the bucket
	CreationDate time.Time // Creation date of the bucket
}

BucketInfo contains information about a bucket

type Config

type Config struct {
	// Provider type (minio, local, etc.)
	Provider ProviderType `json:"provider" yaml:"provider"`

	// Common settings
	Region  string        `json:"region" yaml:"region"`
	Secure  bool          `json:"secure" yaml:"secure"`
	Timeout time.Duration `json:"timeout" yaml:"timeout"`

	// Unified storage settings
	// These fields are used across different providers
	Endpoint     string `json:"endpoint" yaml:"endpoint"`
	AccessKey    string `json:"access_key" yaml:"access_key"`
	SecretKey    string `json:"secret_key" yaml:"secret_key"`
	SessionToken string `json:"session_token,omitempty" yaml:"session_token,omitempty"`
	UseSSL       bool   `json:"use_ssl" yaml:"use_ssl"`

	// Provider-specific settings that don't fit in the common fields
	// Local storage specific
	BasePath string `json:"base_path,omitempty" yaml:"base_path,omitempty"`
}

Config represents the unified configuration for all storage providers

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration

type FuncNewStore

type FuncNewStore func(config *Config) (Provider, error)

type GetObjectOptions

type GetObjectOptions struct {
	Range        string // Range of bytes to download
	MatchETag    string // Download object if ETag matches
	NotMatchETag string // Download object if ETag doesn't match
}

GetObjectOptions specifies options for GetObject operation

type ObjectInfo

type ObjectInfo struct {
	Bucket       string            // Bucket name
	Name         string            // Object name
	ETag         string            // ETag of the object
	Size         int64             // Size of the object
	LastModified time.Time         // Last modified time of the object
	ContentType  string            // Content type of the object
	Metadata     map[string]string // User-defined metadata
}

ObjectInfo contains information about an object

type Option

type Option func(*Store)

func WithBucket

func WithBucket(bucket string) Option

WithBucket sets the default bucket for all operations

type Provider

type Provider interface {
	// Bucket operations
	BucketExists(ctx context.Context, bucketName string) (bool, error)
	CreateBucket(ctx context.Context, bucketName string) error
	RemoveBucket(ctx context.Context, bucketName string) error
	ListBuckets(ctx context.Context) ([]BucketInfo, error)

	// Object operations
	PutObject(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64, opts PutObjectOptions) (ObjectInfo, error)
	GetObject(ctx context.Context, bucketName, objectName string, opts GetObjectOptions) (io.ReadCloser, ObjectInfo, error)
	StatObject(ctx context.Context, bucketName, objectName string) (ObjectInfo, error)
	RemoveObject(ctx context.Context, bucketName, objectName string) error
	ListObjects(ctx context.Context, bucketName, prefix string, recursive bool) <-chan ObjectInfo

	// Presigned URL operations
	PresignedGetObject(ctx context.Context, bucketName, objectName string, expires time.Duration) (string, error)
	PresignedPutObject(ctx context.Context, bucketName, objectName string, expires time.Duration) (string, error)
}

Provider defines the interface for cloud storage operations

type ProviderType

type ProviderType string

ProviderType represents the type of storage provider

const (
	// ProviderMinio represents MinIO/S3 compatible storage
	ProviderMinio ProviderType = "minio"
	// ProviderLocal represents local file system storage
	ProviderLocal ProviderType = "local"
	// ProviderHuaweiOBS represents Huawei Cloud Object Storage Service
	ProviderHuaweiOBS ProviderType = "huawei_obs"
	// ProviderAliyunOSS represents Alibaba Cloud Object Storage Service
	ProviderAliyunOSS ProviderType = "aliyun_oss"
)

type PutObjectOptions

type PutObjectOptions struct {
	ContentType string            // Content type of the object
	Metadata    map[string]string // User-defined metadata
}

PutObjectOptions specifies options for PutObject operation

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store provides a unified interface for cloud storage operations

func NewStore

func NewStore(config *Config, opts ...Option) (*Store, error)

NewStore creates a new storage client based on the provided configuration

func (*Store) Config

func (s *Store) Config() *Config

Config returns the store configuration

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, objectPath string, bucket ...string) error

Delete deletes a file from the specified bucket and object path If bucket is nil, the default bucket will be used if set

func (*Store) Download

func (s *Store) Download(ctx context.Context, objectPath string, bucket ...string) (io.ReadCloser, error)

Download downloads a file from the specified bucket and object path If bucket is nil, the default bucket will be used if set

func (*Store) EnsureBucket

func (s *Store) EnsureBucket(ctx context.Context, bucketName string) error

EnsureBucket ensures that a bucket exists, creating it if necessary

func (*Store) FileExists

func (s *Store) FileExists(ctx context.Context, objectPath string, bucket ...string) (bool, error)

FileExists checks if a file exists

func (*Store) GeneratePresignedURL

func (s *Store) GeneratePresignedURL(ctx context.Context, objectPath string, expiry time.Duration, bucket ...string) (string, error)

GeneratePresignedURL generates a presigned URL for the given object If bucket is nil, the default bucket will be used if set

func (*Store) GetObjectInfo

func (s *Store) GetObjectInfo(ctx context.Context, objectPath string, bucket ...string) (ObjectInfo, error)

GetObjectInfo gets metadata for an object If bucket is nil, the default bucket will be used if set

func (*Store) ListObjects

func (s *Store) ListObjects(ctx context.Context, prefix string, bucket ...string) ([]ObjectInfo, error)

ListObjects lists objects in a bucket with the given prefix If bucket is nil, the default bucket will be used if set

func (*Store) Provider

func (s *Store) Provider() Provider

Provider returns the underlying provider

func (*Store) PutURL

func (s *Store) PutURL(ctx context.Context, bucketName, objectPath string, expirySeconds int) (string, error)

PutURL generates a presigned URL for uploading an object

func (*Store) Upload

func (s *Store) Upload(ctx context.Context, objectPath string, data io.Reader, size int64, contentType string, bucket ...string) (string, error)

Upload uploads a file to the specified bucket and object path If bucket is nil, the default bucket will be used if set

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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