oss

package module
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: Apache-2.0 Imports: 10 Imported by: 2

README

OSS - Object Storage Service

English | 简体中文

A unified object storage abstraction layer. The base oss module provides the interface, registry, configuration, validation, and local filesystem implementation. Cloud providers are optional submodules.

Features

  • Multi-Cloud Support: AWS S3, Azure Blob, Aliyun OSS, Tencent COS, Google Cloud Storage, MinIO, Qiniu Kodo, Synology NAS, and local filesystem
  • Unified Interface: All storage providers implement the same consistent API
  • Explicit Registration: Cloud drivers register through opt-in blank imports
  • Official SDKs: Leverages official SDKs from each cloud provider
  • Local Storage: Built-in support for local filesystem storage
  • Lightweight: Standalone module with minimal dependencies

Installation

go get github.com/ncobase/ncore/oss
go get github.com/ncobase/ncore/oss/minio

Quick Start

package main

import (
    "fmt"
    "strings"

    "github.com/ncobase/ncore/oss"

    _ "github.com/ncobase/ncore/oss/minio"
)

func main() {
    // Create storage configuration
    cfg := &oss.Config{
        Provider: "minio",
        ID:       "minioadmin",
        Secret:   "minioadmin",
        Bucket:   "mybucket",
        Endpoint: "http://localhost:9000",
    }

    // Create storage instance
    storage, err := oss.NewStorage(cfg)
    if err != nil {
        panic(err)
    }

    // Upload file
    content := strings.NewReader("Hello, World!")
    obj, err := storage.Put("test.txt", content)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Uploaded: %s\n", obj.Path)

    // Check if file exists
    exists, err := storage.Exists("test.txt")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Exists: %v\n", exists)

    // Get file metadata
    stat, err := storage.Stat("test.txt")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Size: %d bytes\n", stat.Size)

    // Get file
    file, err := storage.Get("test.txt")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // Get presigned download URL
    url, err := storage.GetURL("test.txt")
    if err != nil {
        panic(err)
    }
    fmt.Printf("URL: %s\n", url)

    // Delete file
    if err := storage.Delete("test.txt"); err != nil {
        panic(err)
    }
}

Supported Providers

Provider Provider Value Provider Module Required Config
AWS S3 s3 github.com/ncobase/ncore/oss/s3 ID, Secret, Bucket, Region
Cloudflare R2 r2 github.com/ncobase/ncore/oss/s3 ID, Secret, Bucket, Endpoint (Region defaults to auto)
Backblaze B2 (S3) b2 github.com/ncobase/ncore/oss/s3 ID, Secret, Bucket, Endpoint, Region
Azure Blob azure github.com/ncobase/ncore/oss/azure ID (account), Secret (key), Bucket (Endpoint optional)
Aliyun OSS aliyun / oss github.com/ncobase/ncore/oss/aliyun ID, Secret, Bucket, Region
Tencent COS tencent / cos github.com/ncobase/ncore/oss/tencent ID, Secret, Bucket, Region, AppID (or bucket as <bucket>-<app_id>)
Google Cloud Storage gcs github.com/ncobase/ncore/oss/gcs Bucket, ServiceAccountJSON or Secret
MinIO minio github.com/ncobase/ncore/oss/minio ID, Secret, Bucket, Endpoint
Qiniu Kodo qiniu github.com/ncobase/ncore/oss/qiniu ID, Secret, Bucket, Region, Endpoint
Synology NAS synology github.com/ncobase/ncore/oss/synology ID, Secret, Bucket, Endpoint
Local Filesystem filesystem / local built in Bucket (path, defaults to ./uploads)

Configuration Examples

