From 86496a8046698f16bff4a1889dea459bdd852dbe Mon Sep 17 00:00:00 2001 From: Patrick Peng Sun Date: Thu, 11 May 2017 02:21:32 +1000 Subject: [PATCH] added API call error message retrieval (not tested) --- todo.tasks | 2 ++ wechatApiError.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 todo.tasks create mode 100644 wechatApiError.go diff --git a/todo.tasks b/todo.tasks new file mode 100644 index 0000000..3429ede --- /dev/null +++ b/todo.tasks @@ -0,0 +1,2 @@ +wechatApiError: + ☐ test get JSON error message when api call happened diff --git a/wechatApiError.go b/wechatApiError.go new file mode 100644 index 0000000..1173cd6 --- /dev/null +++ b/wechatApiError.go @@ -0,0 +1,39 @@ +package main + +import ( + "encoding/json" + "net/http" + "strconv" +) + +//WechatError when API call goes wrong, it shows error message +type WechatError struct { + ErrCode int64 `json:"errcode"` + ErrMsg string `json:"errmsg"` +} + +//getWechatAPIError given an http body, try to decode json error +// caller needs to makesure content type is json +//return +// the error strucutre, on success +// err: if json decode encounters problem +func getWechatAPIError(respBody string) (result WechatError, err error) { + err = json.Unmarshal([]byte(respBody), &result) + return +} + +//see if a http response is json response +func isJSON(r *http.Response) bool { + contentType := r.Header.Get("Content-Type") + contentLen := r.Header.Get("Content-Length") + len, _ := strconv.Atoi(contentLen) + + if contentType == "text/plain" || contentType == "text/json" { + if len < 10240 { //less than 10K + return true + } + } + return false +} + +//To Do: test error message @todo