2 Star 8 Fork 3

BeyondStorage / go-storage

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

go-storage

网站 | 文档 | 社区

Build Status Go dev License go storage dev

一个厂商中立的存储库。

愿景

只需一次编写,即可在任意存储服务中运行。

目标

  • 厂商中立
  • 生产就绪
  • 极致性能

示例

package main

import (
    "log"

    "go.beyondstorage.io/v5/services"
    "go.beyondstorage.io/v5/types"

    // 添加 fs 支持
    _ "go.beyondstorage.io/services/fs/v4"
    // 添加 s3 支持
    _ "go.beyondstorage.io/services/s3/v3"
    // 添加 gcs 支持
    _ "go.beyondstorage.io/services/gcs/v3"
    // 添加 azblob 支持
    _ "go.beyondstorage.io/services/azblob/v3"
    // 更多支持,可在 BeyondStorage 下获取
    _ "go.beyondstorage.io/services/xxx" 
)

func main() {
    // 使用连接字符串初始化 storager
    store, err := services.NewStoragerFromString("s3://bucket_name/path/to/workdir")
    if err != nil {
        log.Fatalf("service init failed: %v", err)
    }

    // 将 io.Reader 中的数据写入 hello.txt
    n, err := store.Write("hello.txt", r, length)

    // 从 hello.txt 中读取数据到 io.Writer
    n, err := store.Read("hello.txt", w)

    // 检查 hello.txt 是否存在并获取其元数据
    o, err := store.Stat("hello.txt")

    // 使用对象的函数获取元数据
    length, ok := o.GetContentLength()
    
    // List 将创建路径下对象的迭代器
    it, err := store.List("path")
    
    for {
    	// 使用迭代器检索下一个对象,直到迭代完成
    	o, err := it.Next()
    	if errors.Is(err, types.IterateDone) {
    		break
        }
    }

    // 删除 hello.txt
    err = store.Delete("hello.txt")
}

更多示例可以在 go-storage-example 找到。

特点

支持多种本地服务

目前已经有 16 个稳定的服务通过了所有的 集成测试

另有 3 个公测版本的服务已实现了所需功能,但还没有通过 集成测试

最后还有 4 个处于内测阶段的服务仍在开发中。

更多关于服务的想法可以在 Service Integration Tracking 找到。

完整且易扩展的接口

基本操作

  • 元数据: 获取 storager 元数据
meta := store.Metadata()
_ := meta.GetWorkDir() // 获取对象的工作目录
_, ok := meta.GetWriteSizeMaximum() // 获取写操作的最大尺寸
  • 读取: 读取 对象 的内容
// 在偏移量 1024 处读取 2048 字节到 io.Writer
n, err := store.Read("path", w, pairs.WithOffset(1024), pairs.WithSize(2048))
  • 写入: 将内容写入 对象
// 从 io.Reader 写入 2048 字节
n, err := store.Write("path", r, 2048)
  • 统计: 获取 对象 元数据并检查是否存在
o, err := store.Stat("path")
if errors.Is(err, services.ErrObjectNotExist) {
	// 对象不存在
}
length, ok := o.GetContentLength() // 获取对象的内容长度
  • 删除: 删除一个 对象
err := store.Delete("path") // 删除对象 "路径"
  • 列表: 列出给定前缀或目录中的 对象
it, err := store.List("path")
for {
	o, err := it.Next()
	if err != nil && errors.Is(err, types.IterateDone) {
        // 列表结束
    }
    length, ok := o.GetContentLength() // 获取对象的内容长度
}

扩展操作

  • 拷贝: 复制一个 对象 到 storager
err := store.(Copier).Copy(src, dst) // 从 src 复制一个对象到 dst
  • 移动: 移动一个 对象 到 storager
err := store.(Mover).Move(src, dst) // 从 src 移动一个对象到 dst
  • 链接: 为 对象 生成一个可访问的公共 url
url, err := store.(Reacher).Reach("path") // 生成一个对象的 url
  • 目录: 对象 目录
o, err := store.(Direr).CreateDir("path") // 创建一个对象目录

大文件操作

  • 分段: 允许进行分段上传
