s3

package module
v0.0.0-...-af4755a Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2025 License: MIT Imports: 17 Imported by: 0

README

go-s3

一个轻量级的 Go 封装库,用于更方便地操作 S3 / MinIO / 自建兼容存储

Lightweight Golang SDK for S3/MinIO-compatible storage.


✨ 特性

  • 📦 一行代码上传文件,自动生成访问链接
  • 🔤 自动检测 MIME 类型(支持扩展名与内容嗅探)
  • 🔁 文件命名策略:保留原名 / ULID 自动命名
  • 🧭 完整的访问 URL 自动构建(支持 HTTP / HTTPS)
  • ⚙️ 兼容所有 S3 API(如 AWS、MinIO、Ceph、Wasabi)

🚀 快速开始

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/terobox/go-s3"
)

func main() {
	client, err := s3.New(
		"s3.xbqx.com", // endpoint
		"us-east-1",   // region
		"ACCESS_KEY",
		"SECRET_KEY",
		"BUCKET_NAME", // bucket name
		true,          // use SSL
	)
	if err != nil {
		log.Fatal(err)
	}

	result, err := client.Upload(context.Background(), "local.txt", &s3.UploadOptions{
		Directory:    "test",      // 上传到子目录
		PreserveName: false,       // 自动重命名
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("✅ 上传成功!\n对象键名: %s\n文件大小: %d 字节\n访问链接: %s\n",
		result.Key, result.Size, result.URL)
}

⚙️ 可选上传参数

字段名 类型 说明 默认值
Directory string 上传目录路径(例如 "images/" ""
PreserveName bool 是否保留原文件名 false

📁 上传结果结构体

type UploadResult struct {
    Key         string // 对象键名
    URL         string // 完整访问链接
    Size        int64  // 文件大小
    ContentType string // MIME 类型
}

🧩 TODO

  • 批量上传(支持多文件并发)

📜 License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateULID

func GenerateULID() string

GenerateULID 生成一个新的 ULID(带时间顺序,可排序) 参考:01K8FJ3Q3WA031F7YPV0E9PRBP

func JoinPath

func JoinPath(parts ...string) string

JoinPath 安全拼接 S3 Key 路径

Types

type Client

type Client struct {
	Bucket   string
	Endpoint string // 新增:存储 endpoint 用于构建 URL
	Region   string // 新增:存储 region 用于构建 URL
	UseSSL   bool   // 新增:存储 SSL 配置用于构建 URL
	// contains filtered or unexported fields
}

Client 封装 S3 客户端

func New

func New(endpoint, region, key, secret, bucket string, useSSL bool) (*Client, error)

New 创建新的 S3 客户端

func (*Client) Exists

func (c *Client) Exists(key string) (bool, error)

Exists 检查对象是否存在于 S3

func (*Client) Upload

func (c *Client) Upload(
	ctx context.Context,
	filePath string,
	options *UploadOptions,
) (*UploadResult, error)

Upload 上传本地文件到 S3 功能特性: - 自动检测文件 MIME 类型 - 支持 ULID 重命名或保留原文件名 - 支持设置公开可读权限 - 返回完整的访问链接和元数据

type UploadOptions

type UploadOptions struct {
	Directory    string // Directory S3 存储目录路径(可选)
	PreserveName bool   // PreserveName 是否保留原始文件名(默认 false)
}

UploadOptions 上传配置

type UploadResult

type UploadResult struct {
	Key         string // Key S3 对象键名
	URL         string // URL 完整的 S3 访问链接
	Size        int64  // Size 文件大小(字节)
	ContentType string // ContentType 文件 MIME 类型
}

UploadResult 上传结果

Directories

Path Synopsis
example
quick-start command
ulid command
upload command

Jump to

Keyboard shortcuts

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