From 7629a37f7708fa9a24c55fd490114922d026bdb3 Mon Sep 17 00:00:00 2001 From: Dmitriy Kharchenko Date: Sun, 24 Nov 2019 11:05:38 +0300 Subject: [PATCH 1/2] Added validation and error checking for incoming updates in ListenForWebhook --- bot.go | 26 ++++++++++++++++++++++++-- helpers.go | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/bot.go b/bot.go index a996790..3bdb49a 100644 --- a/bot.go +++ b/bot.go @@ -533,11 +533,33 @@ func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel { ch := make(chan Update, bot.Buffer) http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - bytes, _ := ioutil.ReadAll(r.Body) + if r.Method != http.MethodPost { + errMsg, _ := json.Marshal(map[string]string{"error": "Wrong HTTP method, required POST"}) + w.WriteHeader(http.StatusMethodNotAllowed) + w.Header().Set("Content-Type", "application/json") + w.Write(errMsg) + return + } + + bytes, err := ioutil.ReadAll(r.Body) + if err != nil { + errMsg, _ := json.Marshal(map[string]string{"error": err.Error()}) + w.WriteHeader(http.StatusBadRequest) + w.Header().Set("Content-Type", "application/json") + w.Write(errMsg) + return + } r.Body.Close() var update Update - json.Unmarshal(bytes, &update) + err = json.Unmarshal(bytes, &update) + if err != nil { + errMsg, _ := json.Marshal(map[string]string{"error": err.Error()}) + w.WriteHeader(http.StatusBadRequest) + w.Header().Set("Content-Type", "application/json") + w.Write(errMsg) + return + } ch <- update }) diff --git a/helpers.go b/helpers.go index 3dabe11..70180bc 100644 --- a/helpers.go +++ b/helpers.go @@ -622,7 +622,7 @@ func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMess ChatID: chatID, MessageID: messageID, }, - Caption: caption, + Caption: caption, } } From b6575a2934b018fc5109ac4b161cc52f51210436 Mon Sep 17 00:00:00 2001 From: Dmitriy Kharchenko <43345312+dmitriy-kharchenko@users.noreply.github.com> Date: Wed, 29 Jul 2020 09:51:11 +0300 Subject: [PATCH 2/2] Added stream processing of input JSON Co-authored-by: TJ Horner --- bot.go | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/bot.go b/bot.go index 5a13ec7..16cdacd 100644 --- a/bot.go +++ b/bot.go @@ -579,17 +579,8 @@ func (bot *BotAPI) HandleUpdate(r *http.Request) (*Update, error) { return nil, err } - payload, err := ioutil.ReadAll(r.Body) - if err != nil { - return nil, err - } - - if err := r.Body.Close(); err != nil { - return nil, err - } - var update Update - err = json.Unmarshal(payload, &update) + err := json.NewDecoder(r.Body).Decode(&update) if err != nil { return nil, err }