ms := store.(Multiparter)

// 创建一个分段对象
o, err := ms.CreateMultipart("path")
// 将 io.reader 中的 1024 字节分段写入索引 1
n, part, err := ms.WriteMultipart(o, r, 1024, 1)
// 完成分段对象创建
err := ms.CompleteMultipart(o, []*Part{part})
  • 追加: 允许追加到一个对象上
as := store.(Appender)

// 创建一个可追加的对象
o, err := as.CreateAppend("path")
// 从 io.Reader 写入 1024 字节
n, err := as.WriteAppend(o, r, 1024)
// 提交一个待追加的对象
err = as.CommitAppend(o)
  • 块: 允许将一个对象与块 id 进行组合
bs := store.(Blocker)

// 创建一个块对象
o, err := bs.CreateBlock("path")
// 将 io.reader 中的 1024 字节写入 id 为 ”id-abc“ 的块
n, err := bs.WriteBlock(o, r, 1024, "id-abc")
// 通过块 id 组合区块
err := bs.CombineBlock(o, []string{"id-abc"})
  • 页:允许进行随机写入
ps := store.(Pager)

// 创建一个页面对象
o, err := ps.CreatePage("path")
// Write 1024 bytes from io.Reader at offset 2048
n, err := ps.WritePage(o, r, 1024, 2048)

综合元数据

全局对象元数据

  • id: 服务中的唯一键
  • name: 服务工作目录的相对路径
  • mode: 对象的模式可以由以下几种进行组合:read, dir, part 以及 更多
  • etag: 实体标签,定义于 rfc2616
  • content-length: 对象的内容大小
  • content-md5: rfc2616 中定义的 Md5 简介
  • content-type: rfc2616 中定义的媒体类型
  • last-modified: 对象的最后更新时间

系统对象元数据

服务系统对象元数据,如 storage-class 等。

o, err := store.Stat("path")

// 通过 go-service-s3 提供的 API 获取服务系统元数据
om := s3.GetObjectSystemMetadata(o)
_ = om.StorageClass // 此对象的存储类型
_ = om.ServerSideEncryptionCustomerAlgorithm // 此对象的 sse 算法

强类型的接口

自我维护的代码生成器 定义 有助于生成我们所有的 API、pairs 和元数据。

生成的 pairs 可用作 API 的可选参数。

func WithContentMd5(v string) Pair {
    return Pair{
        Key:   "content_md5",
        Value: v,
    }
}

生成的对象元数据可用于从对象中获取内容 md5。

func (o *Object) GetContentMd5() (string, bool) {
    o.stat()
    
    if o.bit&objectIndexContentMd5 != 0 {
        return o.contentMd5, true
    }
    
    return "", false
}

服务器端加密

支持通过 system pair 和 system metadata 指定在服务端对数据进行加密编码, 并且我们可以通过 Default Pairs 来简化工作。


func NewS3SseC(key []byte) (types.Storager, error) {
    defaultPairs := s3.DefaultStoragePairs{
        Write: []types.Pair{
            // 要求密钥的加密算法必须为 AES256
            s3.WithServerSideEncryptionCustomerAlgorithm(s3.ServerSideEncryptionAes256),
            // 你的 AES-256 密钥, 必须具有 32 个字节长度
            s3.WithServerSideEncryptionCustomerKey(key),
        },
        // 现在你必须提供客户密钥才能读取加密数据
        Read: []types.Pair{
            // 要求密钥的加密算法必须为 AES256
            s3.WithServerSideEncryptionCustomerAlgorithm(s3.ServerSideEncryptionAes256),
            // 你的 AES-256 密钥, 必须具有 32 个字节长度
            s3.WithServerSideEncryptionCustomerKey(key),
        }}
    
    return s3.NewStorager(..., s3.WithDefaultStoragePairs(defaultPairs))
}

赞助商

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

A vendor-neutral storage library for Golang. 展开 收起
Go 等 2 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Go
1
https://gitee.com/beyondstorage/go-storage.git
git@gitee.com:beyondstorage/go-storage.git
beyondstorage
go-storage
go-storage
master

搜索帮助