-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
76 lines (61 loc) · 1.54 KB
/
request.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
69
70
71
72
73
74
75
76
package cgv
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
)
const CgvAddr = "http://www.cgv.com.cn"
type CommonResponse struct {
SVC_ERR_MSG_TEXT string
RS_MSG string
RS_CD string
ErrorCode int
}
//返回CGV官网指定路径的完整URL
func WrapPath(path string) string {
return CgvAddr + path
}
func request(method, path string, p url.Values, reqInfo interface{}, respInfo interface{}) error {
var body io.Reader
if reqInfo != nil {
dat, err := json.Marshal(reqInfo)
if err != nil {
return fmt.Errorf("编码请求参数失败: ", err)
}
body = bytes.NewReader(dat)
}
req, err := http.NewRequest(method, CgvAddr+path+"?"+p.Encode(), body)
if err != nil {
return fmt.Errorf("创建请求失败: ", err)
}
if reqInfo != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("执行请求失败: ", err)
}
defer resp.Body.Close()
mediaType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if mediaType != "application/json" {
dat, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf(resp.Status + "\n" + string(dat))
}
buf, err := ioutil.ReadAll(resp.Body)
var info CommonResponse
err = json.Unmarshal(buf, &info)
if err != nil {
return fmt.Errorf("解析通用响应失败: %s", err)
}
//TODO: 判断公共响应中的错误
err = json.Unmarshal(buf, respInfo)
if err != nil {
return fmt.Errorf("解析业务响应失败: %s", err)
}
return nil
}