api: make sure io.Pipe in sendFiles will be closed

This commit is contained in:
Aofei Sheng 2020-06-16 02:32:19 +08:00
parent 1a9d4b1333
commit a76047869f

10
api.go
View File

@ -88,18 +88,18 @@ func (b *Bot) sendFiles(method string, files map[string]File, params map[string]
for field, file := range rawFiles { for field, file := range rawFiles {
if err := addFileToWriter(writer, params["file_name"], field, file); err != nil { if err := addFileToWriter(writer, params["file_name"], field, file); err != nil {
pipeWriter.CloseWithError(wrapError(err)) pipeWriter.CloseWithError(err)
return return
} }
} }
for field, value := range params { for field, value := range params {
if err := writer.WriteField(field, value); err != nil { if err := writer.WriteField(field, value); err != nil {
pipeWriter.CloseWithError(wrapError(err)) pipeWriter.CloseWithError(err)
return return
} }
} }
if err := writer.Close(); err != nil { if err := writer.Close(); err != nil {
pipeWriter.CloseWithError(wrapError(err)) pipeWriter.CloseWithError(err)
return return
} }
}() }()
@ -108,7 +108,9 @@ func (b *Bot) sendFiles(method string, files map[string]File, params map[string]
resp, err := b.client.Post(url, writer.FormDataContentType(), pipeReader) resp, err := b.client.Post(url, writer.FormDataContentType(), pipeReader)
if err != nil { if err != nil {
return nil, wrapError(err) err = wrapError(err)
pipeReader.CloseWithError(err)
return nil, err
} }
resp.Close = true resp.Close = true
defer resp.Body.Close() defer resp.Body.Close()