AWS S3
cfg := &oss.Config{
    Provider: "s3",
    ID:       "your-access-key-id",
    Secret:   "your-secret-access-key",
    Bucket:   "my-bucket",
    Region:   "us-east-1",
}
MinIO
cfg := &oss.Config{
    Provider: "minio",
    ID:       "minioadmin",
    Secret:   "minioadmin",
    Bucket:   "mybucket",
    Endpoint: "http://localhost:9000",
}
Aliyun OSS
cfg := &oss.Config{
    Provider: "aliyun",
    ID:       "your-access-key-id",
    Secret:   "your-access-key-secret",
    Bucket:   "my-bucket",
    Region:   "cn-hangzhou",
}
Tencent COS
cfg := &oss.Config{
    Provider: "tencent",
    ID:       "your-secret-id",
    Secret:   "your-secret-key",
    Bucket:   "my-bucket", // or "my-bucket-1250000000"
    Region:   "ap-guangzhou",
    AppID:    "1234567890",
}
Azure Blob Storage
cfg := &oss.Config{
    Provider: "azure",
    ID:       "your-account-name",
    Secret:   "your-account-key",
    Bucket:   "my-container",
    // Optional for sovereign clouds or custom DNS zones:
    // Endpoint: "https://your-account.blob.core.windows.net",
}

Provider Endpoint References (Official)

Google Cloud Storage
cfg := &oss.Config{
    Provider:           "gcs",
    Bucket:             "my-bucket",
    ServiceAccountJSON: "/path/to/service-account.json",
}
Qiniu Kodo
cfg := &oss.Config{
    Provider: "qiniu",
    ID:       "your-access-key",
    Secret:   "your-secret-key",
    Bucket:   "my-bucket",
    Region:   "cn-east-1",
    Endpoint: "https://my-bucket.qiniudn.com",
}
Synology NAS
cfg := &oss.Config{
    Provider: "synology",
    ID:       "your-access-key",
    Secret:   "your-secret-key",
    Bucket:   "my-bucket",
    Endpoint: "https://nas.example.com:5001",
}
Local Filesystem
cfg := &oss.Config{
    Provider: "filesystem",
    Bucket:   "/var/data/storage",
}

API Reference

Interface
type Interface interface {
    // Get downloads a file to a temporary file and returns the file handle.
    // Caller is responsible for closing the file and removing it when done.
    Get(path string) (*os.File, error)

    // GetStream returns a readable stream for streaming large file downloads.
    // Caller is responsible for closing the reader when done.
    GetStream(path string) (io.ReadCloser, error)

    // Put uploads a file from the given reader to the specified path.
    // Returns object metadata on success.
    Put(path string, reader io.Reader) (*Object, error)

    // Delete removes the file at the specified path.
    // Returns nil if file doesn't exist or was successfully deleted.
    Delete(path string) error

    // List returns all objects under the specified path prefix.
    // Returns empty slice if no objects found.
    List(path string) ([]*Object, error)

    // GetURL generates a presigned URL for downloading the file.
    // URL is typically valid for 1 hour.
    GetURL(path string) (string, error)

    // GetEndpoint returns the storage service endpoint URL.
    GetEndpoint() string

    // Exists checks if an object exists at the specified path.
    Exists(path string) (bool, error)

    // Stat retrieves object metadata without downloading content.
    Stat(path string) (*Object, error)
}
Object
type Object struct {
    Path             string     // File path in storage
    Name             string     // File name
    LastModified     *time.Time // Last modification time
    Size             int64      // File size in bytes
    StorageInterface Interface  // Associated storage interface
}
Config
type Config struct {
    Provider           string // Storage provider: s3, minio, aliyun, azure, tencent, qiniu, gcs, synology, filesystem
    ID                 string // Access key ID / Account name
    Secret             string // Secret access key / Account key
    Region             string // Region (required for cloud storage)
    Bucket             string // Bucket name / Container name / Local path
    Endpoint           string // Custom endpoint (required for MinIO, Synology)
    ServiceAccountJSON string // Service account JSON file path for GCS
    AppID              string // Tencent COS Application ID
    Debug              bool   // Enable debug mode
}

Advanced Usage

List Files
objects, err := storage.List("images/")
if err != nil {
    panic(err)
}

for _, obj := range objects {
    fmt.Printf("File: %s, Size: %d bytes\n", obj.Path, obj.Size)
}
Check File Existence
exists, err := storage.Exists("file.txt")
if err != nil {
    panic(err)
}

