提交 cfaf2092 编写于 作者: H HFO4

Feat: List files in COS bucket

上级 305497e7
...@@ -18,6 +18,9 @@ import ( ...@@ -18,6 +18,9 @@ import (
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"path"
"path/filepath"
"strings"
"time" "time"
) )
...@@ -46,8 +49,78 @@ type Driver struct { ...@@ -46,8 +49,78 @@ type Driver struct {
HTTPClient request.Client HTTPClient request.Client
} }
func (handler Driver) List(ctx context.Context, path string, recursive bool) ([]response.Object, error) { // List 列出COS文件
panic("implement me") func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) {
// 初始化列目录参数
opt := &cossdk.BucketGetOptions{
Prefix: strings.TrimPrefix(base, "/"),
EncodingType: "",
MaxKeys: 1000,
}
// 是否为递归列出
if !recursive {
opt.Delimiter = "/"
}
// 手动补齐结尾的slash
if opt.Prefix != "" {
opt.Prefix += "/"
}
var (
marker string
objects []cossdk.Object
commons []string
)
for {
res, _, err := handler.Client.Bucket.Get(ctx, opt)
if err != nil {
return nil, err
}
objects = append(objects, res.Contents...)
commons = append(commons, res.CommonPrefixes...)
// 如果本次未列取完,则继续使用marker获取结果
marker = res.NextMarker
// marker 为空时结果列取完毕,跳出
if marker == "" {
break
}
}
// 处理列取结果
res := make([]response.Object, 0, len(objects)+len(commons))
// 处理目录
for _, object := range commons {
rel, err := filepath.Rel(opt.Prefix, object)
if err != nil {
continue
}
res = append(res, response.Object{
Name: path.Base(object),
RelativePath: filepath.ToSlash(rel),
Size: 0,
IsDir: true,
LastModify: time.Now(),
})
}
// 处理文件
for _, object := range objects {
rel, err := filepath.Rel(opt.Prefix, object.Key)
if err != nil {
continue
}
res = append(res, response.Object{
Name: path.Base(object.Key),
Source: object.Key,
RelativePath: filepath.ToSlash(rel),
Size: uint64(object.Size),
IsDir: false,
LastModify: time.Now(),
})
}
return res, nil
} }
// CORS 创建跨域策略 // CORS 创建跨域策略
......
...@@ -110,15 +110,19 @@ func (handler Driver) List(ctx context.Context, base string, recursive bool) ([] ...@@ -110,15 +110,19 @@ func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]
// 列取文件 // 列取文件
base = strings.TrimPrefix(base, "/") base = strings.TrimPrefix(base, "/")
delimiter := "" if base != "" {
if !recursive { base += "/"
delimiter = "/"
} }
marker := ""
var ( var (
objects []oss.ObjectProperties delimiter string
commons []string marker string
objects []oss.ObjectProperties
commons []string
) )
if !recursive {
delimiter = "/"
}
for { for {
subRes, err := handler.bucket.ListObjects(oss.Marker(marker), oss.Prefix(base), subRes, err := handler.bucket.ListObjects(oss.Marker(marker), oss.Prefix(base),
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册