将多个文件上传到后端Go API

时间:2019-08-09 13:23:24

标签: go file-upload graphql react-apollo apollo-client

我有一个后端Go API,可以满足我所有的GraphQL请求。我使用https://github.com/graph-gophers/graphql-go作为它的库。我最近在后端go-graphql-upload和前端apollo-upload-client的帮助下上传了单个文件。但是我不知道如何使多个上载工作。单个上传突变(有效)如下所示:

upload(file: Upload!): Boolean!

..我已将Upload定义为标量类型,并且对go-graphql-upload:scalar.go中的实现感到满意。此突变的解析器如下所示:

func (r *RootResolver) Upload(ctx context.Context, args struct{ File graphqlupload.GraphQLUpload }) (bool, error) {

    reader, err := args.File.CreateReadStream()
    if err != nil {
        return false, errors.Wrap(err, "failed to create read stream")
    }

    // do something with the reader

    return true, nil
}

为了澄清,到目前为止,一切正常

我遇到的问题是使多文件上传正常工作。 那个突变看起来像这样:

uploadMultiple(files: [Upload!]!): Boolean!

...,解析器如下所示:

func (r *RootResolver) UploadMultiple(ctx context.Context, args struct{ Files []graphqlupload.GraphQLUpload }) (bool, error) {
    for _, file := range args.Files {

        reader, err := file.CreateReadStream()
        if err != nil {
            return false, errors.Wrap(err, "failed to create read stream")
        }

        // handle reader
    }

    return true, nil
}

如您所见,我对多个文件的解析器没有做任何特别的事情。问题来自处理多部分请求的中间件。

我得到的错误是:

panic: interface conversion: interface {} is []interface {}, not map[string]interface {}

goroutine 99 [running]:
{my-app}/vendor/github.com/smithaitufe/go-graphql-upload.findField(0xadfec0, 0xc000288000, 0xc0000b2f30, 0x2, 0x3, 0x2)
        {my-app}/vendor/github.com/smithaitufe/go-graphql-upload/middleware.go:180 +0x163
{my-app}/vendor/github.com/smithaitufe/go-graphql-upload.singleTransformation.func1(0xc0004bc090, 0xc000561ee0, 0x11, 0x11e8931, 0x1, 0xc000288000)
        {my-app}/vendor/github.com/smithaitufe/go-graphql-upload/middleware.go:142 +0x129
created by {my-app}/vendor/github.com/smithaitufe/go-graphql-upload.singleTransformation
        {my-app}/vendor/github.com/smithaitufe/go-graphql-upload/middleware.go:132 +0x114
exit status 2

前端库apollo-upload-client包含多个文件正常工作的示例,因此我知道它不是前端。如何更新Go中间件以允许多个文件上载?

0 个答案:

没有答案