all repos — telegram-bot-api @ 5a72ea681439dd22b56ea4c29bd8c58ef52dd751

Golang bindings for the Telegram Bot API

switch to streaming multipart, reduces memory usage for uploads
Syfaro syfaro@foxpaw.in
Mon, 10 Aug 2015 07:41:44 -0500
commit

5a72ea681439dd22b56ea4c29bd8c58ef52dd751

parent

d06eead68daccd87bfdd6a10d289fd47cdeec987

1 files changed, 9 insertions(+), 25 deletions(-)

jump to
M methods.gomethods.go

@@ -1,14 +1,12 @@

package tgbotapi import ( - "bytes" "encoding/json" "errors" "fmt" - "io" + "github.com/technoweenie/multipartstreamer" "io/ioutil" "log" - "mime/multipart" "net/http" "net/url" "os"

@@ -180,46 +178,32 @@ // UploadFile makes a request to the API with a file.

// // Requires the parameter to hold the file not be in the params. func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, filename string) (APIResponse, error) { - var b bytes.Buffer - w := multipart.NewWriter(&b) - f, err := os.Open(filename) if err != nil { return APIResponse{}, err } + defer f.Close() - fw, err := w.CreateFormFile(fieldname, filename) + fi, err := os.Stat(filename) if err != nil { return APIResponse{}, err } - if _, err = io.Copy(fw, f); err != nil { - return APIResponse{}, err - } - - for key, val := range params { - if fw, err = w.CreateFormField(key); err != nil { - return APIResponse{}, err - } - - if _, err = fw.Write([]byte(val)); err != nil { - return APIResponse{}, err - } - } + ms := multipartstreamer.New() + ms.WriteFields(params) + ms.WriteReader(fieldname, f.Name(), fi.Size(), f) - w.Close() - - req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), &b) + req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), nil) + ms.SetupRequest(req) if err != nil { return APIResponse{}, err } - req.Header.Set("Content-Type", w.FormDataContentType()) - res, err := bot.Client.Do(req) if err != nil { return APIResponse{}, err } + defer res.Body.Close() bytes, err := ioutil.ReadAll(res.Body) if err != nil {