From dfb663a6e08dc9fb51879bb10a56c37c5a4ecc88 Mon Sep 17 00:00:00 2001 From: HFO4 <912394456@qq.com> Date: Wed, 29 Apr 2020 10:37:15 +0800 Subject: [PATCH] Feat: List files in Qiniu bucket --- pkg/filesystem/driver/qiniu/handler.go | 76 +++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 2 deletions(-) diff --git a/pkg/filesystem/driver/qiniu/handler.go b/pkg/filesystem/driver/qiniu/handler.go index 316b65e..355e466 100644 --- a/pkg/filesystem/driver/qiniu/handler.go +++ b/pkg/filesystem/driver/qiniu/handler.go @@ -14,6 +14,9 @@ import ( "io" "net/http" "net/url" + "path" + "path/filepath" + "strings" "time" ) @@ -22,8 +25,77 @@ type Driver struct { Policy *model.Policy } -func (handler Driver) List(ctx context.Context, path string, recursive bool) ([]response.Object, error) { - panic("implement me") +// List 列出给定路径下的文件 +func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) { + base = strings.TrimPrefix(base, "/") + if base != "" { + base += "/" + } + + var ( + delimiter string + marker string + objects []storage.ListItem + commons []string + ) + if !recursive { + delimiter = "/" + } + + mac := qbox.NewMac(handler.Policy.AccessKey, handler.Policy.SecretKey) + cfg := storage.Config{ + UseHTTPS: true, + } + bucketManager := storage.NewBucketManager(mac, &cfg) + + for { + entries, folders, nextMarker, hashNext, err := bucketManager.ListFiles( + handler.Policy.BucketName, + base, delimiter, marker, 1000) + if err != nil { + return nil, err + } + objects = append(objects, entries...) + commons = append(commons, folders...) + if !hashNext { + break + } + marker = nextMarker + } + + // 处理列取结果 + res := make([]response.Object, 0, len(objects)+len(commons)) + // 处理目录 + for _, object := range commons { + rel, err := filepath.Rel(base, 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(base, 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.Fsize), + IsDir: false, + LastModify: time.Now(), + }) + } + + return res, nil } // Get 获取文件