1

我正在为我的 GraphQL API 制作 UT。我需要在上传文件的地方测试突变。我在这个项目上使用 gqlgen。

...
localFile, err := os.Open("./file.xlsx")
if err != nil {
    fmt.Errorf(err.Error())
}

c.MustPost(queries.UPLOAD_CSV, &resp, client.Var("id", id), client.Var("file", localFile), client.AddHeader("Authorization", "Bearer "+hub.AccessToken))

c.MustPost 恐慌并发送错误:

--- FAIL: TestUploadCSV (0.00s)
panic: [{"message":"map[string]interface {} is not an Upload","path":["uploadCSV","file"]}] [recovered]
panic: [{"message":"map[string]interface {} is not an Upload","path":["uploadCSV","file"]}]

如何发送localFile到我的 API?我想过通过 curl 来实现它,但我不确定这是否是一种干净的方式。

4

1 回答 1

1

你不能就os.File这样通过。您需要实际读取文件,构造 MIME 多部分请求正文(请参阅规范)并在 POST 请求中发送。

buf := &bytes.Buffer{}
w := multipart.NewWriter(...)

// add other required fields (operations, map) here

// load file (you can do these directly I am emphasizing them 
// as variables so code below is more understandable
fileKey := "0" // file key in 'map'
fileName := "file.xslx" // file name
fileContentType := "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
fileContents, err := ioutil.ReadFile("./file.xlsx")
// ...

// make multipart body
h := make(textproto.MIMEHeader)

h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fileKey, fileName))
h.Set("Content-Type", fileContentType)
ff, err := bodyWriter.CreatePart(h)
// ...
_, err = ff.Write(fileContents)
// ...
err = bodyWriter.Close()
// ...

req, err := http.NewRequest("POST", fmt.Sprintf("https://endpoint"), buf)
//...

gqlgen在存储库本身中有一个很好的工作示例: example/fileupload/fileupload_test.go

在该示例中,每个文件都加载到(并由)file在我链接的行上定义的结构类型中,这可能会让人乍一看有点混乱。

于 2021-01-28T02:18:19.833 回答