/
HttpHelper.go
68 lines (60 loc) · 2.31 KB
/
HttpHelper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package helper
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
apiResp "github.com/emacsist/golang-weibo-sdk/resp"
"github.com/emacsist/golang-weibo-sdk/url"
"github.com/Sirupsen/logrus"
)
// APIGet : API中get请求返回string的helper方法
func APIGet(URL string) (string, *apiResp.ErrorResp) {
resp, err := http.Get(URL)
if err != nil {
// if error
logrus.Warnf("get[%v] falied. reason : %v", URL, err.Error())
return "", &apiResp.ErrorResp{Error: err.Error(), ErrorCode: apiResp.NetWorkErrorCode, Request: apiResp.NetWorkErrorCodeMsg}
}
return respToString(resp)
}
// APIPost : API中post请求返回string的helper方法
func APIPost(URL string, paramBody string) (string, *apiResp.ErrorResp) {
resp, err := http.Post(URL, url.ContentTypeURLEncoded, strings.NewReader(paramBody))
if err != nil {
// if error
logrus.Warnf("post[url=%v, param=%v] falied. reason : %v\n", URL, paramBody, err.Error())
return "", &apiResp.ErrorResp{Error: err.Error(), ErrorCode: apiResp.NetWorkErrorCode, Request: apiResp.NetWorkErrorCodeMsg}
}
return respToString(resp)
}
// APIPostMultiPart : 带上传文件的post请求
func APIPostMultiPart(req *http.Request) (string, *apiResp.ErrorResp) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// if error
logrus.Warnf("post[url=%v, param=%v] falied. reason : %v\n", req.RequestURI, req.ParseForm(), err.Error())
return "", &apiResp.ErrorResp{Error: err.Error(), ErrorCode: apiResp.NetWorkErrorCode, Request: apiResp.NetWorkErrorCodeMsg}
}
return respToString(resp)
}
func respToString(resp *http.Response) (string, *apiResp.ErrorResp) {
defer resp.Body.Close()
//OK
body, error := ioutil.ReadAll(resp.Body)
if error != nil {
logrus.Warnf("read searchStatusesLimited Response error : %v", error.Error())
return "", &apiResp.ErrorResp{Error: error.Error(), ErrorCode: apiResp.IOErrorCode, Request: apiResp.IOErrorCodeMsg}
}
if resp.StatusCode != 200 {
var apiRespError apiResp.ErrorResp
jsonError := json.Unmarshal(body, &apiRespError)
if jsonError == nil {
//转换为json不出错的话,表示是微博的error_code
return "", &apiRespError
}
return "", &apiResp.ErrorResp{Error: string(body), ErrorCode: resp.StatusCode, Request: resp.Request.URL.Host + resp.Request.URL.RequestURI()}
}
return string(body), nil
}