Skip to content

Commit

Permalink
Merge pull request tucnak#311 from aofei/v2
Browse files Browse the repository at this point in the history
api: fix a huge memory allocation caused by sendFiles
  • Loading branch information
tucnak authored Jun 13, 2020
2 parents 359b733 + 8b48346 commit aac3d68
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,26 +81,32 @@ func (b *Bot) sendFiles(method string, files map[string]File, params map[string]
return b.Raw(method, params)
}

var buf bytes.Buffer
writer := multipart.NewWriter(&buf)

for field, file := range rawFiles {
if err := addFileToWriter(writer, params["file_name"], field, file); err != nil {
return nil, wrapError(err)
pipeReader, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer pipeWriter.Close()

for field, file := range rawFiles {
if err := addFileToWriter(writer, params["file_name"], field, file); err != nil {
pipeWriter.CloseWithError(wrapError(err))
return
}
}
}
for field, value := range params {
if err := writer.WriteField(field, value); err != nil {
return nil, wrapError(err)
for field, value := range params {
if err := writer.WriteField(field, value); err != nil {
pipeWriter.CloseWithError(wrapError(err))
return
}
}
}
if err := writer.Close(); err != nil {
return nil, wrapError(err)
}
if err := writer.Close(); err != nil {
pipeWriter.CloseWithError(wrapError(err))
return
}
}()

url := b.URL + "/bot" + b.Token + "/" + method

resp, err := b.client.Post(url, writer.FormDataContentType(), &buf)
resp, err := b.client.Post(url, writer.FormDataContentType(), pipeReader)
if err != nil {
return nil, wrapError(err)
}
Expand Down

0 comments on commit aac3d68

Please sign in to comment.