/
myclient.go
88 lines (76 loc) · 1.53 KB
/
myclient.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
package myhttp
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"strings"
)
// 主要用于 爬虫
type MyHttpClient struct {
client *http.Client
}
// NewHttpClient 创建http client实例
func NewMyHttpClient() *MyHttpClient {
cookieJar, _ := cookiejar.New(nil)
return &MyHttpClient{
client: &http.Client{
Jar: cookieJar,
},
}
}
func (c *MyHttpClient) GetClient() *http.Client {
return c.client
}
// SendPost 发送POST请求
func (c *MyHttpClient) SendPost(url string, params string, responseBody interface{}) error {
req, err := http.NewRequest("POST", url, strings.NewReader(params))
if err != nil {
return err
}
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
switch v := responseBody.(type) {
case *string:
*v = string(body)
default:
err = json.Unmarshal(body, responseBody)
if err != nil {
return err
}
}
return nil
}
// SendPost 发送POST请求
func (c *MyHttpClient) SendGet(url string, params string, responseBody interface{}) error {
req, err := http.NewRequest("GET", url, strings.NewReader(params))
if err != nil {
return err
}
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
switch v := responseBody.(type) {
case *string:
*v = string(body)
default:
err = json.Unmarshal(body, responseBody)
if err != nil {
return err
}
}
return nil
}