if exists {
    fmt.Println("File exists")
} else {
    fmt.Println("File does not exist")
}
Get File Metadata
obj, err := storage.Stat("document.pdf")
if err != nil {
    panic(err)
}

fmt.Printf("File: %s\n", obj.Name)
fmt.Printf("Size: %d bytes\n", obj.Size)
fmt.Printf("Last Modified: %s\n", obj.LastModified)
Stream Download
reader, err := storage.GetStream("large-file.zip")
if err != nil {
    panic(err)
}
defer reader.Close()

// Process the stream...

Custom Drivers

Implement the Driver interface to add support for new storage providers:

type Driver interface {
    // Name returns the driver name.
    Name() string

    // Connect establishes a connection to the storage service.
    Connect(ctx context.Context, cfg *Config) (Interface, error)

    // Close closes the storage connection.
    Close(conn Interface) error
}

Register your driver in an init() function:

func init() {
    oss.RegisterDriver(&myDriver{})
}

Migration from ncore/data/storage

If you are upgrading from an older version:

// Old Code
import "github.com/ncobase/ncore/data/storage"

// New Code
import (
    "github.com/ncobase/ncore/oss"

    _ "github.com/ncobase/ncore/oss/s3"
)

License

See the LICENSE file for details.

Contributing

Pull requests and issues are welcome!

Documentation

Overview

Package oss provides a unified object storage abstraction layer.

The core package contains only the shared interface, configuration, registry, validation, and local filesystem implementation. Cloud providers live in provider subpackages and must be imported explicitly for registration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContentType added in v0.2.5

func ContentType(ext string) string

ContentType returns the MIME content type for the given file extension. Returns an empty string if the extension is not recognized.

func RegisterDriver

func RegisterDriver(driver Driver)

RegisterDriver registers a storage driver. Typically called in the driver package's init function.

func RegisteredDrivers added in v0.2.5

func RegisteredDrivers() []string

RegisteredDrivers returns a snapshot of registered provider names.

Types

type Config

type Config struct {
	Provider           string `json:"provider" yaml:"provider"`                                             // Storage provider: minio, s3, aliyun, azure, tencent, qiniu, gcs, synology, filesystem (aliases: oss/cos/r2/b2)
	ID                 string `json:"id" yaml:"id"`                                                         // Access key ID / Account name
	Secret             string `json:"secret" yaml:"secret"`                                                 // Secret access key / Account key
	Region             string `json:"region" yaml:"region"`                                                 // Region (required for cloud storage)
	Bucket             string `json:"bucket" yaml:"bucket"`                                                 // Bucket name / Container name / Local path
	Endpoint           string `json:"endpoint" yaml:"endpoint"`                                             // Custom endpoint (required for MinIO, Synology)
	ServiceAccountJSON string `json:"service_account_json,omitempty" yaml:"service_account_json,omitempty"` // Service account JSON file path for Google Cloud Storage
	SharedFolder       string `json:"shared_folder,omitempty" yaml:"shared_folder,omitempty"`               // Synology shared folder (optional)
	OtpCode            string `json:"otp_code,omitempty" yaml:"otp_code,omitempty"`                         // Synology 2FA code (optional)
	Debug              bool   `json:"debug,omitempty" yaml:"debug,omitempty"`                               // Enable debug mode (optional)
	AppID              string `json:"app_id,omitempty" yaml:"app_id,omitempty"`                             // Tencent COS Application ID
}

Config holds configuration for object storage providers.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid and sets default values where applicable.

type Driver

type Driver interface {
	// Name returns the driver name.
	Name() string

	// Connect establishes a connection to the storage service.
	Connect(ctx context.Context, cfg *Config) (Interface, error)

	// Close closes the storage connection.
	Close(conn Interface) error
}

Driver defines the storage driver interface. Implement this interface to add support for new storage providers.

func GetDriver

func GetDriver(name string) (Driver, error)

GetDriver retrieves a driver by name. Returns an error if the driver is not registered.

type FileSystem

