From 3cfc52c9c2c86b6df6a0b54d25c634abd9487cf4 Mon Sep 17 00:00:00 2001 From: zhuharev Date: Mon, 30 Oct 2017 00:03:48 +0300 Subject: [PATCH] print full response when debug --- bot.go | 45 ++++++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/bot.go b/bot.go index 2d95f9e..2a69a33 100644 --- a/bot.go +++ b/bot.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "io/ioutil" "log" "net/http" @@ -67,6 +68,15 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, } defer resp.Body.Close() + var apiResp APIResponse + bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp) + if err != nil { + return apiResp, err + } + if bot.Debug { + log.Printf("%s %s", endpoint, bytes) + } + if resp.StatusCode == http.StatusForbidden { return APIResponse{}, errors.New(ErrAPIForbidden) } @@ -75,18 +85,6 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, return APIResponse{}, errors.New(http.StatusText(resp.StatusCode)) } - bytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - return APIResponse{}, err - } - - if bot.Debug { - log.Println(endpoint, string(bytes)) - } - - var apiResp APIResponse - json.Unmarshal(bytes, &apiResp) - if !apiResp.Ok { return apiResp, errors.New(apiResp.Description) } @@ -94,6 +92,27 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, return apiResp, nil } +func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) { + if !bot.Debug { + dec := json.NewDecoder(responseBody) + err = dec.Decode(resp) + return + } + + // if debug, read reponse body + data, err := ioutil.ReadAll(responseBody) + if err != nil { + return + } + + err = json.Unmarshal(data, resp) + if err != nil { + return + } + + return +} + // makeMessageRequest makes a request to a method that returns a Message. func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) { resp, err := bot.MakeRequest(endpoint, params) @@ -875,4 +894,4 @@ func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) -} \ No newline at end of file +}