print full response when debug

pull/131/head
zhuharev 8 years ago
parent 846d467e14
commit 3cfc52c9c2
No known key found for this signature in database
GPG Key ID: 4B21EFB85BF9CBF5
  1. 41
      bot.go

@ -7,6 +7,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
@ -67,6 +68,15 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse,
} }
defer resp.Body.Close() 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 { if resp.StatusCode == http.StatusForbidden {
return APIResponse{}, errors.New(ErrAPIForbidden) return APIResponse{}, errors.New(ErrAPIForbidden)
} }
@ -75,23 +85,32 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse,
return APIResponse{}, errors.New(http.StatusText(resp.StatusCode)) return APIResponse{}, errors.New(http.StatusText(resp.StatusCode))
} }
bytes, err := ioutil.ReadAll(resp.Body) if !apiResp.Ok {
if err != nil { return apiResp, errors.New(apiResp.Description)
return APIResponse{}, err
} }
if bot.Debug { return apiResp, nil
log.Println(endpoint, string(bytes)) }
func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) {
if !bot.Debug {
dec := json.NewDecoder(responseBody)
err = dec.Decode(resp)
return
} }
var apiResp APIResponse // if debug, read reponse body
json.Unmarshal(bytes, &apiResp) data, err := ioutil.ReadAll(responseBody)
if err != nil {
return
}
if !apiResp.Ok { err = json.Unmarshal(data, resp)
return apiResp, errors.New(apiResp.Description) if err != nil {
return
} }
return apiResp, nil return
} }
// makeMessageRequest makes a request to a method that returns a Message. // makeMessageRequest makes a request to a method that returns a Message.
@ -875,4 +894,4 @@ func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse,
bot.debugLog(config.method(), v, nil) bot.debugLog(config.method(), v, nil)
return bot.MakeRequest(config.method(), v) return bot.MakeRequest(config.method(), v)
} }