type FileSystem interface {
	GetFullPath(p string) string
	Get(p string) (*os.File, error)
	GetStream(p string) (io.ReadCloser, error)
	Put(p string, r io.Reader) (*Object, error)
	Delete(p string) error
	List(p string) ([]*Object, error)
	GetEndpoint() string
	GetURL(p string) (string, error)
}

FileSystem represents the interface for file system storage

type Interface

type Interface interface {
	// Get downloads a file to a temporary file and returns the file handle.
	// Caller is responsible for closing the file and removing it when done.
	Get(path string) (*os.File, error)

	// GetStream returns a readable stream for streaming large file downloads.
	// Caller is responsible for closing the reader when done.
	GetStream(path string) (io.ReadCloser, error)

	// Put uploads a file from the given reader to the specified path.
	// Returns object metadata on success.
	Put(path string, reader io.Reader) (*Object, error)

	// Delete removes the file at the specified path.
	// Returns nil if file doesn't exist or was successfully deleted.
	Delete(path string) error

	// List returns all objects under the specified path prefix.
	// Returns empty slice if no objects found.
	List(path string) ([]*Object, error)

	// GetURL generates a presigned URL for downloading the file.
	// URL is typically valid for 1 hour.
	GetURL(path string) (string, error)

	// GetEndpoint returns the storage service endpoint URL.
	GetEndpoint() string

	// Exists checks if an object exists at the specified path.
	Exists(path string) (bool, error)

	// Stat retrieves object metadata without downloading content.
	Stat(path string) (*Object, error)
}

Interface defines unified object storage operations. All storage providers implement this interface for consistent API access.

func NewStorage

func NewStorage(c *Config) (Interface, error)

NewStorage creates a storage instance based on the provided configuration. Automatically selects the appropriate storage provider.

type LocalFileSystem

type LocalFileSystem struct {
	Folder string
}

LocalFileSystem implements the FileSystem interface for local file system storage

func NewFileSystem

func NewFileSystem(folder string) (*LocalFileSystem, error)

NewFileSystem creates a new local file system storage

func (*LocalFileSystem) Delete

func (fs *LocalFileSystem) Delete(p string) error

Delete deletes a file

func (*LocalFileSystem) Exists added in v0.2.3

func (fs *LocalFileSystem) Exists(p string) (bool, error)

Exists checks if a file exists at the specified path.

func (*LocalFileSystem) Get

func (fs *LocalFileSystem) Get(p string) (*os.File, error)

Get receives a file with the given path

func (*LocalFileSystem) GetEndpoint

func (fs *LocalFileSystem) GetEndpoint() string

GetEndpoint gets the endpoint (for FileSystem, it's just the base path)

func (*LocalFileSystem) GetFullPath

func (fs *LocalFileSystem) GetFullPath(p string) string

GetFullPath returns the full path from absolute/relative path

func (*LocalFileSystem) GetStream

func (fs *LocalFileSystem) GetStream(p string) (io.ReadCloser, error)

GetStream gets a file as a stream

func (*LocalFileSystem) GetURL

func (fs *LocalFileSystem) GetURL(p string) (string, error)

GetURL returns the public accessible URL. For local filesystem, returns the relative path.

func (*LocalFileSystem) List

func (fs *LocalFileSystem) List(p string) ([]*Object, error)

List lists files

func (*LocalFileSystem) Put

func (fs *LocalFileSystem) Put(p string, r io.Reader) (*Object, error)

Put stores the reader into the given path

func (*LocalFileSystem) Stat added in v0.2.3

func (fs *LocalFileSystem) Stat(p string) (*Object, error)

Stat retrieves file metadata without reading content.

type Object

type Object struct {
	Path             string     // File path in storage
	Name             string     // File name
	LastModified     *time.Time // Last modification time
	Size             int64      // File size in bytes
	StorageInterface Interface  // Associated storage interface
}

Object represents metadata about a stored object.

func (Object) Get

func (object Object) Get() (*os.File, error)

Get retrieves the file for this object. This is a convenience method that calls the associated storage interface's Get method.

Directories

Path Synopsis
aliyun module
azure module
gcs module
minio module
qiniu module
s3 module
synology module
tencent module

Jump to

Keyboard shortcuts

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