-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclient.go
137 lines (112 loc) · 2.16 KB
/
httpclient.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package api
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// MyError ...
type MyError struct {
Code string `json:"code"`
Message string `json:"message"`
}
// Get ...
func Get(url string, out interface{}) error {
resp, err := http.Get(url)
if err != nil {
return err
}
if resp != nil {
defer resp.Body.Close()
}
resp.Request.Close = true
return parseResp(resp, out)
}
// PostForm ...
func PostForm(url string, data url.Values, out interface{}) error {
resp, err := http.PostForm(url, data)
if err != nil {
return err
}
if resp != nil {
defer resp.Body.Close()
}
resp.Request.Close = true
return parseResp(resp, out)
}
// Patch ...
func Patch(url string, data url.Values, out interface{}) error {
req, err := http.NewRequest("PATCH", url, strings.NewReader(data.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
c := &http.Client{}
resp, err := c.Do(req)
if err != nil {
return err
}
if resp != nil {
defer resp.Body.Close()
resp.Request.Close = true
}
return parseResp(resp, out)
}
// Delete ...
func Delete(url string) error {
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
c := &http.Client{}
resp, err := c.Do(req)
if err != nil {
return err
}
if resp != nil {
defer resp.Body.Close()
}
resp.Request.Close = true
if resp.StatusCode == 204 {
return nil
}
return fmt.Errorf("未知错误[%d]", resp.StatusCode)
}
func parseResp(resp *http.Response, out interface{}) error {
if resp == nil {
return errors.New("resp is nil")
}
switch resp.StatusCode {
case 200:
if out == nil {
return nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(b, &out)
if err != nil {
return err
}
return nil
case 201, 202, 204:
return nil
case 400, 401, 404, 500:
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
e := &MyError{}
err = json.Unmarshal(b, e)
if err != nil {
return err
}
return errors.New(e.Code)
default:
return fmt.Errorf("不支持的状态码[%d]", resp.StatusCode)
}
}